@vkontakte/videoplayer-core 2.0.123 → 2.0.124-dev.09b35b2f.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 +22 -22
- package/es2015.esm.js +21 -21
- package/es2018.cjs.js +23 -23
- package/es2018.esm.js +22 -22
- package/esnext.cjs.js +24 -24
- package/esnext.esm.js +26 -26
- package/evergreen.esm.js +23 -23
- package/package.json +2 -2
- package/types/providers/DashProvider/lib/buffer.d.ts +2 -2
- package/types/providers/DashProvider/lib/parsers/mpeg/BoxTypeEnum.d.ts +3 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/box.d.ts +0 -5
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/avc1.d.ts +8 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/index.d.ts +3 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mdia.d.ts +2 -1
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/minf.d.ts +2 -1
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moof.d.ts +2 -1
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moov.d.ts +2 -1
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/proj.d.ts +2 -1
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/stbl.d.ts +8 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/stsd.d.ts +11 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/sv3d.d.ts +2 -1
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/traf.d.ts +2 -1
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/trak.d.ts +2 -1
- package/types/providers/DashProvider/lib/player.d.ts +1 -0
- package/types/providers/utils/HTMLVideoElement/TextTrackManager.d.ts +2 -0
- package/types/providers/utils/StallsManager.d.ts +1 -0
- package/types/utils/tuningConfig.d.ts +2 -1
package/es2015.cjs.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.124-dev.09b35b2f.0
|
|
3
|
+
* Tue, 04 Feb 2025 19:22:54 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-124/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var DS=Object.create;var Ii=Object.defineProperty,CS=Object.defineProperties,OS=Object.getOwnPropertyDescriptor,VS=Object.getOwnPropertyDescriptors,BS=Object.getOwnPropertyNames,us=Object.getOwnPropertySymbols,_S=Object.getPrototypeOf,Mn=Object.prototype.hasOwnProperty,ac=Object.prototype.propertyIsEnumerable;var NS=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var bt=Math.pow,ic=(a,e,t)=>e in a?Ii(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,A=(a,e)=>{for(var t in e||(e={}))Mn.call(e,t)&&ic(a,t,e[t]);if(us)for(var t of us(e))ac.call(e,t)&&ic(a,t,e[t]);return a},N=(a,e)=>CS(a,VS(e));var sc=(a,e)=>{var t={};for(var r in a)Mn.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&us)for(var r of us(a))e.indexOf(r)<0&&ac.call(a,r)&&(t[r]=a[r]);return t};var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),FS=(a,e)=>{for(var t in e)Ii(a,t,{get:e[t],enumerable:!0})},nc=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of BS(e))!Mn.call(a,i)&&i!==t&&Ii(a,i,{get:()=>e[i],enumerable:!(r=OS(e,i))||r.enumerable});return a};var K=(a,e,t)=>(t=a!=null?DS(_S(a)):{},nc(e||!a||!a.__esModule?Ii(t,"default",{value:a,enumerable:!0}):t,a)),qS=a=>nc(Ii({},"__esModule",{value:!0}),a);var $=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),Dn=function(a,e){this[0]=a,this[1]=e},ge=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof Dn,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[NS("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var me=b((On,oc)=>{"use strict";var xi=function(a){return a&&a.Math===Math&&a};oc.exports=xi(typeof globalThis=="object"&&globalThis)||xi(typeof window=="object"&&window)||xi(typeof self=="object"&&self)||xi(typeof global=="object"&&global)||xi(typeof On=="object"&&On)||function(){return this}()||Function("return this")()});var Pe=b((v$,uc)=>{"use strict";uc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Pi=b((S$,lc)=>{"use strict";var US=Pe();lc.exports=!US(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Vn=b((y$,hc)=>{"use strict";var HS=Pi(),pc=Function.prototype,cc=pc.apply,dc=pc.call;hc.exports=typeof Reflect=="object"&&Reflect.apply||(HS?dc.bind(cc):function(){return dc.apply(cc,arguments)})});var Se=b((T$,bc)=>{"use strict";var fc=Pi(),mc=Function.prototype,Bn=mc.call,jS=fc&&mc.bind.bind(Bn,Bn);bc.exports=fc?jS:function(a){return function(){return Bn.apply(a,arguments)}}});var fr=b((I$,vc)=>{"use strict";var gc=Se(),GS=gc({}.toString),QS=gc("".slice);vc.exports=function(a){return QS(GS(a),8,-1)}});var _n=b((E$,Sc)=>{"use strict";var WS=fr(),YS=Se();Sc.exports=function(a){if(WS(a)==="Function")return YS(a)}});var he=b((x$,yc)=>{"use strict";var Nn=typeof document=="object"&&document.all;yc.exports=typeof Nn=="undefined"&&Nn!==void 0?function(a){return typeof a=="function"||a===Nn}:function(a){return typeof a=="function"}});var Ue=b((P$,Tc)=>{"use strict";var zS=Pe();Tc.exports=!zS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var He=b((w$,Ic)=>{"use strict";var KS=Pi(),ds=Function.prototype.call;Ic.exports=KS?ds.bind(ds):function(){return ds.apply(ds,arguments)}});var Fn=b(Pc=>{"use strict";var Ec={}.propertyIsEnumerable,xc=Object.getOwnPropertyDescriptor,XS=xc&&!Ec.call({1:2},1);Pc.f=XS?function(e){var t=xc(this,e);return!!t&&t.enumerable}:Ec});var wi=b((k$,wc)=>{"use strict";wc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var kc=b((R$,Ac)=>{"use strict";var JS=Se(),ZS=Pe(),ey=fr(),qn=Object,ty=JS("".split);Ac.exports=ZS(function(){return!qn("z").propertyIsEnumerable(0)})?function(a){return ey(a)==="String"?ty(a,""):qn(a)}:qn});var _r=b(($$,Rc)=>{"use strict";Rc.exports=function(a){return a==null}});var zt=b((L$,$c)=>{"use strict";var ry=_r(),iy=TypeError;$c.exports=function(a){if(ry(a))throw new iy("Can't call method on "+a);return a}});var mr=b((M$,Lc)=>{"use strict";var ay=kc(),sy=zt();Lc.exports=function(a){return ay(sy(a))}});var je=b((D$,Mc)=>{"use strict";var ny=he();Mc.exports=function(a){return typeof a=="object"?a!==null:ny(a)}});var Nr=b((C$,Dc)=>{"use strict";Dc.exports={}});var At=b((O$,Oc)=>{"use strict";var Un=Nr(),Hn=me(),oy=he(),Cc=function(a){return oy(a)?a:void 0};Oc.exports=function(a,e){return arguments.length<2?Cc(Un[a])||Cc(Hn[a]):Un[a]&&Un[a][e]||Hn[a]&&Hn[a][e]}});var Ai=b((V$,Vc)=>{"use strict";var uy=Se();Vc.exports=uy({}.isPrototypeOf)});var br=b((B$,Nc)=>{"use strict";var ly=me(),Bc=ly.navigator,_c=Bc&&Bc.userAgent;Nc.exports=_c?String(_c):""});var Gn=b((_$,Gc)=>{"use strict";var jc=me(),jn=br(),Fc=jc.process,qc=jc.Deno,Uc=Fc&&Fc.versions||qc&&qc.version,Hc=Uc&&Uc.v8,nt,ps;Hc&&(nt=Hc.split("."),ps=nt[0]>0&&nt[0]<4?1:+(nt[0]+nt[1]));!ps&&jn&&(nt=jn.match(/Edge\/(\d+)/),(!nt||nt[1]>=74)&&(nt=jn.match(/Chrome\/(\d+)/),nt&&(ps=+nt[1])));Gc.exports=ps});var Qn=b((N$,Wc)=>{"use strict";var Qc=Gn(),cy=Pe(),dy=me(),py=dy.String;Wc.exports=!!Object.getOwnPropertySymbols&&!cy(function(){var a=Symbol("symbol detection");return!py(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Qc&&Qc<41})});var Wn=b((F$,Yc)=>{"use strict";var hy=Qn();Yc.exports=hy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Yn=b((q$,zc)=>{"use strict";var fy=At(),my=he(),by=Ai(),gy=Wn(),vy=Object;zc.exports=gy?function(a){return typeof a=="symbol"}:function(a){var e=fy("Symbol");return my(e)&&by(e.prototype,vy(a))}});var ki=b((U$,Kc)=>{"use strict";var Sy=String;Kc.exports=function(a){try{return Sy(a)}catch(e){return"Object"}}});var gt=b((H$,Xc)=>{"use strict";var yy=he(),Ty=ki(),Iy=TypeError;Xc.exports=function(a){if(yy(a))return a;throw new Iy(Ty(a)+" is not a function")}});var Ri=b((j$,Jc)=>{"use strict";var Ey=gt(),xy=_r();Jc.exports=function(a,e){var t=a[e];return xy(t)?void 0:Ey(t)}});var ed=b((G$,Zc)=>{"use strict";var zn=He(),Kn=he(),Xn=je(),Py=TypeError;Zc.exports=function(a,e){var t,r;if(e==="string"&&Kn(t=a.toString)&&!Xn(r=zn(t,a))||Kn(t=a.valueOf)&&!Xn(r=zn(t,a))||e!=="string"&&Kn(t=a.toString)&&!Xn(r=zn(t,a)))return r;throw new Py("Can't convert object to primitive value")}});var ot=b((Q$,td)=>{"use strict";td.exports=!0});var ad=b((W$,id)=>{"use strict";var rd=me(),wy=Object.defineProperty;id.exports=function(a,e){try{wy(rd,a,{value:e,configurable:!0,writable:!0})}catch(t){rd[a]=e}return e}});var $i=b((Y$,od)=>{"use strict";var Ay=ot(),ky=me(),Ry=ad(),sd="__core-js_shared__",nd=od.exports=ky[sd]||Ry(sd,{});(nd.versions||(nd.versions=[])).push({version:"3.38.0",mode:Ay?"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 Jn=b((z$,ld)=>{"use strict";var ud=$i();ld.exports=function(a,e){return ud[a]||(ud[a]=e||{})}});var Fr=b((K$,cd)=>{"use strict";var $y=zt(),Ly=Object;cd.exports=function(a){return Ly($y(a))}});var ut=b((X$,dd)=>{"use strict";var My=Se(),Dy=Fr(),Cy=My({}.hasOwnProperty);dd.exports=Object.hasOwn||function(e,t){return Cy(Dy(e),t)}});var Zn=b((J$,pd)=>{"use strict";var Oy=Se(),Vy=0,By=Math.random(),_y=Oy(1 .toString);pd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+_y(++Vy+By,36)}});var we=b((Z$,fd)=>{"use strict";var Ny=me(),Fy=Jn(),hd=ut(),qy=Zn(),Uy=Qn(),Hy=Wn(),qr=Ny.Symbol,eo=Fy("wks"),jy=Hy?qr.for||qr:qr&&qr.withoutSetter||qy;fd.exports=function(a){return hd(eo,a)||(eo[a]=Uy&&hd(qr,a)?qr[a]:jy("Symbol."+a)),eo[a]}});var vd=b((eL,gd)=>{"use strict";var Gy=He(),md=je(),bd=Yn(),Qy=Ri(),Wy=ed(),Yy=we(),zy=TypeError,Ky=Yy("toPrimitive");gd.exports=function(a,e){if(!md(a)||bd(a))return a;var t=Qy(a,Ky),r;if(t){if(e===void 0&&(e="default"),r=Gy(t,a,e),!md(r)||bd(r))return r;throw new zy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Wy(a,e)}});var to=b((tL,Sd)=>{"use strict";var Xy=vd(),Jy=Yn();Sd.exports=function(a){var e=Xy(a,"string");return Jy(e)?e:e+""}});var hs=b((rL,Td)=>{"use strict";var Zy=me(),yd=je(),ro=Zy.document,eT=yd(ro)&&yd(ro.createElement);Td.exports=function(a){return eT?ro.createElement(a):{}}});var io=b((iL,Id)=>{"use strict";var tT=Ue(),rT=Pe(),iT=hs();Id.exports=!tT&&!rT(function(){return Object.defineProperty(iT("div"),"a",{get:function(){return 7}}).a!==7})});var Pd=b(xd=>{"use strict";var aT=Ue(),sT=He(),nT=Fn(),oT=wi(),uT=mr(),lT=to(),cT=ut(),dT=io(),Ed=Object.getOwnPropertyDescriptor;xd.f=aT?Ed:function(e,t){if(e=uT(e),t=lT(t),dT)try{return Ed(e,t)}catch(r){}if(cT(e,t))return oT(!sT(nT.f,e,t),e[t])}});var ao=b((sL,wd)=>{"use strict";var pT=Pe(),hT=he(),fT=/#|\.prototype\./,Li=function(a,e){var t=bT[mT(a)];return t===vT?!0:t===gT?!1:hT(e)?pT(e):!!e},mT=Li.normalize=function(a){return String(a).replace(fT,".").toLowerCase()},bT=Li.data={},gT=Li.NATIVE="N",vT=Li.POLYFILL="P";wd.exports=Li});var Ur=b((nL,kd)=>{"use strict";var Ad=_n(),ST=gt(),yT=Pi(),TT=Ad(Ad.bind);kd.exports=function(a,e){return ST(a),e===void 0?a:yT?TT(a,e):function(){return a.apply(e,arguments)}}});var so=b((oL,Rd)=>{"use strict";var IT=Ue(),ET=Pe();Rd.exports=IT&&ET(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var vt=b((uL,$d)=>{"use strict";var xT=je(),PT=String,wT=TypeError;$d.exports=function(a){if(xT(a))return a;throw new wT(PT(a)+" is not an object")}});var gr=b(Md=>{"use strict";var AT=Ue(),kT=io(),RT=so(),fs=vt(),Ld=to(),$T=TypeError,no=Object.defineProperty,LT=Object.getOwnPropertyDescriptor,oo="enumerable",uo="configurable",lo="writable";Md.f=AT?RT?function(e,t,r){if(fs(e),t=Ld(t),fs(r),typeof e=="function"&&t==="prototype"&&"value"in r&&lo in r&&!r[lo]){var i=LT(e,t);i&&i[lo]&&(e[t]=r.value,r={configurable:uo in r?r[uo]:i[uo],enumerable:oo in r?r[oo]:i[oo],writable:!1})}return no(e,t,r)}:no:function(e,t,r){if(fs(e),t=Ld(t),fs(r),kT)try{return no(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new $T("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Hr=b((cL,Dd)=>{"use strict";var MT=Ue(),DT=gr(),CT=wi();Dd.exports=MT?function(a,e,t){return DT.f(a,e,CT(1,t))}:function(a,e,t){return a[e]=t,a}});var be=b((dL,Od)=>{"use strict";var Mi=me(),OT=Vn(),VT=_n(),BT=he(),_T=Pd().f,NT=ao(),jr=Nr(),FT=Ur(),Gr=Hr(),Cd=ut();$i();var qT=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 OT(a,this,arguments)};return e.prototype=a.prototype,e};Od.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Mi:i?Mi[t]:Mi[t]&&Mi[t].prototype,o=r?jr:jr[t]||Gr(jr,t,{})[t],u=o.prototype,l,c,d,p,h,m,g,v,T;for(p in e)l=NT(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Cd(n,p),m=o[p],c&&(a.dontCallGetSet?(T=_T(n,p),g=T&&T.value):g=n[p]),h=c&&g?g:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?v=FT(h,Mi):a.wrap&&c?v=qT(h):s&&BT(h)?v=VT(h):v=h,(a.sham||h&&h.sham||m&&m.sham)&&Gr(v,"sham",!0),Gr(o,p,v),s&&(d=t+"Prototype",Cd(jr,d)||Gr(jr,d,{}),Gr(jr[d],p,h),a.real&&u&&(l||!u[p])&&Gr(u,p,h)))}});var Bd=b((pL,Vd)=>{"use strict";var UT=Math.ceil,HT=Math.floor;Vd.exports=Math.trunc||function(e){var t=+e;return(t>0?HT:UT)(t)}});var Di=b((hL,_d)=>{"use strict";var jT=Bd();_d.exports=function(a){var e=+a;return e!==e||e===0?0:jT(e)}});var Fd=b((fL,Nd)=>{"use strict";var GT=Di(),QT=Math.max,WT=Math.min;Nd.exports=function(a,e){var t=GT(a);return t<0?QT(t+e,0):WT(t,e)}});var co=b((mL,qd)=>{"use strict";var YT=Di(),zT=Math.min;qd.exports=function(a){var e=YT(a);return e>0?zT(e,9007199254740991):0}});var Qr=b((bL,Ud)=>{"use strict";var KT=co();Ud.exports=function(a){return KT(a.length)}});var po=b((gL,jd)=>{"use strict";var XT=mr(),JT=Fd(),ZT=Qr(),Hd=function(a){return function(e,t,r){var i=XT(e),s=ZT(i);if(s===0)return!a&&-1;var n=JT(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}};jd.exports={includes:Hd(!0),indexOf:Hd(!1)}});var Ci=b((vL,Gd)=>{"use strict";Gd.exports=function(){}});var Qd=b(()=>{"use strict";var eI=be(),tI=po().includes,rI=Pe(),iI=Ci(),aI=rI(function(){return!Array(1).includes()});eI({target:"Array",proto:!0,forced:aI},{includes:function(e){return tI(this,e,arguments.length>1?arguments[1]:void 0)}});iI("includes")});var Kt=b((TL,Wd)=>{"use strict";var sI=At();Wd.exports=sI});var zd=b((IL,Yd)=>{"use strict";Qd();var nI=Kt();Yd.exports=nI("Array","includes")});var Xd=b((EL,Kd)=>{"use strict";var oI=zd();Kd.exports=oI});var lt=b((xL,Jd)=>{"use strict";var uI=Xd();Jd.exports=uI});var bs=b((OL,tp)=>{"use strict";var cI=Jn(),dI=Zn(),ep=cI("keys");tp.exports=function(a){return ep[a]||(ep[a]=dI(a))}});var ip=b((VL,rp)=>{"use strict";var pI=Pe();rp.exports=!pI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var gs=b((BL,sp)=>{"use strict";var hI=ut(),fI=he(),mI=Fr(),bI=bs(),gI=ip(),ap=bI("IE_PROTO"),ho=Object,vI=ho.prototype;sp.exports=gI?ho.getPrototypeOf:function(a){var e=mI(a);if(hI(e,ap))return e[ap];var t=e.constructor;return fI(t)&&e instanceof t?t.prototype:e instanceof ho?vI:null}});var vs=b((_L,np)=>{"use strict";np.exports={}});var lp=b((NL,up)=>{"use strict";var SI=Se(),fo=ut(),yI=mr(),TI=po().indexOf,II=vs(),op=SI([].push);up.exports=function(a,e){var t=yI(a),r=0,i=[],s;for(s in t)!fo(II,s)&&fo(t,s)&&op(i,s);for(;e.length>r;)fo(t,s=e[r++])&&(~TI(i,s)||op(i,s));return i}});var mo=b((FL,cp)=>{"use strict";cp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var bo=b((qL,dp)=>{"use strict";var EI=lp(),xI=mo();dp.exports=Object.keys||function(e){return EI(e,xI)}});var go=b((UL,bp)=>{"use strict";var hp=Ue(),PI=Pe(),fp=Se(),wI=gs(),AI=bo(),kI=mr(),RI=Fn().f,mp=fp(RI),$I=fp([].push),LI=hp&&PI(function(){var a=Object.create(null);return a[2]=2,!mp(a,2)}),pp=function(a){return function(e){for(var t=kI(e),r=AI(t),i=LI&&wI(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!hp||(i?u in t:mp(t,u)))&&$I(o,a?[u,t[u]]:t[u]);return o}};bp.exports={entries:pp(!0),values:pp(!1)}});var gp=b(()=>{"use strict";var MI=be(),DI=go().entries;MI({target:"Object",stat:!0},{entries:function(e){return DI(e)}})});var Sp=b((GL,vp)=>{"use strict";gp();var CI=Nr();vp.exports=CI.Object.entries});var Tp=b((QL,yp)=>{"use strict";var OI=Sp();yp.exports=OI});var Wr=b((WL,Ip)=>{"use strict";var VI=Tp();Ip.exports=VI});var vr=b((YL,Ep)=>{"use strict";Ep.exports={}});var wp=b((zL,Pp)=>{"use strict";var BI=me(),_I=he(),xp=BI.WeakMap;Pp.exports=_I(xp)&&/native code/.test(String(xp))});var To=b((KL,Rp)=>{"use strict";var NI=wp(),kp=me(),FI=je(),qI=Hr(),vo=ut(),So=$i(),UI=bs(),HI=vs(),Ap="Object already initialized",yo=kp.TypeError,jI=kp.WeakMap,Ss,Oi,ys,GI=function(a){return ys(a)?Oi(a):Ss(a,{})},QI=function(a){return function(e){var t;if(!FI(e)||(t=Oi(e)).type!==a)throw new yo("Incompatible receiver, "+a+" required");return t}};NI||So.state?(ct=So.state||(So.state=new jI),ct.get=ct.get,ct.has=ct.has,ct.set=ct.set,Ss=function(a,e){if(ct.has(a))throw new yo(Ap);return e.facade=a,ct.set(a,e),e},Oi=function(a){return ct.get(a)||{}},ys=function(a){return ct.has(a)}):(Sr=UI("state"),HI[Sr]=!0,Ss=function(a,e){if(vo(a,Sr))throw new yo(Ap);return e.facade=a,qI(a,Sr,e),e},Oi=function(a){return vo(a,Sr)?a[Sr]:{}},ys=function(a){return vo(a,Sr)});var ct,Sr;Rp.exports={set:Ss,get:Oi,has:ys,enforce:GI,getterFor:QI}});var xo=b((XL,Lp)=>{"use strict";var Io=Ue(),WI=ut(),$p=Function.prototype,YI=Io&&Object.getOwnPropertyDescriptor,Eo=WI($p,"name"),zI=Eo&&function(){}.name==="something",KI=Eo&&(!Io||Io&&YI($p,"name").configurable);Lp.exports={EXISTS:Eo,PROPER:zI,CONFIGURABLE:KI}});var Dp=b(Mp=>{"use strict";var XI=Ue(),JI=so(),ZI=gr(),eE=vt(),tE=mr(),rE=bo();Mp.f=XI&&!JI?Object.defineProperties:function(e,t){eE(e);for(var r=tE(t),i=rE(t),s=i.length,n=0,o;s>n;)ZI.f(e,o=i[n++],r[o]);return e}});var Po=b((ZL,Cp)=>{"use strict";var iE=At();Cp.exports=iE("document","documentElement")});var Ro=b((eM,qp)=>{"use strict";var aE=vt(),sE=Dp(),Op=mo(),nE=vs(),oE=Po(),uE=hs(),lE=bs(),Vp=">",Bp="<",Ao="prototype",ko="script",Np=lE("IE_PROTO"),wo=function(){},Fp=function(a){return Bp+ko+Vp+a+Bp+"/"+ko+Vp},_p=function(a){a.write(Fp("")),a.close();var e=a.parentWindow.Object;return a=null,e},cE=function(){var a=uE("iframe"),e="java"+ko+":",t;return a.style.display="none",oE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Fp("document.F=Object")),t.close(),t.F},Ts,Is=function(){try{Ts=new ActiveXObject("htmlfile")}catch(e){}Is=typeof document!="undefined"?document.domain&&Ts?_p(Ts):cE():_p(Ts);for(var a=Op.length;a--;)delete Is[Ao][Op[a]];return Is()};nE[Np]=!0;qp.exports=Object.create||function(e,t){var r;return e!==null?(wo[Ao]=aE(e),r=new wo,wo[Ao]=null,r[Np]=e):r=Is(),t===void 0?r:sE.f(r,t)}});var Yr=b((tM,Up)=>{"use strict";var dE=Hr();Up.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:dE(a,e,t),a}});var Do=b((rM,Gp)=>{"use strict";var pE=Pe(),hE=he(),fE=je(),mE=Ro(),Hp=gs(),bE=Yr(),gE=we(),vE=ot(),Mo=gE("iterator"),jp=!1,kt,$o,Lo;[].keys&&(Lo=[].keys(),"next"in Lo?($o=Hp(Hp(Lo)),$o!==Object.prototype&&(kt=$o)):jp=!0);var SE=!fE(kt)||pE(function(){var a={};return kt[Mo].call(a)!==a});SE?kt={}:vE&&(kt=mE(kt));hE(kt[Mo])||bE(kt,Mo,function(){return this});Gp.exports={IteratorPrototype:kt,BUGGY_SAFARI_ITERATORS:jp}});var Es=b((iM,Wp)=>{"use strict";var yE=we(),TE=yE("toStringTag"),Qp={};Qp[TE]="z";Wp.exports=String(Qp)==="[object z]"});var Vi=b((aM,Yp)=>{"use strict";var IE=Es(),EE=he(),xs=fr(),xE=we(),PE=xE("toStringTag"),wE=Object,AE=xs(function(){return arguments}())==="Arguments",kE=function(a,e){try{return a[e]}catch(t){}};Yp.exports=IE?xs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=kE(e=wE(a),PE))=="string"?t:AE?xs(e):(r=xs(e))==="Object"&&EE(e.callee)?"Arguments":r}});var Kp=b((sM,zp)=>{"use strict";var RE=Es(),$E=Vi();zp.exports=RE?{}.toString:function(){return"[object "+$E(this)+"]"}});var Bi=b((nM,Jp)=>{"use strict";var LE=Es(),ME=gr().f,DE=Hr(),CE=ut(),OE=Kp(),VE=we(),Xp=VE("toStringTag");Jp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(CE(i,Xp)||ME(i,Xp,{configurable:!0,value:e}),r&&!LE&&DE(i,"toString",OE))}});var eh=b((oM,Zp)=>{"use strict";var BE=Do().IteratorPrototype,_E=Ro(),NE=wi(),FE=Bi(),qE=vr(),UE=function(){return this};Zp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=_E(BE,{next:NE(+!r,t)}),FE(a,i,!1,!0),qE[i]=UE,a}});var rh=b((uM,th)=>{"use strict";var HE=Se(),jE=gt();th.exports=function(a,e,t){try{return HE(jE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var ah=b((lM,ih)=>{"use strict";var GE=je();ih.exports=function(a){return GE(a)||a===null}});var nh=b((cM,sh)=>{"use strict";var QE=ah(),WE=String,YE=TypeError;sh.exports=function(a){if(QE(a))return a;throw new YE("Can't set "+WE(a)+" as a prototype")}});var Co=b((dM,oh)=>{"use strict";var zE=rh(),KE=je(),XE=zt(),JE=nh();oh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=zE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return XE(i),JE(s),KE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var vh=b((pM,gh)=>{"use strict";var ZE=be(),ex=He(),Ps=ot(),mh=xo(),tx=he(),rx=eh(),uh=gs(),lh=Co(),ix=Bi(),ax=Hr(),Oo=Yr(),sx=we(),ch=vr(),bh=Do(),nx=mh.PROPER,ox=mh.CONFIGURABLE,dh=bh.IteratorPrototype,ws=bh.BUGGY_SAFARI_ITERATORS,_i=sx("iterator"),ph="keys",Ni="values",hh="entries",fh=function(){return this};gh.exports=function(a,e,t,r,i,s,n){rx(t,e,r);var o=function(T){if(T===i&&p)return p;if(!ws&&T&&T in c)return c[T];switch(T){case ph:return function(){return new t(this,T)};case Ni:return function(){return new t(this,T)};case hh:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[_i]||c["@@iterator"]||i&&c[i],p=!ws&&d||o(i),h=e==="Array"&&c.entries||d,m,g,v;if(h&&(m=uh(h.call(new a)),m!==Object.prototype&&m.next&&(!Ps&&uh(m)!==dh&&(lh?lh(m,dh):tx(m[_i])||Oo(m,_i,fh)),ix(m,u,!0,!0),Ps&&(ch[u]=fh))),nx&&i===Ni&&d&&d.name!==Ni&&(!Ps&&ox?ax(c,"name",Ni):(l=!0,p=function(){return ex(d,this)})),i)if(g={values:o(Ni),keys:s?p:o(ph),entries:o(hh)},n)for(v in g)(ws||l||!(v in c))&&Oo(c,v,g[v]);else ZE({target:e,proto:!0,forced:ws||l},g);return(!Ps||n)&&c[_i]!==p&&Oo(c,_i,p,{name:i}),ch[e]=p,g}});var yh=b((hM,Sh)=>{"use strict";Sh.exports=function(a,e){return{value:a,done:e}}});var Bo=b((fM,Ph)=>{"use strict";var ux=mr(),Vo=Ci(),Th=vr(),Eh=To(),lx=gr().f,cx=vh(),As=yh(),dx=ot(),px=Ue(),xh="Array Iterator",hx=Eh.set,fx=Eh.getterFor(xh);Ph.exports=cx(Array,"Array",function(a,e){hx(this,{type:xh,target:ux(a),index:0,kind:e})},function(){var a=fx(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 Ih=Th.Arguments=Th.Array;Vo("keys");Vo("values");Vo("entries");if(!dx&&px&&Ih.name!=="values")try{lx(Ih,"name",{value:"values"})}catch(a){}});var Ah=b((mM,wh)=>{"use strict";var mx=we(),bx=vr(),gx=mx("iterator"),vx=Array.prototype;wh.exports=function(a){return a!==void 0&&(bx.Array===a||vx[gx]===a)}});var _o=b((bM,Rh)=>{"use strict";var Sx=Vi(),kh=Ri(),yx=_r(),Tx=vr(),Ix=we(),Ex=Ix("iterator");Rh.exports=function(a){if(!yx(a))return kh(a,Ex)||kh(a,"@@iterator")||Tx[Sx(a)]}});var Lh=b((gM,$h)=>{"use strict";var xx=He(),Px=gt(),wx=vt(),Ax=ki(),kx=_o(),Rx=TypeError;$h.exports=function(a,e){var t=arguments.length<2?kx(a):e;if(Px(t))return wx(xx(t,a));throw new Rx(Ax(a)+" is not iterable")}});var Ch=b((vM,Dh)=>{"use strict";var $x=He(),Mh=vt(),Lx=Ri();Dh.exports=function(a,e,t){var r,i;Mh(a);try{if(r=Lx(a,"return"),!r){if(e==="throw")throw t;return t}r=$x(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Mh(r),t}});var Rs=b((SM,_h)=>{"use strict";var Mx=Ur(),Dx=He(),Cx=vt(),Ox=ki(),Vx=Ah(),Bx=Qr(),Oh=Ai(),_x=Lh(),Nx=_o(),Vh=Ch(),Fx=TypeError,ks=function(a,e){this.stopped=a,this.result=e},Bh=ks.prototype;_h.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=Mx(e,r),l,c,d,p,h,m,g,v=function(I){return l&&Vh(l,"normal",I),new ks(!0,I)},T=function(I){return i?(Cx(I),o?u(I[0],I[1],v):u(I[0],I[1])):o?u(I,v):u(I)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Nx(a),!c)throw new Fx(Ox(a)+" is not iterable");if(Vx(c)){for(d=0,p=Bx(a);p>d;d++)if(h=T(a[d]),h&&Oh(Bh,h))return h;return new ks(!1)}l=_x(a,c)}for(m=s?a.next:l.next;!(g=Dx(m,l)).done;){try{h=T(g.value)}catch(I){Vh(l,"throw",I)}if(typeof h=="object"&&h&&Oh(Bh,h))return h}return new ks(!1)}});var Fh=b((yM,Nh)=>{"use strict";var qx=Ue(),Ux=gr(),Hx=wi();Nh.exports=function(a,e,t){qx?Ux.f(a,e,Hx(0,t)):a[e]=t}});var qh=b(()=>{"use strict";var jx=be(),Gx=Rs(),Qx=Fh();jx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Gx(e,function(r,i){Qx(t,r,i)},{AS_ENTRIES:!0}),t}})});var Hh=b((EM,Uh)=>{"use strict";Bo();qh();var Wx=Nr();Uh.exports=Wx.Object.fromEntries});var Gh=b((xM,jh)=>{"use strict";jh.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 Wh=b(()=>{"use strict";Bo();var Yx=Gh(),zx=me(),Kx=Bi(),Qh=vr();for($s in Yx)Kx(zx[$s],$s),Qh[$s]=Qh.Array;var $s});var zh=b((AM,Yh)=>{"use strict";var Xx=Hh();Wh();Yh.exports=Xx});var No=b((kM,Kh)=>{"use strict";var Jx=zh();Kh.exports=Jx});var Xh=b(()=>{"use strict"});var Fo=b((LM,Jh)=>{"use strict";var Fi=me(),Zx=br(),eP=fr(),Ls=function(a){return Zx.slice(0,a.length)===a};Jh.exports=function(){return Ls("Bun/")?"BUN":Ls("Cloudflare-Workers")?"CLOUDFLARE":Ls("Deno/")?"DENO":Ls("Node.js/")?"NODE":Fi.Bun&&typeof Bun.version=="string"?"BUN":Fi.Deno&&typeof Deno.version=="object"?"DENO":eP(Fi.process)==="process"?"NODE":Fi.window&&Fi.document?"BROWSER":"REST"}()});var Ms=b((MM,Zh)=>{"use strict";var tP=Fo();Zh.exports=tP==="NODE"});var tf=b((DM,ef)=>{"use strict";var rP=gr();ef.exports=function(a,e,t){return rP.f(a,e,t)}});var sf=b((CM,af)=>{"use strict";var iP=At(),aP=tf(),sP=we(),nP=Ue(),rf=sP("species");af.exports=function(a){var e=iP(a);nP&&e&&!e[rf]&&aP(e,rf,{configurable:!0,get:function(){return this}})}});var of=b((OM,nf)=>{"use strict";var oP=Ai(),uP=TypeError;nf.exports=function(a,e){if(oP(e,a))return a;throw new uP("Incorrect invocation")}});var Uo=b((VM,uf)=>{"use strict";var lP=Se(),cP=he(),qo=$i(),dP=lP(Function.toString);cP(qo.inspectSource)||(qo.inspectSource=function(a){return dP(a)});uf.exports=qo.inspectSource});var jo=b((BM,hf)=>{"use strict";var pP=Se(),hP=Pe(),lf=he(),fP=Vi(),mP=At(),bP=Uo(),cf=function(){},df=mP("Reflect","construct"),Ho=/^\s*(?:class|function)\b/,gP=pP(Ho.exec),vP=!Ho.test(cf),qi=function(e){if(!lf(e))return!1;try{return df(cf,[],e),!0}catch(t){return!1}},pf=function(e){if(!lf(e))return!1;switch(fP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return vP||!!gP(Ho,bP(e))}catch(t){return!0}};pf.sham=!0;hf.exports=!df||hP(function(){var a;return qi(qi.call)||!qi(Object)||!qi(function(){a=!0})||a})?pf:qi});var mf=b((_M,ff)=>{"use strict";var SP=jo(),yP=ki(),TP=TypeError;ff.exports=function(a){if(SP(a))return a;throw new TP(yP(a)+" is not a constructor")}});var Go=b((NM,gf)=>{"use strict";var bf=vt(),IP=mf(),EP=_r(),xP=we(),PP=xP("species");gf.exports=function(a,e){var t=bf(a).constructor,r;return t===void 0||EP(r=bf(t)[PP])?e:IP(r)}});var Sf=b((FM,vf)=>{"use strict";var wP=Se();vf.exports=wP([].slice)});var Tf=b((qM,yf)=>{"use strict";var AP=TypeError;yf.exports=function(a,e){if(a<e)throw new AP("Not enough arguments");return a}});var Qo=b((UM,If)=>{"use strict";var kP=br();If.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(kP)});var tu=b((HM,Lf)=>{"use strict";var Ge=me(),RP=Vn(),$P=Ur(),Ef=he(),LP=ut(),$f=Pe(),xf=Po(),MP=Sf(),Pf=hs(),DP=Tf(),CP=Qo(),OP=Ms(),Jo=Ge.setImmediate,Zo=Ge.clearImmediate,VP=Ge.process,Wo=Ge.Dispatch,BP=Ge.Function,wf=Ge.MessageChannel,_P=Ge.String,Yo=0,Ui={},Af="onreadystatechange",Hi,yr,zo,Ko;$f(function(){Hi=Ge.location});var eu=function(a){if(LP(Ui,a)){var e=Ui[a];delete Ui[a],e()}},Xo=function(a){return function(){eu(a)}},kf=function(a){eu(a.data)},Rf=function(a){Ge.postMessage(_P(a),Hi.protocol+"//"+Hi.host)};(!Jo||!Zo)&&(Jo=function(e){DP(arguments.length,1);var t=Ef(e)?e:BP(e),r=MP(arguments,1);return Ui[++Yo]=function(){RP(t,void 0,r)},yr(Yo),Yo},Zo=function(e){delete Ui[e]},OP?yr=function(a){VP.nextTick(Xo(a))}:Wo&&Wo.now?yr=function(a){Wo.now(Xo(a))}:wf&&!CP?(zo=new wf,Ko=zo.port2,zo.port1.onmessage=kf,yr=$P(Ko.postMessage,Ko)):Ge.addEventListener&&Ef(Ge.postMessage)&&!Ge.importScripts&&Hi&&Hi.protocol!=="file:"&&!$f(Rf)?(yr=Rf,Ge.addEventListener("message",kf,!1)):Af in Pf("script")?yr=function(a){xf.appendChild(Pf("script"))[Af]=function(){xf.removeChild(this),eu(a)}}:yr=function(a){setTimeout(Xo(a),0)});Lf.exports={set:Jo,clear:Zo}});var Cf=b((jM,Df)=>{"use strict";var Mf=me(),NP=Ue(),FP=Object.getOwnPropertyDescriptor;Df.exports=function(a){if(!NP)return Mf[a];var e=FP(Mf,a);return e&&e.value}});var ru=b((GM,Vf)=>{"use strict";var Of=function(){this.head=null,this.tail=null};Of.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}}};Vf.exports=Of});var _f=b((QM,Bf)=>{"use strict";var qP=br();Bf.exports=/ipad|iphone|ipod/i.test(qP)&&typeof Pebble!="undefined"});var Ff=b((WM,Nf)=>{"use strict";var UP=br();Nf.exports=/web0s(?!.*chrome)/i.test(UP)});var Wf=b((YM,Qf)=>{"use strict";var Kr=me(),HP=Cf(),qf=Ur(),iu=tu().set,jP=ru(),GP=Qo(),QP=_f(),WP=Ff(),au=Ms(),Uf=Kr.MutationObserver||Kr.WebKitMutationObserver,Hf=Kr.document,jf=Kr.process,Ds=Kr.Promise,ou=HP("queueMicrotask"),zr,su,nu,Cs,Gf;ou||(ji=new jP,Gi=function(){var a,e;for(au&&(a=jf.domain)&&a.exit();e=ji.get();)try{e()}catch(t){throw ji.head&&zr(),t}a&&a.enter()},!GP&&!au&&!WP&&Uf&&Hf?(su=!0,nu=Hf.createTextNode(""),new Uf(Gi).observe(nu,{characterData:!0}),zr=function(){nu.data=su=!su}):!QP&&Ds&&Ds.resolve?(Cs=Ds.resolve(void 0),Cs.constructor=Ds,Gf=qf(Cs.then,Cs),zr=function(){Gf(Gi)}):au?zr=function(){jf.nextTick(Gi)}:(iu=qf(iu,Kr),zr=function(){iu(Gi)}),ou=function(a){ji.head||zr(),ji.add(a)});var ji,Gi;Qf.exports=ou});var zf=b((zM,Yf)=>{"use strict";Yf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Os=b((KM,Kf)=>{"use strict";Kf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Tr=b((XM,Xf)=>{"use strict";var YP=me();Xf.exports=YP.Promise});var Xr=b((JM,tm)=>{"use strict";var zP=me(),Qi=Tr(),KP=he(),XP=ao(),JP=Uo(),ZP=we(),Jf=Fo(),ew=ot(),uu=Gn(),Zf=Qi&&Qi.prototype,tw=ZP("species"),lu=!1,em=KP(zP.PromiseRejectionEvent),rw=XP("Promise",function(){var a=JP(Qi),e=a!==String(Qi);if(!e&&uu===66||ew&&!(Zf.catch&&Zf.finally))return!0;if(!uu||uu<51||!/native code/.test(a)){var t=new Qi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[tw]=r,lu=t.then(function(){})instanceof r,!lu)return!0}return!e&&(Jf==="BROWSER"||Jf==="DENO")&&!em});tm.exports={CONSTRUCTOR:rw,REJECTION_EVENT:em,SUBCLASSING:lu}});var Jr=b((ZM,im)=>{"use strict";var rm=gt(),iw=TypeError,aw=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new iw("Bad Promise constructor");e=r,t=i}),this.resolve=rm(e),this.reject=rm(t)};im.exports.f=function(a){return new aw(a)}});var Im=b(()=>{"use strict";var sw=be(),nw=ot(),Ns=Ms(),Xt=me(),ri=He(),am=Yr(),sm=Co(),ow=Bi(),uw=sf(),lw=gt(),_s=he(),cw=je(),dw=of(),pw=Go(),cm=tu().set,fu=Wf(),hw=zf(),fw=Os(),mw=ru(),dm=To(),Fs=Tr(),mu=Xr(),pm=Jr(),qs="Promise",hm=mu.CONSTRUCTOR,bw=mu.REJECTION_EVENT,gw=mu.SUBCLASSING,cu=dm.getterFor(qs),vw=dm.set,Zr=Fs&&Fs.prototype,Ir=Fs,Vs=Zr,fm=Xt.TypeError,du=Xt.document,bu=Xt.process,pu=pm.f,Sw=pu,yw=!!(du&&du.createEvent&&Xt.dispatchEvent),mm="unhandledrejection",Tw="rejectionhandled",nm=0,bm=1,Iw=2,gu=1,gm=2,Bs,om,Ew,um,vm=function(a){var e;return cw(a)&&_s(e=a.then)?e:!1},Sm=function(a,e){var t=e.value,r=e.state===bm,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===gm&&Pw(e),e.rejection=gu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new fm("Promise-chain cycle")):(l=vm(u))?ri(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},ym=function(a,e){a.notified||(a.notified=!0,fu(function(){for(var t=a.reactions,r;r=t.get();)Sm(r,a);a.notified=!1,e&&!a.rejection&&xw(a)}))},Tm=function(a,e,t){var r,i;yw?(r=du.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Xt.dispatchEvent(r)):r={promise:e,reason:t},!bw&&(i=Xt["on"+a])?i(r):a===mm&&hw("Unhandled promise rejection",t)},xw=function(a){ri(cm,Xt,function(){var e=a.facade,t=a.value,r=lm(a),i;if(r&&(i=fw(function(){Ns?bu.emit("unhandledRejection",t,e):Tm(mm,e,t)}),a.rejection=Ns||lm(a)?gm:gu,i.error))throw i.value})},lm=function(a){return a.rejection!==gu&&!a.parent},Pw=function(a){ri(cm,Xt,function(){var e=a.facade;Ns?bu.emit("rejectionHandled",e):Tm(Tw,e,a.value)})},ei=function(a,e,t){return function(r){a(e,r,t)}},ti=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Iw,ym(a,!0))},hu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new fm("Promise can't be resolved itself");var r=vm(e);r?fu(function(){var i={done:!1};try{ri(r,e,ei(hu,i,a),ei(ti,i,a))}catch(s){ti(i,s,a)}}):(a.value=e,a.state=bm,ym(a,!1))}catch(i){ti({done:!1},i,a)}}};if(hm&&(Ir=function(e){dw(this,Vs),lw(e),ri(Bs,this);var t=cu(this);try{e(ei(hu,t),ei(ti,t))}catch(r){ti(t,r)}},Vs=Ir.prototype,Bs=function(e){vw(this,{type:qs,done:!1,notified:!1,parent:!1,reactions:new mw,rejection:!1,state:nm,value:void 0})},Bs.prototype=am(Vs,"then",function(e,t){var r=cu(this),i=pu(pw(this,Ir));return r.parent=!0,i.ok=_s(e)?e:!0,i.fail=_s(t)&&t,i.domain=Ns?bu.domain:void 0,r.state===nm?r.reactions.add(i):fu(function(){Sm(i,r)}),i.promise}),om=function(){var a=new Bs,e=cu(a);this.promise=a,this.resolve=ei(hu,e),this.reject=ei(ti,e)},pm.f=pu=function(a){return a===Ir||a===Ew?new om(a):Sw(a)},!nw&&_s(Fs)&&Zr!==Object.prototype)){um=Zr.then,gw||am(Zr,"then",function(e,t){var r=this;return new Ir(function(i,s){ri(um,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Zr.constructor}catch(a){}sm&&sm(Zr,Vs)}sw({global:!0,constructor:!0,wrap:!0,forced:hm},{Promise:Ir});ow(Ir,qs,!1,!0);uw(qs)});var Am=b((r0,wm)=>{"use strict";var ww=we(),xm=ww("iterator"),Pm=!1;try{Em=0,vu={next:function(){return{done:!!Em++}},return:function(){Pm=!0}},vu[xm]=function(){return this},Array.from(vu,function(){throw 2})}catch(a){}var Em,vu;wm.exports=function(a,e){try{if(!e&&!Pm)return!1}catch(i){return!1}var t=!1;try{var r={};r[xm]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Su=b((i0,km)=>{"use strict";var Aw=Tr(),kw=Am(),Rw=Xr().CONSTRUCTOR;km.exports=Rw||!kw(function(a){Aw.all(a).then(void 0,function(){})})});var Rm=b(()=>{"use strict";var $w=be(),Lw=He(),Mw=gt(),Dw=Jr(),Cw=Os(),Ow=Rs(),Vw=Su();$w({target:"Promise",stat:!0,forced:Vw},{all:function(e){var t=this,r=Dw.f(t),i=r.resolve,s=r.reject,n=Cw(function(){var o=Mw(t.resolve),u=[],l=0,c=1;Ow(e,function(d){var p=l++,h=!1;c++,Lw(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Lm=b(()=>{"use strict";var Bw=be(),_w=ot(),Nw=Xr().CONSTRUCTOR,Tu=Tr(),Fw=At(),qw=he(),Uw=Yr(),$m=Tu&&Tu.prototype;Bw({target:"Promise",proto:!0,forced:Nw,real:!0},{catch:function(a){return this.then(void 0,a)}});!_w&&qw(Tu)&&(yu=Fw("Promise").prototype.catch,$m.catch!==yu&&Uw($m,"catch",yu,{unsafe:!0}));var yu});var Mm=b(()=>{"use strict";var Hw=be(),jw=He(),Gw=gt(),Qw=Jr(),Ww=Os(),Yw=Rs(),zw=Su();Hw({target:"Promise",stat:!0,forced:zw},{race:function(e){var t=this,r=Qw.f(t),i=r.reject,s=Ww(function(){var n=Gw(t.resolve);Yw(e,function(o){jw(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Dm=b(()=>{"use strict";var Kw=be(),Xw=Jr(),Jw=Xr().CONSTRUCTOR;Kw({target:"Promise",stat:!0,forced:Jw},{reject:function(e){var t=Xw.f(this),r=t.reject;return r(e),t.promise}})});var Iu=b((p0,Cm)=>{"use strict";var Zw=vt(),eA=je(),tA=Jr();Cm.exports=function(a,e){if(Zw(a),eA(e)&&e.constructor===a)return e;var t=tA.f(a),r=t.resolve;return r(e),t.promise}});var Bm=b(()=>{"use strict";var rA=be(),iA=At(),Om=ot(),aA=Tr(),Vm=Xr().CONSTRUCTOR,sA=Iu(),nA=iA("Promise"),oA=Om&&!Vm;rA({target:"Promise",stat:!0,forced:Om||Vm},{resolve:function(e){return sA(oA&&this===nA?aA:this,e)}})});var _m=b(()=>{"use strict";Im();Rm();Lm();Mm();Dm();Bm()});var Um=b(()=>{"use strict";var uA=be(),lA=ot(),Us=Tr(),cA=Pe(),Fm=At(),qm=he(),dA=Go(),Nm=Iu(),pA=Yr(),xu=Us&&Us.prototype,hA=!!Us&&cA(function(){xu.finally.call({then:function(){}},function(){})});uA({target:"Promise",proto:!0,real:!0,forced:hA},{finally:function(a){var e=dA(this,Fm("Promise")),t=qm(a);return this.then(t?function(r){return Nm(e,a()).then(function(){return r})}:a,t?function(r){return Nm(e,a()).then(function(){throw r})}:a)}});!lA&&qm(Us)&&(Eu=Fm("Promise").prototype.finally,xu.finally!==Eu&&pA(xu,"finally",Eu,{unsafe:!0}));var Eu});var jm=b((S0,Hm)=>{"use strict";Xh();_m();Um();var fA=Kt();Hm.exports=fA("Promise","finally")});var Qm=b((y0,Gm)=>{"use strict";var mA=jm();Gm.exports=mA});var Hs=b((T0,Wm)=>{"use strict";var bA=Qm();Wm.exports=bA});var eb=b(()=>{"use strict";var TA=be(),IA=go().values;TA({target:"Object",stat:!0},{values:function(e){return IA(e)}})});var rb=b((J0,tb)=>{"use strict";eb();var EA=Nr();tb.exports=EA.Object.values});var ab=b((Z0,ib)=>{"use strict";var xA=rb();ib.exports=xA});var ii=b((eD,sb)=>{"use strict";var PA=ab();sb.exports=PA});var lb=b(()=>{"use strict";var RA=be(),$A=Fr(),LA=Qr(),MA=Di(),DA=Ci();RA({target:"Array",proto:!0},{at:function(e){var t=$A(this),r=LA(t),i=MA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});DA("at")});var db=b((xD,cb)=>{"use strict";lb();var CA=Kt();cb.exports=CA("Array","at")});var hb=b((PD,pb)=>{"use strict";var OA=db();pb.exports=OA});var ai=b((wD,fb)=>{"use strict";var VA=hb();fb.exports=VA});var qu=b((WC,Cb)=>{"use strict";var WA=fr();Cb.exports=Array.isArray||function(e){return WA(e)==="Array"}});var Vb=b((YC,Ob)=>{"use strict";var YA=TypeError,zA=9007199254740991;Ob.exports=function(a){if(a>zA)throw YA("Maximum allowed index exceeded");return a}});var Nb=b((zC,_b)=>{"use strict";var KA=qu(),XA=Qr(),JA=Vb(),ZA=Ur(),Bb=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=Bb(a,e,d,p,u,s-1)-1):(JA(u+1),a[u]=d),u++),l++;return u};_b.exports=Bb});var Hb=b((KC,Ub)=>{"use strict";var Fb=qu(),ek=jo(),tk=je(),rk=we(),ik=rk("species"),qb=Array;Ub.exports=function(a){var e;return Fb(a)&&(e=a.constructor,ek(e)&&(e===qb||Fb(e.prototype))?e=void 0:tk(e)&&(e=e[ik],e===null&&(e=void 0))),e===void 0?qb:e}});var Gb=b((XC,jb)=>{"use strict";var ak=Hb();jb.exports=function(a,e){return new(ak(a))(e===0?0:e)}});var Qb=b(()=>{"use strict";var sk=be(),nk=Nb(),ok=gt(),uk=Fr(),lk=Qr(),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 Wb=b(()=>{"use strict";var dk=Ci();dk("flatMap")});var zb=b((rO,Yb)=>{"use strict";Qb();Wb();var pk=Kt();Yb.exports=pk("Array","flatMap")});var Xb=b((iO,Kb)=>{"use strict";var hk=zb();Kb.exports=hk});var Uu=b((aO,Jb)=>{"use strict";var fk=Xb();Jb.exports=fk});var aa=b((fO,vg)=>{"use strict";var Ik=Vi(),Ek=String;vg.exports=function(a){if(Ik(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Ek(a)}});var ju=b((mO,Sg)=>{"use strict";Sg.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 Ig=b((bO,Tg)=>{"use strict";var xk=Se(),Pk=zt(),wk=aa(),Qu=ju(),yg=xk("".replace),Ak=RegExp("^["+Qu+"]+"),kk=RegExp("(^|[^"+Qu+"])["+Qu+"]+$"),Gu=function(a){return function(e){var t=wk(Pk(e));return a&1&&(t=yg(t,Ak,"")),a&2&&(t=yg(t,kk,"$1")),t}};Tg.exports={start:Gu(1),end:Gu(2),trim:Gu(3)}});var wg=b((gO,Pg)=>{"use strict";var Rk=xo().PROPER,$k=Pe(),Eg=ju(),xg="\u200B\x85\u180E";Pg.exports=function(a){return $k(function(){return!!Eg[a]()||xg[a]()!==xg||Rk&&Eg[a].name!==a})}});var Wu=b((vO,Ag)=>{"use strict";var Lk=Ig().start,Mk=wg();Ag.exports=Mk("trimStart")?function(){return Lk(this)}:"".trimStart});var Rg=b(()=>{"use strict";var Dk=be(),kg=Wu();Dk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==kg},{trimLeft:kg})});var Lg=b(()=>{"use strict";Rg();var Ck=be(),$g=Wu();Ck({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==$g},{trimStart:$g})});var Dg=b((EO,Mg)=>{"use strict";Lg();var Ok=Kt();Mg.exports=Ok("String","trimLeft")});var Og=b((xO,Cg)=>{"use strict";var Vk=Dg();Cg.exports=Vk});var Bg=b((PO,Vg)=>{"use strict";var Bk=Og();Vg.exports=Bk});var Xg=b(()=>{"use strict"});var Jg=b(()=>{"use strict"});var ev=b((YB,Zg)=>{"use strict";var iR=je(),aR=fr(),sR=we(),nR=sR("match");Zg.exports=function(a){var e;return iR(a)&&((e=a[nR])!==void 0?!!e:aR(a)==="RegExp")}});var rv=b((zB,tv)=>{"use strict";var oR=vt();tv.exports=function(){var a=oR(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 sv=b((KB,av)=>{"use strict";var uR=He(),lR=ut(),cR=Ai(),dR=rv(),iv=RegExp.prototype;av.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in iv)&&!lR(a,"flags")&&cR(iv,a)?uR(dR,a):e}});var ov=b((XB,nv)=>{"use strict";var el=Se(),pR=Fr(),hR=Math.floor,Ju=el("".charAt),fR=el("".replace),Zu=el("".slice),mR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,bR=/\$([$&'`]|\d{1,2})/g;nv.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=bR;return i!==void 0&&(i=pR(i),u=mR),fR(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=hR(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 cv=b(()=>{"use strict";var gR=be(),vR=He(),rl=Se(),uv=zt(),SR=he(),yR=_r(),TR=ev(),di=aa(),IR=Ri(),ER=sv(),xR=ov(),PR=we(),wR=ot(),AR=PR("replace"),kR=TypeError,tl=rl("".indexOf),RR=rl("".replace),lv=rl("".slice),$R=Math.max;gR({target:"String",proto:!0},{replaceAll:function(e,t){var r=uv(this),i,s,n,o,u,l,c,d,p,h,m=0,g="";if(!yR(e)){if(i=TR(e),i&&(s=di(uv(ER(e))),!~tl(s,"g")))throw new kR("`.replaceAll` does not allow non-global regexes");if(n=IR(e,AR),n)return vR(n,e,r,t);if(wR&&i)return RR(di(r),e,t)}for(o=di(r),u=di(e),l=SR(t),l||(t=di(t)),c=u.length,d=$R(1,c),p=tl(o,u);p!==-1;)h=l?di(t(u,p,o)):xR(u,o,p,[],void 0,t),g+=lv(o,m,p)+h,m=p+c,p=p+d>o.length?-1:tl(o,u,p+d);return m<o.length&&(g+=lv(o,m)),g}})});var pv=b((e_,dv)=>{"use strict";Xg();Jg();cv();var LR=Kt();dv.exports=LR("String","replaceAll")});var fv=b((t_,hv)=>{"use strict";var MR=pv();hv.exports=MR});var bv=b((r_,mv)=>{"use strict";var DR=fv();mv.exports=DR});var vv=b((i_,gv)=>{"use strict";var CR=Di(),OR=aa(),VR=zt(),BR=RangeError;gv.exports=function(e){var t=OR(VR(this)),r="",i=CR(e);if(i<0||i===1/0)throw new BR("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var Ev=b((a_,Iv)=>{"use strict";var Tv=Se(),_R=co(),Sv=aa(),NR=vv(),FR=zt(),qR=Tv(NR),UR=Tv("".slice),HR=Math.ceil,yv=function(a){return function(e,t,r){var i=Sv(FR(e)),s=_R(t),n=i.length,o=r===void 0?" ":Sv(r),u,l;return s<=n||o===""?i:(u=s-n,l=qR(o,HR(u/o.length)),l.length>u&&(l=UR(l,0,u)),a?i+l:l+i)}};Iv.exports={start:yv(!1),end:yv(!0)}});var Pv=b((s_,xv)=>{"use strict";var jR=br();xv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(jR)});var wv=b(()=>{"use strict";var GR=be(),QR=Ev().start,WR=Pv();GR({target:"String",proto:!0,forced:WR},{padStart:function(e){return QR(this,e,arguments.length>1?arguments[1]:void 0)}})});var kv=b((u_,Av)=>{"use strict";wv();var YR=Kt();Av.exports=YR("String","padStart")});var $v=b((l_,Rv)=>{"use strict";var zR=kv();Rv.exports=zR});var Mv=b((c_,Lv)=>{"use strict";var KR=$v();Lv.exports=KR});var f$={};FS(f$,{ChromecastState:()=>Ei,HttpConnectionType:()=>ls,Observable:()=>xt.Observable,PlaybackState:()=>$e,Player:()=>za,SDK_VERSION:()=>h$,Subject:()=>xt.Subject,Subscription:()=>xt.Subscription,Surface:()=>cs,VERSION:()=>Cn,ValueSubject:()=>xt.ValueSubject,VideoFormat:()=>wt,VideoQuality:()=>xt.VideoQuality});module.exports=qS(f$);var Cn="2.0.123";var $e=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))($e||{}),wt=(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))(wt||{});var Ei=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Ei||{}),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||{});var xS=K(lt(),1);var j=require("@vkontakte/videoplayer-shared/es2015");var Zd=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 j.ValueSubject(void 0);this.castState$=new j.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new j.Subject;this.realCastState$=new j.ValueSubject("NOT_AVAILABLE");this.subscription=new j.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,j.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||Zd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:j.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,j.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,j.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,j.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,j.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,j.assertNever)(i.sessionState)}})).add((0,j.merge)((0,j.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,j.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,j.map)(i=>i.castState)),(0,j.observableFrom)([r.getCastState()])).pipe((0,j.filterChanged)(),(0,j.map)(lI),(0,j.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=(0,j.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();(0,j.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,j.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,j.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:j.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},lI=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,j.assertNever)(a)}};var Tl=K(lt(),1),dS=K(Wr(),1),pS=K(No(),1);var Xm=K(Hs(),1);var Pu=require("@vkontakte/videoplayer-shared/es2015");var Ae=(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,Pu.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,Pu.assertNever)(e)}};var R=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var St=require("@vkontakte/videoplayer-shared/es2015"),Q=class{constructor(e){this.transitionStarted$=new St.Subject;this.transitionEnded$=new St.Subject;this.transitionUpdated$=new St.Subject;this.forceChanged$=new St.Subject;this.stateChangeStarted$=(0,St.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,St.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,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,St.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 Ym=require("@vkontakte/videoplayer-shared/es2015"),zm=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,Ym.assertNever)(a)}};var M=require("@vkontakte/videoplayer-shared/es2015");var gA=5,vA=5,SA=500,Km=7e3,Wi=class{constructor(e){this.subscription=new M.Subscription;this.loadMediaTimeoutSubscription=new M.Subscription;this.videoState=new Q("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,M.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,M.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,M.assertNever)(e)}break}default:(0,M.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(zm(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 M.Subscription;this.subscription.add(e),this.subscription.add((0,M.merge)(this.videoState.stateChangeStarted$.pipe((0,M.map)(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe((0,M.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 M.Subject;e.add(i.pipe((0,M.debounce)(SA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,M.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)>gA)&&i.next(o),s=o})),e.add((0,M.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,M.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,M.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,M.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<vA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(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,M.assertNever)(n)}}),t((0,M.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t((0,M.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=(0,M.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,M.observableFrom)(["init"])).pipe((0,M.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"),R(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),R(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"),R(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"),R(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"&&R(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,M.assertNonNullable)(c);let d=(0,M.getHighestQuality)(Object.keys(c));(0,M.assertNonNullable)(d);let p=c[d];(0,M.assertNonNullable)(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,M.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,M.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,M.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,M.assertNonNullable)(c),r=Ae(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:M.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,M.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,M.isNonNullable)(o)&&(n.metadata.title=o),(0,M.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,M.timeout)(Km).subscribe(()=>s(`timeout(${Km})`)))});(0,Xm.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:M.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Nu=K(lt(),1);var Ru=require("@vkontakte/videoplayer-shared/es2015");var Jm=require("@vkontakte/videoplayer-shared/es2015"),Zm=a=>{try{a.pause(),a.playbackRate=0,(0,Jm.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Gs=require("@vkontakte/videoplayer-shared/es2015"),wu=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)}},Au=window.WeakMap?new WeakMap:new wu,ku=window.WeakMap?new WeakMap:new Map,yA=(a,e=20)=>{let t=0;return(0,Gs.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},De=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?(0,Ru.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),Au.set(t,r);let i=new Gs.Subscription;return i.add(yA(t,e)),ku.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Ce=a=>{let e=ku.get(a);e==null||e.unsubscribe(),ku.delete(a);let t=Au.get(a);Au.delete(a),t?(0,Ru.clearVideoElement)(a):Zm(a)};var $u=K(ii(),1),D=require("@vkontakte/videoplayer-shared/es2015");var Jt=require("@vkontakte/videoplayer-shared/es2015"),Qs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Jt.isNullable)(i),l=new Jt.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},yt=(a,e,t)=>Qs(e,()=>a.loop,r=>{(0,Jt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),Oe=(a,e,t,r)=>Qs(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,Jt.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}),Xe=(a,e,t,r)=>Qs(e,()=>a.playbackRate,i=>{(0,Jt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Zt=Qs;var wA=a=>["__",a.language,a.label].join("|"),AA=(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(){this.available$=new D.Subject;this.current$=new D.ValueSubject(void 0);this.error$=new D.Subject;this.subscription=new D.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:D.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(Zt(t.internalTextTracks,()=>(0,$u.default)(this.internalTracks),s=>{(0,D.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,D.isNonNullable)(s)&&(0,D.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,D.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Zt(t.externalTextTracks,()=>(0,$u.default)(this.externalTracks),s=>{(0,D.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,D.isNonNullable)(s)&&(0,D.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,D.map)(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Zt(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(Zt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,D.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,D.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,D.merge)((0,D.fromEvent)(e,"addtrack"),(0,D.fromEvent)(e,"removetrack"),(0,D.observableFrom)(["init"])).pipe((0,D.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,D.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,D.merge)((0,D.fromEvent)(e,"change"),(0,D.observableFrom)(["init"])).pipe((0,D.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,D.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,D.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,D.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,D.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,D.isNonNullable)(t.align)&&(i.align=t.align),(0,D.isNonNullable)(t.position)&&(i.position=t.position),(0,D.isNonNullable)(t.size)&&(i.size=t.size),(0,D.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,D.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:wA(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,D.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,D.isNullable)(e)||!AA(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,D.assertNonNullable)(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,D.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)}},Je=Lu;var $t=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 nb=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},Mu=a=>{let e=nb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ob=a=>{let e=nb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var O=require("@vkontakte/videoplayer-shared/es2015");var kA=3,ub=(a,e,t=kA)=>{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,O.fromEvent)(a,x).pipe((0,O.mapTo)(void 0)),r=(0,O.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>(0,O.fromEvent)(a,x))).pipe((0,O.map)(x=>x.type==="ended"?a.readyState<2:a.readyState<3),(0,O.filterChanged)()),i=(0,O.merge)((0,O.fromEvent)(a,"progress"),(0,O.fromEvent)(a,"timeupdate")).pipe((0,O.map)(()=>ub(a.buffered,a.currentTime))),s=O.clientChecker.isSafari?(0,O.combine)({play:e("play").pipe((0,O.once)()),playing:e("playing")}).pipe((0,O.mapTo)(void 0)):e("playing"),n=(0,O.fromEvent)(a,"volumechange").pipe((0,O.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,O.fromEvent)(a,"ratechange").pipe((0,O.map)(()=>a.playbackRate)),u=(0,O.fromEvent)(a,"error").pipe((0,O.filter)(()=>!!(a.error||a.played.length)),(0,O.map)(()=>{var w;let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:O.ErrorCategory.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:(w=a.error)!=null?w:void 0}})),l=(0,O.fromEvent)(a,"timeupdate").pipe((0,O.map)(()=>a.currentTime)),c=new O.Subject,d=.3,p;l.subscribe(x=>{a.loop&&(0,O.isNonNullable)(p)&&(0,O.isNonNullable)(x)&&p>=a.duration-d&&x<=d&&c.next(p),p=x});let h=e("pause").pipe((0,O.filter)(()=>!a.error&&p!==a.duration)),m=(0,O.fromEvent)(a,"enterpictureinpicture"),g=(0,O.fromEvent)(a,"leavepictureinpicture"),v=new O.ValueSubject(ob(a));m.subscribe(()=>v.next(!0)),g.subscribe(()=>v.next(!1));let T=new O.ValueSubject(Mu(a));return(0,O.fromEvent)(a,"fullscreenchange").pipe((0,O.map)(()=>Mu(a))).subscribe(T),{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,O.fromEvent)(a,"durationchange").pipe((0,O.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:T,enterPip$:m,leavePip$:g}};var Lt=require("@vkontakte/videoplayer-shared/es2015"),er=a=>{switch(a){case"mobile":return Lt.VideoQuality.Q_144P;case"lowest":return Lt.VideoQuality.Q_240P;case"low":return Lt.VideoQuality.Q_360P;case"sd":case"medium":return Lt.VideoQuality.Q_480P;case"hd":case"high":return Lt.VideoQuality.Q_720P;case"fullhd":case"full":return Lt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Lt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Lt.VideoQuality.Q_2160P}};var tr=K(ai(),1),Sb=K(lt(),1),Ws=K(Wr(),1),C=require("@vkontakte/videoplayer-shared/es2015");var Du=!1,Mt={},mb=a=>{Du=a},bb=()=>{Mt={}},gb=a=>{a(Mt)},Yi=(a,e)=>{var t;Du&&(Mt.meta=(t=Mt.meta)!=null?t:{},Mt.meta[a]=e)},Le=class{constructor(e){this.name=e}next(e){var r,i;if(!Du)return;Mt.series=(r=Mt.series)!=null?r:{};let t=(i=Mt.series[this.name])!=null?i:[];t.push([Date.now(),e]),Mt.series[this.name]=t}};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)),zi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,C.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,C.isNonNullable)(l.bitrate)&&(0,C.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,tr.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,tr.default)(s,-1);return o&&(0,Sb.default)(n,o)?o:n.length?(0,tr.default)(n,-1):(0,tr.default)(s,0)},vb=a=>"quality"in a,Ib=(a,e,t,r)=>{var n;let i=(0,C.isNonNullable)((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&(0,C.isNonNullable)(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&(0,C.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 OS=Object.create;var Ii=Object.defineProperty,_S=Object.defineProperties,NS=Object.getOwnPropertyDescriptor,FS=Object.getOwnPropertyDescriptors,qS=Object.getOwnPropertyNames,ps=Object.getOwnPropertySymbols,US=Object.getPrototypeOf,On=Object.prototype.hasOwnProperty,lc=Object.prototype.propertyIsEnumerable;var HS=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var bt=Math.pow,uc=(a,e,t)=>e in a?Ii(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,A=(a,e)=>{for(var t in e||(e={}))On.call(e,t)&&uc(a,t,e[t]);if(ps)for(var t of ps(e))lc.call(e,t)&&uc(a,t,e[t]);return a},N=(a,e)=>_S(a,FS(e));var cc=(a,e)=>{var t={};for(var r in a)On.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&ps)for(var r of ps(a))e.indexOf(r)<0&&lc.call(a,r)&&(t[r]=a[r]);return t};var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),jS=(a,e)=>{for(var t in e)Ii(a,t,{get:e[t],enumerable:!0})},dc=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of qS(e))!On.call(a,i)&&i!==t&&Ii(a,i,{get:()=>e[i],enumerable:!(r=NS(e,i))||r.enumerable});return a};var X=(a,e,t)=>(t=a!=null?OS(US(a)):{},dc(e||!a||!a.__esModule?Ii(t,"default",{value:a,enumerable:!0}):t,a)),GS=a=>dc(Ii({},"__esModule",{value:!0}),a);var $=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),hs=function(a,e){this[0]=a,this[1]=e},ge=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof hs,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[HS("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var be=b((Nn,pc)=>{"use strict";var xi=function(a){return a&&a.Math===Math&&a};pc.exports=xi(typeof globalThis=="object"&&globalThis)||xi(typeof window=="object"&&window)||xi(typeof self=="object"&&self)||xi(typeof global=="object"&&global)||xi(typeof Nn=="object"&&Nn)||function(){return this}()||Function("return this")()});var xe=b((I$,hc)=>{"use strict";hc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Pi=b((E$,fc)=>{"use strict";var QS=xe();fc.exports=!QS(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Fn=b((x$,vc)=>{"use strict";var WS=Pi(),gc=Function.prototype,mc=gc.apply,bc=gc.call;vc.exports=typeof Reflect=="object"&&Reflect.apply||(WS?bc.bind(mc):function(){return bc.apply(mc,arguments)})});var ye=b((P$,Tc)=>{"use strict";var Sc=Pi(),yc=Function.prototype,qn=yc.call,YS=Sc&&yc.bind.bind(qn,qn);Tc.exports=Sc?YS:function(a){return function(){return qn.apply(a,arguments)}}});var mr=b((w$,Ec)=>{"use strict";var Ic=ye(),zS=Ic({}.toString),KS=Ic("".slice);Ec.exports=function(a){return KS(zS(a),8,-1)}});var Un=b((A$,xc)=>{"use strict";var XS=mr(),JS=ye();xc.exports=function(a){if(XS(a)==="Function")return JS(a)}});var fe=b((k$,Pc)=>{"use strict";var Hn=typeof document=="object"&&document.all;Pc.exports=typeof Hn=="undefined"&&Hn!==void 0?function(a){return typeof a=="function"||a===Hn}:function(a){return typeof a=="function"}});var He=b((R$,wc)=>{"use strict";var ZS=xe();wc.exports=!ZS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var je=b(($$,Ac)=>{"use strict";var ey=Pi(),bs=Function.prototype.call;Ac.exports=ey?bs.bind(bs):function(){return bs.apply(bs,arguments)}});var jn=b($c=>{"use strict";var kc={}.propertyIsEnumerable,Rc=Object.getOwnPropertyDescriptor,ty=Rc&&!kc.call({1:2},1);$c.f=ty?function(e){var t=Rc(this,e);return!!t&&t.enumerable}:kc});var wi=b((M$,Lc)=>{"use strict";Lc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Dc=b((D$,Mc)=>{"use strict";var ry=ye(),iy=xe(),ay=mr(),Gn=Object,sy=ry("".split);Mc.exports=iy(function(){return!Gn("z").propertyIsEnumerable(0)})?function(a){return ay(a)==="String"?sy(a,""):Gn(a)}:Gn});var _r=b((C$,Cc)=>{"use strict";Cc.exports=function(a){return a==null}});var zt=b((B$,Bc)=>{"use strict";var ny=_r(),oy=TypeError;Bc.exports=function(a){if(ny(a))throw new oy("Can't call method on "+a);return a}});var br=b((V$,Vc)=>{"use strict";var uy=Dc(),ly=zt();Vc.exports=function(a){return uy(ly(a))}});var Ge=b((O$,Oc)=>{"use strict";var cy=fe();Oc.exports=function(a){return typeof a=="object"?a!==null:cy(a)}});var Nr=b((_$,_c)=>{"use strict";_c.exports={}});var kt=b((N$,Fc)=>{"use strict";var Qn=Nr(),Wn=be(),dy=fe(),Nc=function(a){return dy(a)?a:void 0};Fc.exports=function(a,e){return arguments.length<2?Nc(Qn[a])||Nc(Wn[a]):Qn[a]&&Qn[a][e]||Wn[a]&&Wn[a][e]}});var Ai=b((F$,qc)=>{"use strict";var py=ye();qc.exports=py({}.isPrototypeOf)});var gr=b((q$,jc)=>{"use strict";var hy=be(),Uc=hy.navigator,Hc=Uc&&Uc.userAgent;jc.exports=Hc?String(Hc):""});var zn=b((U$,Kc)=>{"use strict";var zc=be(),Yn=gr(),Gc=zc.process,Qc=zc.Deno,Wc=Gc&&Gc.versions||Qc&&Qc.version,Yc=Wc&&Wc.v8,nt,gs;Yc&&(nt=Yc.split("."),gs=nt[0]>0&&nt[0]<4?1:+(nt[0]+nt[1]));!gs&&Yn&&(nt=Yn.match(/Edge\/(\d+)/),(!nt||nt[1]>=74)&&(nt=Yn.match(/Chrome\/(\d+)/),nt&&(gs=+nt[1])));Kc.exports=gs});var Kn=b((H$,Jc)=>{"use strict";var Xc=zn(),fy=xe(),my=be(),by=my.String;Jc.exports=!!Object.getOwnPropertySymbols&&!fy(function(){var a=Symbol("symbol detection");return!by(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Xc&&Xc<41})});var Xn=b((j$,Zc)=>{"use strict";var gy=Kn();Zc.exports=gy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Jn=b((G$,ed)=>{"use strict";var vy=kt(),Sy=fe(),yy=Ai(),Ty=Xn(),Iy=Object;ed.exports=Ty?function(a){return typeof a=="symbol"}:function(a){var e=vy("Symbol");return Sy(e)&&yy(e.prototype,Iy(a))}});var ki=b((Q$,td)=>{"use strict";var Ey=String;td.exports=function(a){try{return Ey(a)}catch(e){return"Object"}}});var gt=b((W$,rd)=>{"use strict";var xy=fe(),Py=ki(),wy=TypeError;rd.exports=function(a){if(xy(a))return a;throw new wy(Py(a)+" is not a function")}});var Ri=b((Y$,id)=>{"use strict";var Ay=gt(),ky=_r();id.exports=function(a,e){var t=a[e];return ky(t)?void 0:Ay(t)}});var sd=b((z$,ad)=>{"use strict";var Zn=je(),eo=fe(),to=Ge(),Ry=TypeError;ad.exports=function(a,e){var t,r;if(e==="string"&&eo(t=a.toString)&&!to(r=Zn(t,a))||eo(t=a.valueOf)&&!to(r=Zn(t,a))||e!=="string"&&eo(t=a.toString)&&!to(r=Zn(t,a)))return r;throw new Ry("Can't convert object to primitive value")}});var ot=b((K$,nd)=>{"use strict";nd.exports=!0});var ld=b((X$,ud)=>{"use strict";var od=be(),$y=Object.defineProperty;ud.exports=function(a,e){try{$y(od,a,{value:e,configurable:!0,writable:!0})}catch(t){od[a]=e}return e}});var $i=b((J$,pd)=>{"use strict";var Ly=ot(),My=be(),Dy=ld(),cd="__core-js_shared__",dd=pd.exports=My[cd]||Dy(cd,{});(dd.versions||(dd.versions=[])).push({version:"3.38.0",mode:Ly?"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 ro=b((Z$,fd)=>{"use strict";var hd=$i();fd.exports=function(a,e){return hd[a]||(hd[a]=e||{})}});var Fr=b((eL,md)=>{"use strict";var Cy=zt(),By=Object;md.exports=function(a){return By(Cy(a))}});var ut=b((tL,bd)=>{"use strict";var Vy=ye(),Oy=Fr(),_y=Vy({}.hasOwnProperty);bd.exports=Object.hasOwn||function(e,t){return _y(Oy(e),t)}});var io=b((rL,gd)=>{"use strict";var Ny=ye(),Fy=0,qy=Math.random(),Uy=Ny(1 .toString);gd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Uy(++Fy+qy,36)}});var Pe=b((iL,Sd)=>{"use strict";var Hy=be(),jy=ro(),vd=ut(),Gy=io(),Qy=Kn(),Wy=Xn(),qr=Hy.Symbol,ao=jy("wks"),Yy=Wy?qr.for||qr:qr&&qr.withoutSetter||Gy;Sd.exports=function(a){return vd(ao,a)||(ao[a]=Qy&&vd(qr,a)?qr[a]:Yy("Symbol."+a)),ao[a]}});var Ed=b((aL,Id)=>{"use strict";var zy=je(),yd=Ge(),Td=Jn(),Ky=Ri(),Xy=sd(),Jy=Pe(),Zy=TypeError,eT=Jy("toPrimitive");Id.exports=function(a,e){if(!yd(a)||Td(a))return a;var t=Ky(a,eT),r;if(t){if(e===void 0&&(e="default"),r=zy(t,a,e),!yd(r)||Td(r))return r;throw new Zy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Xy(a,e)}});var so=b((sL,xd)=>{"use strict";var tT=Ed(),rT=Jn();xd.exports=function(a){var e=tT(a,"string");return rT(e)?e:e+""}});var vs=b((nL,wd)=>{"use strict";var iT=be(),Pd=Ge(),no=iT.document,aT=Pd(no)&&Pd(no.createElement);wd.exports=function(a){return aT?no.createElement(a):{}}});var oo=b((oL,Ad)=>{"use strict";var sT=He(),nT=xe(),oT=vs();Ad.exports=!sT&&!nT(function(){return Object.defineProperty(oT("div"),"a",{get:function(){return 7}}).a!==7})});var $d=b(Rd=>{"use strict";var uT=He(),lT=je(),cT=jn(),dT=wi(),pT=br(),hT=so(),fT=ut(),mT=oo(),kd=Object.getOwnPropertyDescriptor;Rd.f=uT?kd:function(e,t){if(e=pT(e),t=hT(t),mT)try{return kd(e,t)}catch(r){}if(fT(e,t))return dT(!lT(cT.f,e,t),e[t])}});var uo=b((lL,Ld)=>{"use strict";var bT=xe(),gT=fe(),vT=/#|\.prototype\./,Li=function(a,e){var t=yT[ST(a)];return t===IT?!0:t===TT?!1:gT(e)?bT(e):!!e},ST=Li.normalize=function(a){return String(a).replace(vT,".").toLowerCase()},yT=Li.data={},TT=Li.NATIVE="N",IT=Li.POLYFILL="P";Ld.exports=Li});var Ur=b((cL,Dd)=>{"use strict";var Md=Un(),ET=gt(),xT=Pi(),PT=Md(Md.bind);Dd.exports=function(a,e){return ET(a),e===void 0?a:xT?PT(a,e):function(){return a.apply(e,arguments)}}});var lo=b((dL,Cd)=>{"use strict";var wT=He(),AT=xe();Cd.exports=wT&&AT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var vt=b((pL,Bd)=>{"use strict";var kT=Ge(),RT=String,$T=TypeError;Bd.exports=function(a){if(kT(a))return a;throw new $T(RT(a)+" is not an object")}});var vr=b(Od=>{"use strict";var LT=He(),MT=oo(),DT=lo(),Ss=vt(),Vd=so(),CT=TypeError,co=Object.defineProperty,BT=Object.getOwnPropertyDescriptor,po="enumerable",ho="configurable",fo="writable";Od.f=LT?DT?function(e,t,r){if(Ss(e),t=Vd(t),Ss(r),typeof e=="function"&&t==="prototype"&&"value"in r&&fo in r&&!r[fo]){var i=BT(e,t);i&&i[fo]&&(e[t]=r.value,r={configurable:ho in r?r[ho]:i[ho],enumerable:po in r?r[po]:i[po],writable:!1})}return co(e,t,r)}:co:function(e,t,r){if(Ss(e),t=Vd(t),Ss(r),MT)try{return co(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new CT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Hr=b((fL,_d)=>{"use strict";var VT=He(),OT=vr(),_T=wi();_d.exports=VT?function(a,e,t){return OT.f(a,e,_T(1,t))}:function(a,e,t){return a[e]=t,a}});var ve=b((mL,Fd)=>{"use strict";var Mi=be(),NT=Fn(),FT=Un(),qT=fe(),UT=$d().f,HT=uo(),jr=Nr(),jT=Ur(),Gr=Hr(),Nd=ut();$i();var GT=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 NT(a,this,arguments)};return e.prototype=a.prototype,e};Fd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Mi:i?Mi[t]:Mi[t]&&Mi[t].prototype,o=r?jr:jr[t]||Gr(jr,t,{})[t],u=o.prototype,l,c,d,p,h,m,g,v,I;for(p in e)l=HT(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Nd(n,p),m=o[p],c&&(a.dontCallGetSet?(I=UT(n,p),g=I&&I.value):g=n[p]),h=c&&g?g:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?v=jT(h,Mi):a.wrap&&c?v=GT(h):s&&qT(h)?v=FT(h):v=h,(a.sham||h&&h.sham||m&&m.sham)&&Gr(v,"sham",!0),Gr(o,p,v),s&&(d=t+"Prototype",Nd(jr,d)||Gr(jr,d,{}),Gr(jr[d],p,h),a.real&&u&&(l||!u[p])&&Gr(u,p,h)))}});var Ud=b((bL,qd)=>{"use strict";var QT=Math.ceil,WT=Math.floor;qd.exports=Math.trunc||function(e){var t=+e;return(t>0?WT:QT)(t)}});var Di=b((gL,Hd)=>{"use strict";var YT=Ud();Hd.exports=function(a){var e=+a;return e!==e||e===0?0:YT(e)}});var Gd=b((vL,jd)=>{"use strict";var zT=Di(),KT=Math.max,XT=Math.min;jd.exports=function(a,e){var t=zT(a);return t<0?KT(t+e,0):XT(t,e)}});var mo=b((SL,Qd)=>{"use strict";var JT=Di(),ZT=Math.min;Qd.exports=function(a){var e=JT(a);return e>0?ZT(e,9007199254740991):0}});var Qr=b((yL,Wd)=>{"use strict";var eI=mo();Wd.exports=function(a){return eI(a.length)}});var bo=b((TL,zd)=>{"use strict";var tI=br(),rI=Gd(),iI=Qr(),Yd=function(a){return function(e,t,r){var i=tI(e),s=iI(i);if(s===0)return!a&&-1;var n=rI(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}};zd.exports={includes:Yd(!0),indexOf:Yd(!1)}});var Ci=b((IL,Kd)=>{"use strict";Kd.exports=function(){}});var Xd=b(()=>{"use strict";var aI=ve(),sI=bo().includes,nI=xe(),oI=Ci(),uI=nI(function(){return!Array(1).includes()});aI({target:"Array",proto:!0,forced:uI},{includes:function(e){return sI(this,e,arguments.length>1?arguments[1]:void 0)}});oI("includes")});var Kt=b((PL,Jd)=>{"use strict";var lI=kt();Jd.exports=lI});var ep=b((wL,Zd)=>{"use strict";Xd();var cI=Kt();Zd.exports=cI("Array","includes")});var rp=b((AL,tp)=>{"use strict";var dI=ep();tp.exports=dI});var lt=b((kL,ip)=>{"use strict";var pI=rp();ip.exports=pI});var Ts=b((NL,np)=>{"use strict";var fI=ro(),mI=io(),sp=fI("keys");np.exports=function(a){return sp[a]||(sp[a]=mI(a))}});var up=b((FL,op)=>{"use strict";var bI=xe();op.exports=!bI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Is=b((qL,cp)=>{"use strict";var gI=ut(),vI=fe(),SI=Fr(),yI=Ts(),TI=up(),lp=yI("IE_PROTO"),go=Object,II=go.prototype;cp.exports=TI?go.getPrototypeOf:function(a){var e=SI(a);if(gI(e,lp))return e[lp];var t=e.constructor;return vI(t)&&e instanceof t?t.prototype:e instanceof go?II:null}});var Es=b((UL,dp)=>{"use strict";dp.exports={}});var fp=b((HL,hp)=>{"use strict";var EI=ye(),vo=ut(),xI=br(),PI=bo().indexOf,wI=Es(),pp=EI([].push);hp.exports=function(a,e){var t=xI(a),r=0,i=[],s;for(s in t)!vo(wI,s)&&vo(t,s)&&pp(i,s);for(;e.length>r;)vo(t,s=e[r++])&&(~PI(i,s)||pp(i,s));return i}});var So=b((jL,mp)=>{"use strict";mp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var yo=b((GL,bp)=>{"use strict";var AI=fp(),kI=So();bp.exports=Object.keys||function(e){return AI(e,kI)}});var To=b((QL,Tp)=>{"use strict";var vp=He(),RI=xe(),Sp=ye(),$I=Is(),LI=yo(),MI=br(),DI=jn().f,yp=Sp(DI),CI=Sp([].push),BI=vp&&RI(function(){var a=Object.create(null);return a[2]=2,!yp(a,2)}),gp=function(a){return function(e){for(var t=MI(e),r=LI(t),i=BI&&$I(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!vp||(i?u in t:yp(t,u)))&&CI(o,a?[u,t[u]]:t[u]);return o}};Tp.exports={entries:gp(!0),values:gp(!1)}});var Ip=b(()=>{"use strict";var VI=ve(),OI=To().entries;VI({target:"Object",stat:!0},{entries:function(e){return OI(e)}})});var xp=b((zL,Ep)=>{"use strict";Ip();var _I=Nr();Ep.exports=_I.Object.entries});var wp=b((KL,Pp)=>{"use strict";var NI=xp();Pp.exports=NI});var Wr=b((XL,Ap)=>{"use strict";var FI=wp();Ap.exports=FI});var Sr=b((JL,kp)=>{"use strict";kp.exports={}});var Lp=b((ZL,$p)=>{"use strict";var qI=be(),UI=fe(),Rp=qI.WeakMap;$p.exports=UI(Rp)&&/native code/.test(String(Rp))});var Po=b((eM,Cp)=>{"use strict";var HI=Lp(),Dp=be(),jI=Ge(),GI=Hr(),Io=ut(),Eo=$i(),QI=Ts(),WI=Es(),Mp="Object already initialized",xo=Dp.TypeError,YI=Dp.WeakMap,xs,Bi,Ps,zI=function(a){return Ps(a)?Bi(a):xs(a,{})},KI=function(a){return function(e){var t;if(!jI(e)||(t=Bi(e)).type!==a)throw new xo("Incompatible receiver, "+a+" required");return t}};HI||Eo.state?(ct=Eo.state||(Eo.state=new YI),ct.get=ct.get,ct.has=ct.has,ct.set=ct.set,xs=function(a,e){if(ct.has(a))throw new xo(Mp);return e.facade=a,ct.set(a,e),e},Bi=function(a){return ct.get(a)||{}},Ps=function(a){return ct.has(a)}):(yr=QI("state"),WI[yr]=!0,xs=function(a,e){if(Io(a,yr))throw new xo(Mp);return e.facade=a,GI(a,yr,e),e},Bi=function(a){return Io(a,yr)?a[yr]:{}},Ps=function(a){return Io(a,yr)});var ct,yr;Cp.exports={set:xs,get:Bi,has:Ps,enforce:zI,getterFor:KI}});var ko=b((tM,Vp)=>{"use strict";var wo=He(),XI=ut(),Bp=Function.prototype,JI=wo&&Object.getOwnPropertyDescriptor,Ao=XI(Bp,"name"),ZI=Ao&&function(){}.name==="something",eE=Ao&&(!wo||wo&&JI(Bp,"name").configurable);Vp.exports={EXISTS:Ao,PROPER:ZI,CONFIGURABLE:eE}});var _p=b(Op=>{"use strict";var tE=He(),rE=lo(),iE=vr(),aE=vt(),sE=br(),nE=yo();Op.f=tE&&!rE?Object.defineProperties:function(e,t){aE(e);for(var r=sE(t),i=nE(t),s=i.length,n=0,o;s>n;)iE.f(e,o=i[n++],r[o]);return e}});var Ro=b((iM,Np)=>{"use strict";var oE=kt();Np.exports=oE("document","documentElement")});var Do=b((aM,Qp)=>{"use strict";var uE=vt(),lE=_p(),Fp=So(),cE=Es(),dE=Ro(),pE=vs(),hE=Ts(),qp=">",Up="<",Lo="prototype",Mo="script",jp=hE("IE_PROTO"),$o=function(){},Gp=function(a){return Up+Mo+qp+a+Up+"/"+Mo+qp},Hp=function(a){a.write(Gp("")),a.close();var e=a.parentWindow.Object;return a=null,e},fE=function(){var a=pE("iframe"),e="java"+Mo+":",t;return a.style.display="none",dE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Gp("document.F=Object")),t.close(),t.F},ws,As=function(){try{ws=new ActiveXObject("htmlfile")}catch(e){}As=typeof document!="undefined"?document.domain&&ws?Hp(ws):fE():Hp(ws);for(var a=Fp.length;a--;)delete As[Lo][Fp[a]];return As()};cE[jp]=!0;Qp.exports=Object.create||function(e,t){var r;return e!==null?($o[Lo]=uE(e),r=new $o,$o[Lo]=null,r[jp]=e):r=As(),t===void 0?r:lE.f(r,t)}});var Yr=b((sM,Wp)=>{"use strict";var mE=Hr();Wp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:mE(a,e,t),a}});var Oo=b((nM,Kp)=>{"use strict";var bE=xe(),gE=fe(),vE=Ge(),SE=Do(),Yp=Is(),yE=Yr(),TE=Pe(),IE=ot(),Vo=TE("iterator"),zp=!1,Rt,Co,Bo;[].keys&&(Bo=[].keys(),"next"in Bo?(Co=Yp(Yp(Bo)),Co!==Object.prototype&&(Rt=Co)):zp=!0);var EE=!vE(Rt)||bE(function(){var a={};return Rt[Vo].call(a)!==a});EE?Rt={}:IE&&(Rt=SE(Rt));gE(Rt[Vo])||yE(Rt,Vo,function(){return this});Kp.exports={IteratorPrototype:Rt,BUGGY_SAFARI_ITERATORS:zp}});var ks=b((oM,Jp)=>{"use strict";var xE=Pe(),PE=xE("toStringTag"),Xp={};Xp[PE]="z";Jp.exports=String(Xp)==="[object z]"});var Vi=b((uM,Zp)=>{"use strict";var wE=ks(),AE=fe(),Rs=mr(),kE=Pe(),RE=kE("toStringTag"),$E=Object,LE=Rs(function(){return arguments}())==="Arguments",ME=function(a,e){try{return a[e]}catch(t){}};Zp.exports=wE?Rs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=ME(e=$E(a),RE))=="string"?t:LE?Rs(e):(r=Rs(e))==="Object"&&AE(e.callee)?"Arguments":r}});var th=b((lM,eh)=>{"use strict";var DE=ks(),CE=Vi();eh.exports=DE?{}.toString:function(){return"[object "+CE(this)+"]"}});var Oi=b((cM,ih)=>{"use strict";var BE=ks(),VE=vr().f,OE=Hr(),_E=ut(),NE=th(),FE=Pe(),rh=FE("toStringTag");ih.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(_E(i,rh)||VE(i,rh,{configurable:!0,value:e}),r&&!BE&&OE(i,"toString",NE))}});var sh=b((dM,ah)=>{"use strict";var qE=Oo().IteratorPrototype,UE=Do(),HE=wi(),jE=Oi(),GE=Sr(),QE=function(){return this};ah.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=UE(qE,{next:HE(+!r,t)}),jE(a,i,!1,!0),GE[i]=QE,a}});var oh=b((pM,nh)=>{"use strict";var WE=ye(),YE=gt();nh.exports=function(a,e,t){try{return WE(YE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var lh=b((hM,uh)=>{"use strict";var zE=Ge();uh.exports=function(a){return zE(a)||a===null}});var dh=b((fM,ch)=>{"use strict";var KE=lh(),XE=String,JE=TypeError;ch.exports=function(a){if(KE(a))return a;throw new JE("Can't set "+XE(a)+" as a prototype")}});var _o=b((mM,ph)=>{"use strict";var ZE=oh(),ex=Ge(),tx=zt(),rx=dh();ph.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=ZE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return tx(i),rx(s),ex(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Eh=b((bM,Ih)=>{"use strict";var ix=ve(),ax=je(),$s=ot(),yh=ko(),sx=fe(),nx=sh(),hh=Is(),fh=_o(),ox=Oi(),ux=Hr(),No=Yr(),lx=Pe(),mh=Sr(),Th=Oo(),cx=yh.PROPER,dx=yh.CONFIGURABLE,bh=Th.IteratorPrototype,Ls=Th.BUGGY_SAFARI_ITERATORS,_i=lx("iterator"),gh="keys",Ni="values",vh="entries",Sh=function(){return this};Ih.exports=function(a,e,t,r,i,s,n){nx(t,e,r);var o=function(I){if(I===i&&p)return p;if(!Ls&&I&&I in c)return c[I];switch(I){case gh:return function(){return new t(this,I)};case Ni:return function(){return new t(this,I)};case vh:return function(){return new t(this,I)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[_i]||c["@@iterator"]||i&&c[i],p=!Ls&&d||o(i),h=e==="Array"&&c.entries||d,m,g,v;if(h&&(m=hh(h.call(new a)),m!==Object.prototype&&m.next&&(!$s&&hh(m)!==bh&&(fh?fh(m,bh):sx(m[_i])||No(m,_i,Sh)),ox(m,u,!0,!0),$s&&(mh[u]=Sh))),cx&&i===Ni&&d&&d.name!==Ni&&(!$s&&dx?ux(c,"name",Ni):(l=!0,p=function(){return ax(d,this)})),i)if(g={values:o(Ni),keys:s?p:o(gh),entries:o(vh)},n)for(v in g)(Ls||l||!(v in c))&&No(c,v,g[v]);else ix({target:e,proto:!0,forced:Ls||l},g);return(!$s||n)&&c[_i]!==p&&No(c,_i,p,{name:i}),mh[e]=p,g}});var Ph=b((gM,xh)=>{"use strict";xh.exports=function(a,e){return{value:a,done:e}}});var qo=b((vM,$h)=>{"use strict";var px=br(),Fo=Ci(),wh=Sr(),kh=Po(),hx=vr().f,fx=Eh(),Ms=Ph(),mx=ot(),bx=He(),Rh="Array Iterator",gx=kh.set,vx=kh.getterFor(Rh);$h.exports=fx(Array,"Array",function(a,e){gx(this,{type:Rh,target:px(a),index:0,kind:e})},function(){var a=vx(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ms(void 0,!0);switch(a.kind){case"keys":return Ms(t,!1);case"values":return Ms(e[t],!1)}return Ms([t,e[t]],!1)},"values");var Ah=wh.Arguments=wh.Array;Fo("keys");Fo("values");Fo("entries");if(!mx&&bx&&Ah.name!=="values")try{hx(Ah,"name",{value:"values"})}catch(a){}});var Mh=b((SM,Lh)=>{"use strict";var Sx=Pe(),yx=Sr(),Tx=Sx("iterator"),Ix=Array.prototype;Lh.exports=function(a){return a!==void 0&&(yx.Array===a||Ix[Tx]===a)}});var Uo=b((yM,Ch)=>{"use strict";var Ex=Vi(),Dh=Ri(),xx=_r(),Px=Sr(),wx=Pe(),Ax=wx("iterator");Ch.exports=function(a){if(!xx(a))return Dh(a,Ax)||Dh(a,"@@iterator")||Px[Ex(a)]}});var Vh=b((TM,Bh)=>{"use strict";var kx=je(),Rx=gt(),$x=vt(),Lx=ki(),Mx=Uo(),Dx=TypeError;Bh.exports=function(a,e){var t=arguments.length<2?Mx(a):e;if(Rx(t))return $x(kx(t,a));throw new Dx(Lx(a)+" is not iterable")}});var Nh=b((IM,_h)=>{"use strict";var Cx=je(),Oh=vt(),Bx=Ri();_h.exports=function(a,e,t){var r,i;Oh(a);try{if(r=Bx(a,"return"),!r){if(e==="throw")throw t;return t}r=Cx(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Oh(r),t}});var Cs=b((EM,Hh)=>{"use strict";var Vx=Ur(),Ox=je(),_x=vt(),Nx=ki(),Fx=Mh(),qx=Qr(),Fh=Ai(),Ux=Vh(),Hx=Uo(),qh=Nh(),jx=TypeError,Ds=function(a,e){this.stopped=a,this.result=e},Uh=Ds.prototype;Hh.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,m,g,v=function(E){return l&&qh(l,"normal",E),new Ds(!0,E)},I=function(E){return i?(_x(E),o?u(E[0],E[1],v):u(E[0],E[1])):o?u(E,v):u(E)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Hx(a),!c)throw new jx(Nx(a)+" is not iterable");if(Fx(c)){for(d=0,p=qx(a);p>d;d++)if(h=I(a[d]),h&&Fh(Uh,h))return h;return new Ds(!1)}l=Ux(a,c)}for(m=s?a.next:l.next;!(g=Ox(m,l)).done;){try{h=I(g.value)}catch(E){qh(l,"throw",E)}if(typeof h=="object"&&h&&Fh(Uh,h))return h}return new Ds(!1)}});var Gh=b((xM,jh)=>{"use strict";var Gx=He(),Qx=vr(),Wx=wi();jh.exports=function(a,e,t){Gx?Qx.f(a,e,Wx(0,t)):a[e]=t}});var Qh=b(()=>{"use strict";var Yx=ve(),zx=Cs(),Kx=Gh();Yx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return zx(e,function(r,i){Kx(t,r,i)},{AS_ENTRIES:!0}),t}})});var Yh=b((AM,Wh)=>{"use strict";qo();Qh();var Xx=Nr();Wh.exports=Xx.Object.fromEntries});var Kh=b((kM,zh)=>{"use strict";zh.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 Jh=b(()=>{"use strict";qo();var Jx=Kh(),Zx=be(),eP=Oi(),Xh=Sr();for(Bs in Jx)eP(Zx[Bs],Bs),Xh[Bs]=Xh.Array;var Bs});var ef=b((LM,Zh)=>{"use strict";var tP=Yh();Jh();Zh.exports=tP});var Ho=b((MM,tf)=>{"use strict";var rP=ef();tf.exports=rP});var rf=b(()=>{"use strict"});var jo=b((BM,af)=>{"use strict";var Fi=be(),iP=gr(),aP=mr(),Vs=function(a){return iP.slice(0,a.length)===a};af.exports=function(){return Vs("Bun/")?"BUN":Vs("Cloudflare-Workers")?"CLOUDFLARE":Vs("Deno/")?"DENO":Vs("Node.js/")?"NODE":Fi.Bun&&typeof Bun.version=="string"?"BUN":Fi.Deno&&typeof Deno.version=="object"?"DENO":aP(Fi.process)==="process"?"NODE":Fi.window&&Fi.document?"BROWSER":"REST"}()});var Os=b((VM,sf)=>{"use strict";var sP=jo();sf.exports=sP==="NODE"});var of=b((OM,nf)=>{"use strict";var nP=vr();nf.exports=function(a,e,t){return nP.f(a,e,t)}});var cf=b((_M,lf)=>{"use strict";var oP=kt(),uP=of(),lP=Pe(),cP=He(),uf=lP("species");lf.exports=function(a){var e=oP(a);cP&&e&&!e[uf]&&uP(e,uf,{configurable:!0,get:function(){return this}})}});var pf=b((NM,df)=>{"use strict";var dP=Ai(),pP=TypeError;df.exports=function(a,e){if(dP(e,a))return a;throw new pP("Incorrect invocation")}});var Qo=b((FM,hf)=>{"use strict";var hP=ye(),fP=fe(),Go=$i(),mP=hP(Function.toString);fP(Go.inspectSource)||(Go.inspectSource=function(a){return mP(a)});hf.exports=Go.inspectSource});var Yo=b((qM,vf)=>{"use strict";var bP=ye(),gP=xe(),ff=fe(),vP=Vi(),SP=kt(),yP=Qo(),mf=function(){},bf=SP("Reflect","construct"),Wo=/^\s*(?:class|function)\b/,TP=bP(Wo.exec),IP=!Wo.test(mf),qi=function(e){if(!ff(e))return!1;try{return bf(mf,[],e),!0}catch(t){return!1}},gf=function(e){if(!ff(e))return!1;switch(vP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return IP||!!TP(Wo,yP(e))}catch(t){return!0}};gf.sham=!0;vf.exports=!bf||gP(function(){var a;return qi(qi.call)||!qi(Object)||!qi(function(){a=!0})||a})?gf:qi});var yf=b((UM,Sf)=>{"use strict";var EP=Yo(),xP=ki(),PP=TypeError;Sf.exports=function(a){if(EP(a))return a;throw new PP(xP(a)+" is not a constructor")}});var zo=b((HM,If)=>{"use strict";var Tf=vt(),wP=yf(),AP=_r(),kP=Pe(),RP=kP("species");If.exports=function(a,e){var t=Tf(a).constructor,r;return t===void 0||AP(r=Tf(t)[RP])?e:wP(r)}});var xf=b((jM,Ef)=>{"use strict";var $P=ye();Ef.exports=$P([].slice)});var wf=b((GM,Pf)=>{"use strict";var LP=TypeError;Pf.exports=function(a,e){if(a<e)throw new LP("Not enough arguments");return a}});var Ko=b((QM,Af)=>{"use strict";var MP=gr();Af.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(MP)});var su=b((WM,Vf)=>{"use strict";var Qe=be(),DP=Fn(),CP=Ur(),kf=fe(),BP=ut(),Bf=xe(),Rf=Ro(),VP=xf(),$f=vs(),OP=wf(),_P=Ko(),NP=Os(),ru=Qe.setImmediate,iu=Qe.clearImmediate,FP=Qe.process,Xo=Qe.Dispatch,qP=Qe.Function,Lf=Qe.MessageChannel,UP=Qe.String,Jo=0,Ui={},Mf="onreadystatechange",Hi,Tr,Zo,eu;Bf(function(){Hi=Qe.location});var au=function(a){if(BP(Ui,a)){var e=Ui[a];delete Ui[a],e()}},tu=function(a){return function(){au(a)}},Df=function(a){au(a.data)},Cf=function(a){Qe.postMessage(UP(a),Hi.protocol+"//"+Hi.host)};(!ru||!iu)&&(ru=function(e){OP(arguments.length,1);var t=kf(e)?e:qP(e),r=VP(arguments,1);return Ui[++Jo]=function(){DP(t,void 0,r)},Tr(Jo),Jo},iu=function(e){delete Ui[e]},NP?Tr=function(a){FP.nextTick(tu(a))}:Xo&&Xo.now?Tr=function(a){Xo.now(tu(a))}:Lf&&!_P?(Zo=new Lf,eu=Zo.port2,Zo.port1.onmessage=Df,Tr=CP(eu.postMessage,eu)):Qe.addEventListener&&kf(Qe.postMessage)&&!Qe.importScripts&&Hi&&Hi.protocol!=="file:"&&!Bf(Cf)?(Tr=Cf,Qe.addEventListener("message",Df,!1)):Mf in $f("script")?Tr=function(a){Rf.appendChild($f("script"))[Mf]=function(){Rf.removeChild(this),au(a)}}:Tr=function(a){setTimeout(tu(a),0)});Vf.exports={set:ru,clear:iu}});var Nf=b((YM,_f)=>{"use strict";var Of=be(),HP=He(),jP=Object.getOwnPropertyDescriptor;_f.exports=function(a){if(!HP)return Of[a];var e=jP(Of,a);return e&&e.value}});var nu=b((zM,qf)=>{"use strict";var Ff=function(){this.head=null,this.tail=null};Ff.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}}};qf.exports=Ff});var Hf=b((KM,Uf)=>{"use strict";var GP=gr();Uf.exports=/ipad|iphone|ipod/i.test(GP)&&typeof Pebble!="undefined"});var Gf=b((XM,jf)=>{"use strict";var QP=gr();jf.exports=/web0s(?!.*chrome)/i.test(QP)});var Jf=b((JM,Xf)=>{"use strict";var Kr=be(),WP=Nf(),Qf=Ur(),ou=su().set,YP=nu(),zP=Ko(),KP=Hf(),XP=Gf(),uu=Os(),Wf=Kr.MutationObserver||Kr.WebKitMutationObserver,Yf=Kr.document,zf=Kr.process,_s=Kr.Promise,du=WP("queueMicrotask"),zr,lu,cu,Ns,Kf;du||(ji=new YP,Gi=function(){var a,e;for(uu&&(a=zf.domain)&&a.exit();e=ji.get();)try{e()}catch(t){throw ji.head&&zr(),t}a&&a.enter()},!zP&&!uu&&!XP&&Wf&&Yf?(lu=!0,cu=Yf.createTextNode(""),new Wf(Gi).observe(cu,{characterData:!0}),zr=function(){cu.data=lu=!lu}):!KP&&_s&&_s.resolve?(Ns=_s.resolve(void 0),Ns.constructor=_s,Kf=Qf(Ns.then,Ns),zr=function(){Kf(Gi)}):uu?zr=function(){zf.nextTick(Gi)}:(ou=Qf(ou,Kr),zr=function(){ou(Gi)}),du=function(a){ji.head||zr(),ji.add(a)});var ji,Gi;Xf.exports=du});var em=b((ZM,Zf)=>{"use strict";Zf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Fs=b((eD,tm)=>{"use strict";tm.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ir=b((tD,rm)=>{"use strict";var JP=be();rm.exports=JP.Promise});var Xr=b((rD,nm)=>{"use strict";var ZP=be(),Qi=Ir(),ew=fe(),tw=uo(),rw=Qo(),iw=Pe(),im=jo(),aw=ot(),pu=zn(),am=Qi&&Qi.prototype,sw=iw("species"),hu=!1,sm=ew(ZP.PromiseRejectionEvent),nw=tw("Promise",function(){var a=rw(Qi),e=a!==String(Qi);if(!e&&pu===66||aw&&!(am.catch&&am.finally))return!0;if(!pu||pu<51||!/native code/.test(a)){var t=new Qi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[sw]=r,hu=t.then(function(){})instanceof r,!hu)return!0}return!e&&(im==="BROWSER"||im==="DENO")&&!sm});nm.exports={CONSTRUCTOR:nw,REJECTION_EVENT:sm,SUBCLASSING:hu}});var Jr=b((iD,um)=>{"use strict";var om=gt(),ow=TypeError,uw=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new ow("Bad Promise constructor");e=r,t=i}),this.resolve=om(e),this.reject=om(t)};um.exports.f=function(a){return new uw(a)}});var Am=b(()=>{"use strict";var lw=ve(),cw=ot(),js=Os(),Xt=be(),ri=je(),lm=Yr(),cm=_o(),dw=Oi(),pw=cf(),hw=gt(),Hs=fe(),fw=Ge(),mw=pf(),bw=zo(),mm=su().set,vu=Jf(),gw=em(),vw=Fs(),Sw=nu(),bm=Po(),Gs=Ir(),Su=Xr(),gm=Jr(),Qs="Promise",vm=Su.CONSTRUCTOR,yw=Su.REJECTION_EVENT,Tw=Su.SUBCLASSING,fu=bm.getterFor(Qs),Iw=bm.set,Zr=Gs&&Gs.prototype,Er=Gs,qs=Zr,Sm=Xt.TypeError,mu=Xt.document,yu=Xt.process,bu=gm.f,Ew=bu,xw=!!(mu&&mu.createEvent&&Xt.dispatchEvent),ym="unhandledrejection",Pw="rejectionhandled",dm=0,Tm=1,ww=2,Tu=1,Im=2,Us,pm,Aw,hm,Em=function(a){var e;return fw(a)&&Hs(e=a.then)?e:!1},xm=function(a,e){var t=e.value,r=e.state===Tm,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Im&&Rw(e),e.rejection=Tu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Sm("Promise-chain cycle")):(l=Em(u))?ri(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Pm=function(a,e){a.notified||(a.notified=!0,vu(function(){for(var t=a.reactions,r;r=t.get();)xm(r,a);a.notified=!1,e&&!a.rejection&&kw(a)}))},wm=function(a,e,t){var r,i;xw?(r=mu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Xt.dispatchEvent(r)):r={promise:e,reason:t},!yw&&(i=Xt["on"+a])?i(r):a===ym&&gw("Unhandled promise rejection",t)},kw=function(a){ri(mm,Xt,function(){var e=a.facade,t=a.value,r=fm(a),i;if(r&&(i=vw(function(){js?yu.emit("unhandledRejection",t,e):wm(ym,e,t)}),a.rejection=js||fm(a)?Im:Tu,i.error))throw i.value})},fm=function(a){return a.rejection!==Tu&&!a.parent},Rw=function(a){ri(mm,Xt,function(){var e=a.facade;js?yu.emit("rejectionHandled",e):wm(Pw,e,a.value)})},ei=function(a,e,t){return function(r){a(e,r,t)}},ti=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=ww,Pm(a,!0))},gu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Sm("Promise can't be resolved itself");var r=Em(e);r?vu(function(){var i={done:!1};try{ri(r,e,ei(gu,i,a),ei(ti,i,a))}catch(s){ti(i,s,a)}}):(a.value=e,a.state=Tm,Pm(a,!1))}catch(i){ti({done:!1},i,a)}}};if(vm&&(Er=function(e){mw(this,qs),hw(e),ri(Us,this);var t=fu(this);try{e(ei(gu,t),ei(ti,t))}catch(r){ti(t,r)}},qs=Er.prototype,Us=function(e){Iw(this,{type:Qs,done:!1,notified:!1,parent:!1,reactions:new Sw,rejection:!1,state:dm,value:void 0})},Us.prototype=lm(qs,"then",function(e,t){var r=fu(this),i=bu(bw(this,Er));return r.parent=!0,i.ok=Hs(e)?e:!0,i.fail=Hs(t)&&t,i.domain=js?yu.domain:void 0,r.state===dm?r.reactions.add(i):vu(function(){xm(i,r)}),i.promise}),pm=function(){var a=new Us,e=fu(a);this.promise=a,this.resolve=ei(gu,e),this.reject=ei(ti,e)},gm.f=bu=function(a){return a===Er||a===Aw?new pm(a):Ew(a)},!cw&&Hs(Gs)&&Zr!==Object.prototype)){hm=Zr.then,Tw||lm(Zr,"then",function(e,t){var r=this;return new Er(function(i,s){ri(hm,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Zr.constructor}catch(a){}cm&&cm(Zr,qs)}lw({global:!0,constructor:!0,wrap:!0,forced:vm},{Promise:Er});dw(Er,Qs,!1,!0);pw(Qs)});var Mm=b((nD,Lm)=>{"use strict";var $w=Pe(),Rm=$w("iterator"),$m=!1;try{km=0,Iu={next:function(){return{done:!!km++}},return:function(){$m=!0}},Iu[Rm]=function(){return this},Array.from(Iu,function(){throw 2})}catch(a){}var km,Iu;Lm.exports=function(a,e){try{if(!e&&!$m)return!1}catch(i){return!1}var t=!1;try{var r={};r[Rm]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Eu=b((oD,Dm)=>{"use strict";var Lw=Ir(),Mw=Mm(),Dw=Xr().CONSTRUCTOR;Dm.exports=Dw||!Mw(function(a){Lw.all(a).then(void 0,function(){})})});var Cm=b(()=>{"use strict";var Cw=ve(),Bw=je(),Vw=gt(),Ow=Jr(),_w=Fs(),Nw=Cs(),Fw=Eu();Cw({target:"Promise",stat:!0,forced:Fw},{all:function(e){var t=this,r=Ow.f(t),i=r.resolve,s=r.reject,n=_w(function(){var o=Vw(t.resolve),u=[],l=0,c=1;Nw(e,function(d){var p=l++,h=!1;c++,Bw(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Vm=b(()=>{"use strict";var qw=ve(),Uw=ot(),Hw=Xr().CONSTRUCTOR,Pu=Ir(),jw=kt(),Gw=fe(),Qw=Yr(),Bm=Pu&&Pu.prototype;qw({target:"Promise",proto:!0,forced:Hw,real:!0},{catch:function(a){return this.then(void 0,a)}});!Uw&&Gw(Pu)&&(xu=jw("Promise").prototype.catch,Bm.catch!==xu&&Qw(Bm,"catch",xu,{unsafe:!0}));var xu});var Om=b(()=>{"use strict";var Ww=ve(),Yw=je(),zw=gt(),Kw=Jr(),Xw=Fs(),Jw=Cs(),Zw=Eu();Ww({target:"Promise",stat:!0,forced:Zw},{race:function(e){var t=this,r=Kw.f(t),i=r.reject,s=Xw(function(){var n=zw(t.resolve);Jw(e,function(o){Yw(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var _m=b(()=>{"use strict";var eA=ve(),tA=Jr(),rA=Xr().CONSTRUCTOR;eA({target:"Promise",stat:!0,forced:rA},{reject:function(e){var t=tA.f(this),r=t.reject;return r(e),t.promise}})});var wu=b((bD,Nm)=>{"use strict";var iA=vt(),aA=Ge(),sA=Jr();Nm.exports=function(a,e){if(iA(a),aA(e)&&e.constructor===a)return e;var t=sA.f(a),r=t.resolve;return r(e),t.promise}});var Um=b(()=>{"use strict";var nA=ve(),oA=kt(),Fm=ot(),uA=Ir(),qm=Xr().CONSTRUCTOR,lA=wu(),cA=oA("Promise"),dA=Fm&&!qm;nA({target:"Promise",stat:!0,forced:Fm||qm},{resolve:function(e){return lA(dA&&this===cA?uA:this,e)}})});var Hm=b(()=>{"use strict";Am();Cm();Vm();Om();_m();Um()});var Wm=b(()=>{"use strict";var pA=ve(),hA=ot(),Ws=Ir(),fA=xe(),Gm=kt(),Qm=fe(),mA=zo(),jm=wu(),bA=Yr(),ku=Ws&&Ws.prototype,gA=!!Ws&&fA(function(){ku.finally.call({then:function(){}},function(){})});pA({target:"Promise",proto:!0,real:!0,forced:gA},{finally:function(a){var e=mA(this,Gm("Promise")),t=Qm(a);return this.then(t?function(r){return jm(e,a()).then(function(){return r})}:a,t?function(r){return jm(e,a()).then(function(){throw r})}:a)}});!hA&&Qm(Ws)&&(Au=Gm("Promise").prototype.finally,ku.finally!==Au&&bA(ku,"finally",Au,{unsafe:!0}));var Au});var zm=b((ED,Ym)=>{"use strict";rf();Hm();Wm();var vA=Kt();Ym.exports=vA("Promise","finally")});var Xm=b((xD,Km)=>{"use strict";var SA=zm();Km.exports=SA});var Ys=b((PD,Jm)=>{"use strict";var yA=Xm();Jm.exports=yA});var sb=b(()=>{"use strict";var PA=ve(),wA=To().values;PA({target:"Object",stat:!0},{values:function(e){return wA(e)}})});var ob=b((r0,nb)=>{"use strict";sb();var AA=Nr();nb.exports=AA.Object.values});var lb=b((i0,ub)=>{"use strict";var kA=ob();ub.exports=kA});var ii=b((a0,cb)=>{"use strict";var RA=lb();cb.exports=RA});var fb=b(()=>{"use strict";var DA=ve(),CA=Fr(),BA=Qr(),VA=Di(),OA=Ci();DA({target:"Array",proto:!0},{at:function(e){var t=CA(this),r=BA(t),i=VA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});OA("at")});var bb=b((k0,mb)=>{"use strict";fb();var _A=Kt();mb.exports=_A("Array","at")});var vb=b((R0,gb)=>{"use strict";var NA=bb();gb.exports=NA});var ai=b(($0,Sb)=>{"use strict";var FA=vb();Sb.exports=FA});var Gu=b((XC,Nb)=>{"use strict";var XA=mr();Nb.exports=Array.isArray||function(e){return XA(e)==="Array"}});var qb=b((JC,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((ZC,Hb)=>{"use strict";var ek=Gu(),tk=Qr(),rk=qb(),ik=Ur(),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((eB,Wb)=>{"use strict";var Gb=Gu(),ak=Yo(),sk=Ge(),nk=Pe(),ok=nk("species"),Qb=Array;Wb.exports=function(a){var e;return Gb(a)&&(e=a.constructor,ak(e)&&(e===Qb||Gb(e.prototype))?e=void 0:sk(e)&&(e=e[ok],e===null&&(e=void 0))),e===void 0?Qb:e}});var Kb=b((tB,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=ve(),ck=jb(),dk=gt(),pk=Fr(),hk=Qr(),fk=Kb();lk({target:"Array",proto:!0},{flatMap:function(e){var t=pk(this),r=hk(t),i;return dk(e),i=fk(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 mk=Ci();mk("flatMap")});var eg=b((nB,Zb)=>{"use strict";Xb();Jb();var bk=Kt();Zb.exports=bk("Array","flatMap")});var rg=b((oB,tg)=>{"use strict";var gk=eg();tg.exports=gk});var Qu=b((uB,ig)=>{"use strict";var vk=rg();ig.exports=vk});var aa=b((vB,Eg)=>{"use strict";var wk=Vi(),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 Yu=b((SB,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((yB,wg)=>{"use strict";var kk=ye(),Rk=zt(),$k=aa(),Ku=Yu(),Pg=kk("".replace),Lk=RegExp("^["+Ku+"]+"),Mk=RegExp("(^|[^"+Ku+"])["+Ku+"]+$"),zu=function(a){return function(e){var t=$k(Rk(e));return a&1&&(t=Pg(t,Lk,"")),a&2&&(t=Pg(t,Mk,"$1")),t}};wg.exports={start:zu(1),end:zu(2),trim:zu(3)}});var Lg=b((TB,$g)=>{"use strict";var Dk=ko().PROPER,Ck=xe(),kg=Yu(),Rg="\u200B\x85\u180E";$g.exports=function(a){return Ck(function(){return!!kg[a]()||Rg[a]()!==Rg||Dk&&kg[a].name!==a})}});var Xu=b((IB,Mg)=>{"use strict";var Bk=Ag().start,Vk=Lg();Mg.exports=Vk("trimStart")?function(){return Bk(this)}:"".trimStart});var Cg=b(()=>{"use strict";var Ok=ve(),Dg=Xu();Ok({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Dg},{trimLeft:Dg})});var Vg=b(()=>{"use strict";Cg();var _k=ve(),Bg=Xu();_k({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Bg},{trimStart:Bg})});var _g=b((AB,Og)=>{"use strict";Vg();var Nk=Kt();Og.exports=Nk("String","trimLeft")});var Fg=b((kB,Ng)=>{"use strict";var Fk=_g();Ng.exports=Fk});var Ug=b((RB,qg)=>{"use strict";var qk=Fg();qg.exports=qk});var rv=b(()=>{"use strict"});var iv=b(()=>{"use strict"});var sv=b((o_,av)=>{"use strict";var oR=Ge(),uR=mr(),lR=Pe(),cR=lR("match");av.exports=function(a){var e;return oR(a)&&((e=a[cR])!==void 0?!!e:uR(a)==="RegExp")}});var ov=b((u_,nv)=>{"use strict";var dR=vt();nv.exports=function(){var a=dR(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((l_,lv)=>{"use strict";var pR=je(),hR=ut(),fR=Ai(),mR=ov(),uv=RegExp.prototype;lv.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in uv)&&!hR(a,"flags")&&fR(uv,a)?pR(mR,a):e}});var pv=b((c_,dv)=>{"use strict";var al=ye(),bR=Fr(),gR=Math.floor,rl=al("".charAt),vR=al("".replace),il=al("".slice),SR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,yR=/\$([$&'`]|\d{1,2})/g;dv.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=yR;return i!==void 0&&(i=bR(i),u=SR),vR(s,u,function(l,c){var d;switch(rl(c,0)){case"$":return"$";case"&":return a;case"`":return il(e,0,t);case"'":return il(e,n);case"<":d=i[il(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=gR(p/10);return h===0?l:h<=o?r[h-1]===void 0?rl(c,1):r[h-1]+rl(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var mv=b(()=>{"use strict";var TR=ve(),IR=je(),nl=ye(),hv=zt(),ER=fe(),xR=_r(),PR=sv(),di=aa(),wR=Ri(),AR=cv(),kR=pv(),RR=Pe(),$R=ot(),LR=RR("replace"),MR=TypeError,sl=nl("".indexOf),DR=nl("".replace),fv=nl("".slice),CR=Math.max;TR({target:"String",proto:!0},{replaceAll:function(e,t){var r=hv(this),i,s,n,o,u,l,c,d,p,h,m=0,g="";if(!xR(e)){if(i=PR(e),i&&(s=di(hv(AR(e))),!~sl(s,"g")))throw new MR("`.replaceAll` does not allow non-global regexes");if(n=wR(e,LR),n)return IR(n,e,r,t);if($R&&i)return DR(di(r),e,t)}for(o=di(r),u=di(e),l=ER(t),l||(t=di(t)),c=u.length,d=CR(1,c),p=sl(o,u);p!==-1;)h=l?di(t(u,p,o)):kR(u,o,p,[],void 0,t),g+=fv(o,m,p)+h,m=p+c,p=p+d>o.length?-1:sl(o,u,p+d);return m<o.length&&(g+=fv(o,m)),g}})});var gv=b((h_,bv)=>{"use strict";rv();iv();mv();var BR=Kt();bv.exports=BR("String","replaceAll")});var Sv=b((f_,vv)=>{"use strict";var VR=gv();vv.exports=VR});var Tv=b((m_,yv)=>{"use strict";var OR=Sv();yv.exports=OR});var Ev=b((b_,Iv)=>{"use strict";var _R=Di(),NR=aa(),FR=zt(),qR=RangeError;Iv.exports=function(e){var t=NR(FR(this)),r="",i=_R(e);if(i<0||i===1/0)throw new qR("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var kv=b((g_,Av)=>{"use strict";var wv=ye(),UR=mo(),xv=aa(),HR=Ev(),jR=zt(),GR=wv(HR),QR=wv("".slice),WR=Math.ceil,Pv=function(a){return function(e,t,r){var i=xv(jR(e)),s=UR(t),n=i.length,o=r===void 0?" ":xv(r),u,l;return s<=n||o===""?i:(u=s-n,l=GR(o,WR(u/o.length)),l.length>u&&(l=QR(l,0,u)),a?i+l:l+i)}};Av.exports={start:Pv(!1),end:Pv(!0)}});var $v=b((v_,Rv)=>{"use strict";var YR=gr();Rv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(YR)});var Lv=b(()=>{"use strict";var zR=ve(),KR=kv().start,XR=$v();zR({target:"String",proto:!0,forced:XR},{padStart:function(e){return KR(this,e,arguments.length>1?arguments[1]:void 0)}})});var Dv=b((T_,Mv)=>{"use strict";Lv();var JR=Kt();Mv.exports=JR("String","padStart")});var Bv=b((I_,Cv)=>{"use strict";var ZR=Dv();Cv.exports=ZR});var Ov=b((E_,Vv)=>{"use strict";var e$=Bv();Vv.exports=e$});var v$={};jS(v$,{ChromecastState:()=>Ei,HttpConnectionType:()=>fs,Observable:()=>xt.Observable,PlaybackState:()=>Le,Player:()=>Ja,SDK_VERSION:()=>g$,Subject:()=>xt.Subject,Subscription:()=>xt.Subscription,Surface:()=>ms,VERSION:()=>_n,ValueSubject:()=>xt.ValueSubject,VideoFormat:()=>At,VideoQuality:()=>xt.VideoQuality});module.exports=GS(v$);var _n="2.0.124-dev.09b35b2f.0";var Le=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Le||{}),At=(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))(At||{});var Ei=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Ei||{}),fs=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(fs||{});var ms=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ms||{});var RS=X(lt(),1);var G=require("@vkontakte/videoplayer-shared/es2015");var ap=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 ys=class{constructor(e){this.connection$=new G.ValueSubject(void 0);this.castState$=new G.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new G.Subject;this.realCastState$=new G.ValueSubject("NOT_AVAILABLE");this.subscription=new G.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,G.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||ap("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:G.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,G.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,G.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,G.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,G.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,G.assertNever)(i.sessionState)}})).add((0,G.merge)((0,G.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,G.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,G.map)(i=>i.castState)),(0,G.observableFrom)([r.getCastState()])).pipe((0,G.filterChanged)(),(0,G.map)(hI),(0,G.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=(0,G.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();(0,G.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,G.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,G.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:G.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},hI=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,G.assertNever)(a)}};var Pl=X(lt(),1),bS=X(Wr(),1),gS=X(Ho(),1);var rb=X(Ys(),1);var Ru=require("@vkontakte/videoplayer-shared/es2015");var we=(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,Ru.assertNever)(t)}return a},zs=(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,Ru.assertNever)(e)}};var R=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var St=require("@vkontakte/videoplayer-shared/es2015"),W=class{constructor(e){this.transitionStarted$=new St.Subject;this.transitionEnded$=new St.Subject;this.transitionUpdated$=new St.Subject;this.forceChanged$=new St.Subject;this.stateChangeStarted$=(0,St.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,St.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,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,St.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 Zm=require("@vkontakte/videoplayer-shared/es2015"),eb=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,Zm.assertNever)(a)}};var D=require("@vkontakte/videoplayer-shared/es2015");var TA=5,IA=5,EA=500,tb=7e3,Wi=class{constructor(e){this.subscription=new D.Subscription;this.loadMediaTimeoutSubscription=new D.Subscription;this.videoState=new W("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,D.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,D.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,D.assertNever)(e)}break}default:(0,D.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(eb(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 D.Subscription;this.subscription.add(e),this.subscription.add((0,D.merge)(this.videoState.stateChangeStarted$.pipe((0,D.map)(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe((0,D.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 D.Subject;e.add(i.pipe((0,D.debounce)(EA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,D.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)>TA)&&i.next(o),s=o})),e.add((0,D.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,D.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,D.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,D.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<IA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(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,D.assertNever)(n)}}),t((0,D.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t((0,D.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=(0,D.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,D.observableFrom)(["init"])).pipe((0,D.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"),R(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),R(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"),R(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"),R(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"&&R(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,D.assertNonNullable)(c);let d=(0,D.getHighestQuality)(Object.keys(c));(0,D.assertNonNullable)(d);let p=c[d];(0,D.assertNonNullable)(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,D.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,D.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,D.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,D.assertNonNullable)(c),r=we(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:D.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,D.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,D.isNonNullable)(o)&&(n.metadata.title=o),(0,D.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,D.timeout)(tb).subscribe(()=>s(`timeout(${tb})`)))});(0,rb.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:D.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Hu=X(lt(),1);var Du=require("@vkontakte/videoplayer-shared/es2015");var ib=require("@vkontakte/videoplayer-shared/es2015"),ab=a=>{try{a.pause(),a.playbackRate=0,(0,ib.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Ks=require("@vkontakte/videoplayer-shared/es2015"),$u=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)}},Lu=window.WeakMap?new WeakMap:new $u,Mu=window.WeakMap?new WeakMap:new Map,xA=(a,e=20)=>{let t=0;return(0,Ks.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Be=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?(0,Du.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),Lu.set(t,r);let i=new Ks.Subscription;return i.add(xA(t,e)),Mu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.setAttribute("x-yandex-pip","false"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Ve=a=>{let e=Mu.get(a);e==null||e.unsubscribe(),Mu.delete(a);let t=Lu.get(a);Lu.delete(a),t?(0,Du.clearVideoElement)(a):ab(a)};var Cu=X(ii(),1),C=require("@vkontakte/videoplayer-shared/es2015");var Jt=require("@vkontakte/videoplayer-shared/es2015"),Xs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Jt.isNullable)(i),l=new Jt.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},yt=(a,e,t)=>Xs(e,()=>a.loop,r=>{(0,Jt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),Oe=(a,e,t,r)=>Xs(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,Jt.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}),Xe=(a,e,t,r)=>Xs(e,()=>a.playbackRate,i=>{(0,Jt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Zt=Xs;var $A=a=>["__",a.language,a.label].join("|"),LA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Bu=class a{constructor(e){this.available$=new C.Subject;this.current$=new C.ValueSubject(void 0);this.error$=new C.Subject;this.subscription=new C.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:C.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(Zt(t.internalTextTracks,()=>(0,Cu.default)(this.internalTracks),s=>{(0,C.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,C.isNonNullable)(s)&&(0,C.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,C.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Zt(t.externalTextTracks,()=>(0,Cu.default)(this.externalTracks),s=>{(0,C.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,C.isNonNullable)(s)&&(0,C.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,C.map)(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Zt(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(Zt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,C.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,C.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,C.merge)((0,C.fromEvent)(e,"addtrack"),(0,C.fromEvent)(e,"removetrack"),(0,C.observableFrom)(["init"])).pipe((0,C.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,C.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,C.merge)((0,C.fromEvent)(e,"change"),(0,C.observableFrom)(["init"])).pipe((0,C.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,C.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,C.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,C.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,C.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,C.isNonNullable)(t.align)&&(i.align=t.align),(0,C.isNonNullable)(t.position)&&(i.position=t.position),(0,C.isNonNullable)(t.size)&&(i.size=t.size),(0,C.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,C.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:$A(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,C.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,C.isNullable)(e)||!LA(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,C.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,C.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)}},Je=Bu;var Lt=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 db=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},Vu=a=>{let e=db(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},pb=a=>{let e=db(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var B=require("@vkontakte/videoplayer-shared/es2015");var MA=3,hb=(a,e,t=MA)=>{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 _e=a=>{let e=x=>(0,B.fromEvent)(a,x).pipe((0,B.mapTo)(void 0)),r=(0,B.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>(0,B.fromEvent)(a,x))).pipe((0,B.map)(x=>x.type==="ended"?a.readyState<2:a.readyState<3),(0,B.filterChanged)()),i=(0,B.merge)((0,B.fromEvent)(a,"progress"),(0,B.fromEvent)(a,"timeupdate")).pipe((0,B.map)(()=>hb(a.buffered,a.currentTime))),s=B.clientChecker.isSafari?(0,B.combine)({play:e("play").pipe((0,B.once)()),playing:e("playing")}).pipe((0,B.mapTo)(void 0)):e("playing"),n=(0,B.fromEvent)(a,"volumechange").pipe((0,B.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,B.fromEvent)(a,"ratechange").pipe((0,B.map)(()=>a.playbackRate)),u=(0,B.fromEvent)(a,"error").pipe((0,B.filter)(()=>!!(a.error||a.played.length)),(0,B.map)(()=>{var w;let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:B.ErrorCategory.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:(w=a.error)!=null?w:void 0}})),l=(0,B.fromEvent)(a,"timeupdate").pipe((0,B.map)(()=>a.currentTime)),c=new B.Subject,d=.3,p;l.subscribe(x=>{a.loop&&(0,B.isNonNullable)(p)&&(0,B.isNonNullable)(x)&&p>=a.duration-d&&x<=d&&c.next(p),p=x});let h=e("pause").pipe((0,B.filter)(()=>!a.error&&p!==a.duration)),m=(0,B.fromEvent)(a,"enterpictureinpicture"),g=(0,B.fromEvent)(a,"leavepictureinpicture"),v=new B.ValueSubject(pb(a));m.subscribe(()=>v.next(!0)),g.subscribe(()=>v.next(!1));let I=new B.ValueSubject(Vu(a));return(0,B.fromEvent)(a,"fullscreenchange").pipe((0,B.map)(()=>Vu(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,B.fromEvent)(a,"durationchange").pipe((0,B.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:I,enterPip$:m,leavePip$:g}};var Mt=require("@vkontakte/videoplayer-shared/es2015"),er=a=>{switch(a){case"mobile":return Mt.VideoQuality.Q_144P;case"lowest":return Mt.VideoQuality.Q_240P;case"low":return Mt.VideoQuality.Q_360P;case"sd":case"medium":return Mt.VideoQuality.Q_480P;case"hd":case"high":return Mt.VideoQuality.Q_720P;case"fullhd":case"full":return Mt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Mt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Mt.VideoQuality.Q_2160P}};var tr=X(ai(),1),xb=X(lt(),1),Js=X(Wr(),1),L=require("@vkontakte/videoplayer-shared/es2015");var Ou=!1,Dt={},yb=a=>{Ou=a},Tb=()=>{Dt={}},Ib=a=>{a(Dt)},Yi=(a,e)=>{var t;Ou&&(Dt.meta=(t=Dt.meta)!=null?t:{},Dt.meta[a]=e)},Me=class{constructor(e){this.name=e}next(e){var r,i;if(!Ou)return;Dt.series=(r=Dt.series)!=null?r:{};let t=(i=Dt.series[this.name])!=null?i:[];t.push([Date.now(),e]),Dt.series[this.name]=t}};var qA=new Me("best_bitrate"),Pb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var _u=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),zi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,L.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},wb='Assertion "ABR Tracks is empty array" failed',Zs=(a,e,t,r)=>{var u;let i=[...e].sort(_u(1)),s=[...t].sort(_u(1)),n=s.filter(l=>(0,L.isNonNullable)(l.bitrate)&&(0,L.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,tr.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,tr.default)(s,-1);return o&&(0,xb.default)(n,o)?o:n.length?(0,tr.default)(n,-1):(0,tr.default)(s,0)},Eb=a=>"quality"in a,Ab=(a,e,t,r)=>{var n;let i=(0,L.isNonNullable)((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&(0,L.isNonNullable)(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&(0,L.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=Eb(o)?"video":"audio",l=Eb(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},UA=(a,e)=>Math.log(e)/Math.log(a),rr=(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:m})=>{var ie,Z,oe,M,U;(0,L.assertNotEmptyArray)(a,wb);let g=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let P=window.devicePixelRatio;if(r.pixelRatioMultiplier)g*=r.pixelRatioMultiplier*(P-1)+1;else{let Q=r.pixelRatioLogBase,[j=0,ze=0,or=0]=r.pixelRatioLogCoefficients,Pt=UA(Q,j*P+ze)+or;Number.isFinite(Pt)&&(g*=Pt)}}let v=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*g,height:e.height*g}:void 0,I=r.considerPlaybackRate&&(0,L.isNonNullable)(o)?o:1,E=a.filter(P=>!(0,L.isInvariantQuality)(P.quality)).sort((P,Q)=>(0,L.isHigher)(P.quality,Q.quality)?-1:1),x=(ie=(0,tr.default)(E,-1))==null?void 0:ie.quality,w=(Z=(0,tr.default)(E,0))==null?void 0:Z.quality,k=(0,L.isNullable)(i)||(0,L.isNonNullable)(i.min)&&(0,L.isNonNullable)(i.max)&&(0,L.isLower)(i.max,i.min)||(0,L.isNonNullable)(i.min)&&w&&(0,L.isHigher)(i.min,w)||(0,L.isNonNullable)(i.max)&&x&&(0,L.isLower)(i.max,x),q=I*Pb(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),z={},H=E.filter(P=>{let Q=!0;if(v)if(P.size)Q=P.size.width<=v.width&&P.size.height<=v.height;else{let Re=v&&(0,L.videoSizeToQuality)(v);Q=Re?(0,L.isLowerOrEqual)(P.quality,Re):!0}if(!Q)return z[P.quality]="FitsContainer",!1;let j=h||t;if(!((0,L.isNonNullable)(j)&&isFinite(j)&&(0,L.isNonNullable)(P.bitrate)?j-s>=P.bitrate*q:!0))return z[P.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&(0,L.isNonNullable)(r.minBufferToSwitchUp)&&u&&!(0,L.isInvariantQuality)(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&(0,L.isHigher)(P.quality,u.quality))return z[P.quality]="Buffer",!1;if(!!d&&(0,L.isHigherOrEqual)(P.quality,d))return z[P.quality]="DroppedFramesLimit",!1;if(!!p&&(0,L.isHigherOrEqual)(P.quality,p))return z[P.quality]="StallsLimit",!1;let Ee=k||((0,L.isNullable)(i.max)||(0,L.isLowerOrEqual)(P.quality,i.max))&&((0,L.isNullable)(i.min)||(0,L.isHigherOrEqual)(P.quality,i.min)),ke=(0,L.isNonNullable)(c)&&!c?(0,L.isLowerOrEqual)(P.quality,r.backgroundVideoQualityLimit):!0;return!Ee||!ke?(z[P.quality]="FitsQualityLimits",!1):!0})[0];H&&H.bitrate&&qA.next(H.bitrate);let ne=(oe=H!=null?H:(0,tr.default)(E,-1))!=null?oe:a[0],J=l==null?void 0:l.last,V=Ab(r,m,ne,l);return(0,L.isNonNullable)(l)&&V.quality!==(J==null?void 0:J.quality)&&m({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${a.map(P=>{var
|
|
12
|
+
${a.map(P=>{var Q,j;return`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate}, size: ${(Q=P.size)==null?void 0:Q.width}:${(j=P.size)==null?void 0:j.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,Js.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: ${(M=v==null?void 0:v.width)!=null?M:0} x ${(U=v==null?void 0:v.height)!=null?U:0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${h},
|
|
24
24
|
reserve: ${s},
|
|
25
25
|
playbackRate: ${o},
|
|
26
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${I},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
28
|
bitrateFactor: ${q},
|
|
29
29
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
@@ -34,19 +34,19 @@
|
|
|
34
34
|
minQualityLimit: ${i==null?void 0:i.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,
|
|
37
|
+
${(0,Js.default)(z).map(([P,Q])=>`${P}: ${Q}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`}),
|
|
40
|
+
[best video track] ${H==null?void 0:H.quality}
|
|
41
|
+
[selected video track] ${V==null?void 0:V.quality}
|
|
42
|
+
`}),V},kb=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{(0,L.assertNotEmptyArray)(t,wb);let c=i.considerPlaybackRate&&(0,L.isNonNullable)(s)?s:1,d=[...t].sort(_u(-1)),p=a.bitrate;(0,L.assertNonNullable)(p);let h=c*Pb(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),m,g=Zs(a,e,t,i.minVideoAudioRatio),v=l||r;(0,L.isNonNullable)(v)&&isFinite(v)&&(m=d.find(x=>(0,L.isNonNullable)(x.bitrate)&&(0,L.isNonNullable)(g==null?void 0:g.bitrate)?v-p>=x.bitrate*h&&x.bitrate>=g.bitrate:!1)),m||(m=g);let I=o==null?void 0:o.last,E=m&&Ab(i,u,m,o);return(0,L.isNonNullable)(o)&&(E==null?void 0:E.bitrate)!==(I==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,Js.default)(i!=null?i:{}).map(([x,w])=>`${x}: ${w}`).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] ${m==null?void 0:m.id}
|
|
63
|
-
`}),m&&Ib(i,u,m,o)};var ye=a=>new URL(a).hostname;var V=require("@vkontakte/videoplayer-shared/es2015");var Pb=K(lt(),1);var 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=(a,e)=>$(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!xb(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return xb(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});var Qe=require("@vkontakte/videoplayer-shared/es2015");var wb=K(ii(),1),Tt=require("@vkontakte/videoplayer-shared/es2015");function Te(){return(0,Tt.now)()}function Ou(a){return Te()-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 Ab(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function si(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,g=2e3,v=()=>{if(u)return;(0,Tt.assertNonNullable)(c);let _=Ou(c),re;if(_<g){re=g-_,setTimeout(v,re);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new i,q()},T=_=>(s=_,te),I=_=>(d=_,te),x=()=>(h="json",te),w=()=>{if(!u){if(--l>=0){v(),r&&r();return}u=!0,d&&d(),t&&t()}},k=_=>(p=_,te),q=()=>{c=Te(),n=new i,n.open("get",a);let _=0,re,X=0,ne=()=>((0,Tt.assertNonNullable)(c),Math.max(c,Math.max(re||0,X||0)));if(s&&n.addEventListener("progress",L=>{let P=Te();s.updateChunk&&L.loaded>_&&(s.updateChunk(ne(),L.loaded-_),_=L.loaded,re=P)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;(0,Tt.assertNonNullable)(n);let L=n.status;if(L>=200&&L<300){if(n.response.byteLength&&s){let P=n.response.byteLength-_;P&&s.updateChunk&&s.updateChunk(ne(),P)}n.responseType==="json"&&!(0,wb.default)(n.response).length?w():(d&&d(),e(n.response))}else w()}),n.addEventListener("error",()=>{w()}),p){let L=()=>{(0,Tt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(X=Te(),n.removeEventListener("readystatechange",L))};n.addEventListener("readystatechange",L)}return n.responseType=h,n.send(),te},te={withBitrateReporting:T,withParallel:k,withJSONResponse:x,withRetryCount:_=>(l=_,te),withRetryInterval:(_,re)=>((0,Tt.isNonNullable)(_)&&(g=_),(0,Tt.isNonNullable)(re)&&(m=re),te),withTimeout:_=>(o=_,te),withFinally:I,send:q,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return te}var Ki=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=K(ii(),1);var Xi=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=Te(),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=Te()-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=si(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=Te()}_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=Te();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/es2015"),zs=1e4,Bu=3;var FA=6e4,qA=10,UA=1,HA=500,Ji=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new Rb.Subject,this.chunkRateEstimator=new Ki(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}setMaxAutoQuality(e){this.maxAutoQuality=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],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(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 Xi(Bu,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 w=s&&(!c||c===this.rep);return w||t("Not running!"),w},p=(w,k,q)=>{u&&u.abort(),u=si(this.urlResolver.resolve(w,!1),k,q,()=>this._retryCallback()).withTimeout(zs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Bu).withFinally(()=>{u=null}).send()},h=(w,k,q)=>{(0,Qe.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),k,q,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=w=>{let k=r.playbackRate;r.playbackRate!==w&&(t(`Playback rate switch: ${k}=>${w}`),r.playbackRate=w)},g=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let q=Te()-1e4,Y=0;for(let U=0;U<this.bufferStates.length;U++){let ee=this.bufferStates[U];w=Math.min(w,ee.buf),ee.ts<q&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${w} drop=${Y} jitter=${this.sourceJitter}`);let le=w-UA;this.sourceJitter>=0?le-=this.sourceJitter/2:this.sourceJitter-=1,le>3?m(1.15):le>1?m(1.1):le>.3?m(1.05):m(1)}},T=w=>{let k,q=()=>k&&k.start?k.start.length:0,Y=L=>k.start[L]/1e3,le=L=>k.dur[L]/1e3,U=L=>k.fragIndex+L,ee=(L,P)=>({chunkIdx:U(L),startTS:Y(L),dur:le(L),discontinuity:P}),te=()=>{let L=0;if(k&&k.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,H=P;this.sourceJitter>1&&(H+=this.sourceJitter-1);let ve=k.dur.length-1;for(;ve>=0&&(H-=k.dur[ve],!(H<=0));--ve);L=Math.min(ve,k.dur.length-1-G),L=Math.max(L,0)}return ee(L,!0)},_=L=>{let P=q();if(!(P<=0)){if((0,Qe.isNonNullable)(L)){for(let G=0;G<P;G++)if(Y(G)>L)return ee(G)}return te()}},re=L=>{let P=q(),G=L?L.chunkIdx+1:0,H=G-k.fragIndex;if(!(P<=0)){if(!L||H<0||H-P>qA)return t(`Resync: offset=${H} bChunks=${P} chunk=`+JSON.stringify(L)),te();if(!(H>=P))return ee(G-k.fragIndex,!1)}},X=(L,P,G)=>{l&&l.abort(),l=si(this.urlResolver.resolve(L,!0,this.lowLatency),P,G,()=>this._retryCallback()).withTimeout(zs).withRetryCount(Bu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(L,P)=>{X(w,G=>{if(!d())return;k=G;let H=!!k.lowLatency;H!==this.lowLatency&&g(H);let ve=0;for(let Ye=0;Ye<k.dur.length;++Ye)ve+=k.dur[Ye];ve>0&&((0,Qe.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ve/k.dur.length)),i({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,L(_(P))},()=>this._handleNetworkError())},nextChunk:re}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Qe.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:w=>{let{videoElement:k,logger:q}=this.params,Y=T(e.jidxUrl),le,U,ee,te,_=0,re,X,ne,L=()=>{re&&(clearTimeout(re),re=void 0);let ie=Math.max(HA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=_+ie,xe=Te(),ze=Math.min(1e4,Ee-xe);_=xe;let qt=()=>{l||d()&&Y.seek(()=>{d()&&(_=Te(),P(),L())})};ze>0?re=window.setTimeout(()=>{this.paused?L():qt()},ze):qt()},P=()=>{let ie;for(;ie=Y.nextChunk(te);)te=ie,Ft(ie);let Ee=Y.nextChunk(ee);if(Ee){if(ee&&Ee.discontinuity){q("Detected discontinuity; restarting playback"),this.paused?L():(I(),this._initPlayerWith(e));return}Ye(Ee)}else L()},G=(ie,Ee)=>{if(!d()||!this.sourceBuffer)return;let xe,ze,qt,$r=Ut=>{window.setTimeout(()=>{d()&&G(ie,Ee)},Ut)};if(this.sourceBuffer.updating)q("Source buffer is updating; delaying appendBuffer"),$r(100);else{let Ut=Te(),or=k.currentTime;!this.paused&&k.buffered.length>1&&X===or&&Ut-ne>500&&(q("Stall suspected; trying to fix"),this._fixupStall()),X!==or&&(X=or,ne=Ut);let Lr=this._getBufferSizeSec();if(Lr>30)q(`Buffered ${Lr} seconds; delaying appendBuffer`),$r(2e3);else try{this.sourceBuffer.appendBuffer(ie),this.videoPlayStarted?(this.bufferStates.push({ts:Ut,buf:Lr}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(mi){if(mi.name==="QuotaExceededError")q("QuotaExceededError; delaying appendBuffer"),qt=this.sourceBuffer.buffered.length,qt!==0&&(xe=this.sourceBuffer.buffered.start(0),ze=or,ze-xe>4&&this.sourceBuffer.remove(xe,ze-3)),$r(1e3);else throw mi}}},H=()=>{U&&le&&(q([`Appending chunk, sz=${U.byteLength}:`,JSON.stringify(ee)]),G(U,function(){U=null,P()}))},ve=ie=>e.fragUrlTemplate.replace("%%id%%",ie.chunkIdx),Ye=ie=>{d()&&h(ve(ie),(Ee,xe)=>{if(d()){if(xe/=1e3,U=Ee,ee=ie,n=ie.startTS,xe){let ze=Math.min(10,ie.dur/xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ze:ze}H()}},()=>this._handleNetworkError())},Ft=ie=>{d()&&((0,Qe.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ve(ie),!1)))},Rr=ie=>{d()&&(e.cachedHeader=ie,G(ie,()=>{le=!0,H()}))};s=!0,Y.seek(ie=>{if(d()){if(_=Te(),!ie){L();return}te=ie,!(0,Qe.isNullable)(w)||ie.startTS>w?Ye(ie):(ee=ie,P())}},w),e.cachedHeader?Rr(e.cachedHeader):p(e.headerUrl,Rr,()=>this._handleNetworkError())},stop:I,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,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.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 m=Te();if(this.chunkRateEstimator.addInterval(p,m,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:v}),!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&&Ou(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=Te();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=si(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)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(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=K(Wr(),1),de=require("@vkontakte/videoplayer-shared/es2015"),_u=class{constructor(){this.onDroopedVideoFramesLimit$=new de.Subject;this.subscription=new de.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new de.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,de.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,de.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,de.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,de.interval)(this.droppedFramesChecker.checkTime).pipe((0,de.filter)(()=>this.playing),(0,de.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,de.debounce)(this.droppedFramesChecker.checkTime)),r=(0,de.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,de.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/es2015"),Lb=require("@vkontakte/videoplayer-shared/es2015");var Zi=()=>{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||Zi()))},A(A({},r),e));i.observe(a);let s=(0,Lb.fromEvent)(document,"visibilitychange").pipe((0,Xs.map)(n=>!document.hidden||Zi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ze=jA;var GA=["paused","playing","ready"],QA=["paused","playing","ready"],ea=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new Q("stopped");this.representations$=new V.ValueSubject([]);this.textTracksManager=new Je;this.droppedFramesManager=new Ks;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new $t;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:V.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=er(u.name))!=null?r:(0,V.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p=A({},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,V.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)(QA,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,Nu.default)(GA,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ae(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(Ae(this.params.source.url,u))}return;default:return(0,V.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:V.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,V.merge)(this.videoState.stateChangeStarted$.pipe((0,V.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,V.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(ye(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,V.map)(i=>i.map(({track:s})=>s)),(0,V.filter)(i=>!!i.length),(0,V.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,V.filterChanged)(),(0,V.map)(i=>-i/1e3)).subscribe(this.params.output.duration$)).add((0,V.combine)({zeroTime:this.zeroTime$.pipe((0,V.filter)(V.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(yt(this.video,this.params.desiredState.isLooped,t)).add(Oe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Xe(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(Ze(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&(0,V.videoQualityToHeight)(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).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,V.assertNever)(i.to)}},t)).add((0,V.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,V.observableFrom)(["init"])).pipe((0,V.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ce(this.video)}createLiveDashPlayer(){let e=new Ji({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,m;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,V.isNonNullable)(t)?t:rr(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=(m=e.find(({track:v})=>v.id===s))==null?void 0:m.representation;(0,V.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,V.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),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(Ae(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Mb=ea;var tS=K(lt(),1);var It=(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 F=require("@vkontakte/videoplayer-shared/es2015");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}},ni=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)}},ta=class{constructor(){Object.defineProperty(this,"signal",{value:new ni,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&&(ta.prototype[Symbol.toStringTag]="AbortController",ni.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,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ra=Zs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Db=ra?Fu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,dt=ra?Db.fetch:window.fetch,jC=ra?Db.Request:window.Request,ke=ra?ta:window.AbortController,GC=ra?ni:window.AbortSignal;var ml=K(Uu(),1);var ln=K(ai(),1);var Dt=()=>window.ManagedMediaSource||window.MediaSource,en=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Zb=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},eg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Et=require("@vkontakte/videoplayer-shared/es2015");var et=document.createElement("video"),gk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',vk='video/mp4; codecs="hev1.1.6.L93.B0"',dg='video/webm; codecs="vp09.00.10.08"',pg='video/webm; codecs="av01.0.00M.08"',Sk='audio/mp4; codecs="mp4a.40.2"',yk='audio/webm; codecs="opus"',tg,rg,ia={mms:en(),mse:Zb(),hls:!!((tg=et.canPlayType)!=null&&tg.call(et,"application/x-mpegurl")||(rg=et.canPlayType)!=null&&rg.call(et,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ig,ag,_e={mp4:!!((ig=et.canPlayType)!=null&&ig.call(et,"video/mp4")),webm:!!((ag=et.canPlayType)!=null&&ag.call(et,"video/webm")),cmaf:!0},rn,sg,an,ng,sn,og,nn,ug,on,lg,un,cg,Ne={h264:!!((sg=(rn=Dt())==null?void 0:rn.isTypeSupported)!=null&&sg.call(rn,gk)),h265:!!((ng=(an=Dt())==null?void 0:an.isTypeSupported)!=null&&ng.call(an,vk)),vp9:!!((og=(sn=Dt())==null?void 0:sn.isTypeSupported)!=null&&og.call(sn,dg)),av1:!!((ug=(nn=Dt())==null?void 0:nn.isTypeSupported)!=null&&ug.call(nn,pg)),aac:!!((lg=(on=Dt())==null?void 0:on.isTypeSupported)!=null&&lg.call(on,Sk)),opus:!!((cg=(un=Dt())==null?void 0:un.isTypeSupported)!=null&&cg.call(un,yk))},oi=(Ne.h264||Ne.h265)&&Ne.aac,Er,Tk=()=>$(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(N(A({},a),{video:N(A({},a.video),{contentType:pg})})),window.navigator.mediaCapabilities.decodingInfo(N(A({},a),{video:N(A({},a.video),{contentType:dg})}))]);Er={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{Tk()}catch(a){console.error(a)}var ui=ia.hls&&_e.mp4,hg=()=>Object.keys(Ne).filter(a=>Ne[a]),fg=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=ia.mse&&(!r||!!window.MediaStreamTrack)||ia.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&_e.mp4&&oi;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&&oi||_e.webm&&(Ne.vp9||Ne.av1)&&(Ne.opus||Ne.aac));case"DASH_LIVE":return i&&_e.mp4&&oi;case"DASH_LIVE_CMAF":return i&&_e.mp4&&oi&&_e.cmaf;case"DASH_ONDEMAND":return i&&_e.mp4&&oi;case"HLS":case"HLS_ONDEMAND":return ui||e&&i&&_e.mp4&&oi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return ui;case"MPEG":return _e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ia.webrtc&&ia.ws&&Ne.h264&&(_e.mp4||_e.webm);default:return(0,Et.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 Er?Er[t].smooth?[t,e]:Er[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Er?Er[t].powerEfficient?[t,e]:Er[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,Et.assertNever)(a)}return[e,t]},mg=({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(Et.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,Et.assertNever)(e)}return ui?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},bg=({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=Et.clientChecker.isMac&&Et.clientChecker.isSafari;if(Et.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,Et.assertNever)(a)}else ui&&!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"],gg=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 _g=K(Bg(),1),li=require("@vkontakte/videoplayer-shared/es2015"),Ng=a=>{if(!a)return{id:"EmptyResponse",category:li.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:li.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,_g.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:li.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:li.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:li.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var ir=(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 S=require("@vkontakte/videoplayer-shared/es2015");var cn=K(lt(),1),pi=K(ai(),1),dn=K(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),Fg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),qg=!Fg(window.requestIdleCallback)||!Fg(window.cancelIdleCallback),Yu=qg?_k:window.requestIdleCallback,sa=qg?Nk:window.cancelIdleCallback;var Wv=K(Hs(),1);var tt=require("@vkontakte/videoplayer-shared/es2015");var Fk=18,Ug=!1;try{Ug=tt.clientChecker.isSafari&&!!tt.clientChecker.macVersion&&tt.clientChecker.macVersion<=Fk}catch(a){console.error(a)}var zu=class{constructor(e){this.bufferFull$=new tt.Subject;this.error$=new tt.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:tt.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return $(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return $(this,null,function*(){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()})})}abort(e){return $(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};Ug&&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:tt.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,tt.assertNever)(t)}}},Hg=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 E=require("@vkontakte/videoplayer-shared/es2015");var ae=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),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let 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 ci=class extends ae{};var na=class extends ae{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 oa=class extends ae{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 ua=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pe=class extends ae{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var la=class extends pe{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 ca=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var da=class extends ae{constructor(e,t){super(e,t),this.data=this.content}};var xr=class extends pe{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 pa=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ha=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fa=class extends pe{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 ma=class extends pe{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ba=class extends pe{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ga=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var va=class extends pe{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 Sa=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ya=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ta=class extends pe{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ia=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ea=class extends pe{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 xa=class extends pe{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 Pa=class extends pe{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 Uk={ftyp:oa,moov:ua,mvhd:la,moof:ca,mdat:da,sidx:xr,trak:pa,mdia:ga,mfhd:Ta,tkhd:va,traf:Ia,tfhd:Ea,tfdt:xa,trun:Pa,minf:Sa,sv3d:ha,st3d:fa,prhd:ma,proj:ya,equi:ba,uuid:na,unknown:ci},Ct=class a{constructor(e={}){this.options=A({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 ci(t,new a)}};var ar=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"),Gk=a=>jk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Qk=a=>{let e=new xr(a,new Ct),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 Ct().parse(a),i=new ar(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 Ct().parse(a),r=new ar(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},zk=a=>{var i;let t=new Ct().parse(a);return(i=new ar(t).find("sidx"))==null?void 0:i.timescale},Kk=(a,e)=>{let r=new Ct().parse(a),s=new ar(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 Ct().parse(a),i=new ar(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},jg={validateData:Gk,parseInit:Xk,getIndexRange:()=>{},parseSegments:Qk,parseFeedableSegmentChunk:Wk,getChunkEndTime:Kk,getServerLatencyTimestamps:Yk,getTimescaleFromIndex:zk};var Aa=K(lt(),1),Ot=require("@vkontakte/videoplayer-shared/es2015");var Qg=require("@vkontakte/videoplayer-shared/es2015");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"}},Wg=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=wa(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=wa(u),d=l*bt(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}},wa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*bt(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*bt(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*bt(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},pt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return wa(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,Qg.assertNever)(e)}},Pr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Wg(r);if(!e(i))return;i.type==="master"&&Pr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Yg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Wg(a);return Pr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=pt(o,n):s===17026?t=pt(o,n):s===17029&&(r=pt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var zg=[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 Pr(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let v=pt(m,h);l=wa(v)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=pt(m,h):p===17545?i=pt(m,h):p===21420&&l===475249515?u=pt(m,h):p===374648427?Pr(m,({tag:v,type:T,value:I})=>v===30321?(c=pt(I,T)===1,!1):!0):s&&n&&(0,Aa.default)(zg,p)&&(o=!0),!o}),(0,Ot.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Ot.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Ot.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}}}},eR=a=>{if((0,Ot.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},tR=(a,e)=>{let t=!1,r=!1,i=o=>(0,Ot.isNonNullable)(o.time)&&(0,Ot.isNonNullable)(o.position),s=[],n;return Pr(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=pt(l,u));break;case 183:break;case 241:n&&(n.position=pt(l,u));break;default:t&&(0,Aa.default)(zg,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}}})},rR=a=>{let e=0,t=!1;try{Pr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Aa.default)(Jk,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Aa.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},Kg={validateData:Yg,parseInit:Zk,getIndexRange:eR,parseSegments:tR,parseFeedableSegmentChunk:rR};var ka=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Kg;case"mp4":return jg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var ll=K(bv(),1),Uv=K(Wr(),1),Hv=K(Mv(),1),jv=K(ai(),1),cl=K(ii(),1);var Dv=K(lt(),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,Dv.default)(["6E","7A","F4"],o)}}return!1};var $a=require("@vkontakte/videoplayer-shared/es2015");var Cv=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Ov=a=>{var e;try{let t=XR(),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 XR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
63
|
+
`}),E};var Te=a=>new URL(a).hostname;var O=require("@vkontakte/videoplayer-shared/es2015");var $b=X(lt(),1);var Rb=a=>{if(a instanceof DOMException&&(0,$b.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"))},Ne=(a,e)=>$(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!Rb(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return Rb(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});var We=require("@vkontakte/videoplayer-shared/es2015");var Lb=X(ii(),1),Tt=require("@vkontakte/videoplayer-shared/es2015");function Ie(){return(0,Tt.now)()}function Nu(a){return Ie()-a}function Fu(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 Mb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function si(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,g=2e3,v=()=>{if(u)return;(0,Tt.assertNonNullable)(c);let V=Nu(c),ie;if(V<g){ie=g-V,setTimeout(v,ie);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new i,q()},I=V=>(s=V,J),E=V=>(d=V,J),x=()=>(h="json",J),w=()=>{if(!u){if(--l>=0){v(),r&&r();return}u=!0,d&&d(),t&&t()}},k=V=>(p=V,J),q=()=>{c=Ie(),n=new i,n.open("get",a);let V=0,ie,Z=0,oe=()=>((0,Tt.assertNonNullable)(c),Math.max(c,Math.max(ie||0,Z||0)));if(s&&n.addEventListener("progress",M=>{let U=Ie();s.updateChunk&&M.loaded>V&&(s.updateChunk(oe(),M.loaded-V),V=M.loaded,ie=U)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;(0,Tt.assertNonNullable)(n);let M=n.status;if(M>=200&&M<300){let{response:U,responseType:P}=n,Q=U==null?void 0:U.byteLength;if(typeof Q=="number"&&s){let j=Q-V;j&&s.updateChunk&&s.updateChunk(oe(),j)}P==="json"&&(!U||!(0,Lb.default)(U).length)?w():(d&&d(),e(U))}else w()}),n.addEventListener("error",()=>{w()}),p){let M=()=>{(0,Tt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Z=Ie(),n.removeEventListener("readystatechange",M))};n.addEventListener("readystatechange",M)}return n.responseType=h,n.send(),J},J={withBitrateReporting:I,withParallel:k,withJSONResponse:x,withRetryCount:V=>(l=V,J),withRetryInterval:(V,ie)=>((0,Tt.isNonNullable)(V)&&(g=V),(0,Tt.isNonNullable)(ie)&&(m=ie),J),withTimeout:V=>(o=V,J),withFinally:E,send:q,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return J}var Ki=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 Db=X(ii(),1);var Xi=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=Ie(),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=Ie()-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=si(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=Ie()}_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=Ie();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,Db.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/es2015"),en=1e4,qu=3;var jA=6e4,GA=10,QA=1,WA=500,Ji=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new Cb.Subject,this.chunkRateEstimator=new Ki(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Fu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=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=Fu(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],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(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,We.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=()=>{Mb(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 Xi(qu,en,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 w=s&&(!c||c===this.rep);return w||t("Not running!"),w},p=(w,k,q)=>{u&&u.abort(),u=si(this.urlResolver.resolve(w,!1),k,q,()=>this._retryCallback()).withTimeout(en).withBitrateReporting(this.bitrateSwitcher).withRetryCount(qu).withFinally(()=>{u=null}).send()},h=(w,k,q)=>{(0,We.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),k,q,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=w=>{let k=r.playbackRate;r.playbackRate!==w&&(t(`Playback rate switch: ${k}=>${w}`),r.playbackRate=w)},g=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let q=Ie()-1e4,z=0;for(let H=0;H<this.bufferStates.length;H++){let ne=this.bufferStates[H];w=Math.min(w,ne.buf),ne.ts<q&&z++}this.bufferStates.splice(0,z),t(`update playback rate; minBuffer=${w} drop=${z} jitter=${this.sourceJitter}`);let de=w-QA;this.sourceJitter>=0?de-=this.sourceJitter/2:this.sourceJitter-=1,de>3?m(1.15):de>1?m(1.1):de>.3?m(1.05):m(1)}},I=w=>{let k,q=()=>k&&k.start?k.start.length:0,z=M=>k.start[M]/1e3,de=M=>k.dur[M]/1e3,H=M=>k.fragIndex+M,ne=(M,U)=>({chunkIdx:H(M),startTS:z(M),dur:de(M),discontinuity:U}),J=()=>{let M=0;if(k&&k.dur){let U=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,P=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Q=U;this.sourceJitter>1&&(Q+=this.sourceJitter-1);let j=k.dur.length-1;for(;j>=0&&(Q-=k.dur[j],!(Q<=0));--j);M=Math.min(j,k.dur.length-1-P),M=Math.max(M,0)}return ne(M,!0)},V=M=>{let U=q();if(!(U<=0)){if((0,We.isNonNullable)(M)){for(let P=0;P<U;P++)if(z(P)>M)return ne(P)}return J()}},ie=M=>{let U=q(),P=M?M.chunkIdx+1:0,Q=P-k.fragIndex;if(!(U<=0)){if(!M||Q<0||Q-U>GA)return t(`Resync: offset=${Q} bChunks=${U} chunk=`+JSON.stringify(M)),J();if(!(Q>=U))return ne(P-k.fragIndex,!1)}},Z=(M,U,P)=>{l&&l.abort(),l=si(this.urlResolver.resolve(M,!0,this.lowLatency),U,P,()=>this._retryCallback()).withTimeout(en).withRetryCount(qu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(M,U)=>{Z(w,P=>{if(!d())return;k=P;let Q=!!k.lowLatency;Q!==this.lowLatency&&g(Q);let j=0;for(let ze=0;ze<k.dur.length;++ze)j+=k.dur[ze];j>0&&((0,We.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(j/k.dur.length)),i({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,M(V(U))},()=>this._handleNetworkError())},nextChunk:ie}},E=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,We.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:w=>{let{videoElement:k,logger:q}=this.params,z=I(e.jidxUrl),de,H,ne,J,V=0,ie,Z,oe,M=()=>{ie&&(clearTimeout(ie),ie=void 0);let ae=Math.max(WA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=V+ae,ke=Ie(),Re=Math.min(1e4,Ee-ke);V=ke;let qt=()=>{l||d()&&z.seek(()=>{d()&&(V=Ie(),U(),M())})};Re>0?ie=window.setTimeout(()=>{this.paused?M():qt()},Re):qt()},U=()=>{let ae;for(;ae=z.nextChunk(J);)J=ae,or(ae);let Ee=z.nextChunk(ne);if(Ee){if(ne&&Ee.discontinuity){q("Detected discontinuity; restarting playback"),this.paused?M():(E(),this._initPlayerWith(e));return}ze(Ee)}else M()},P=(ae,Ee)=>{if(!d()||!this.sourceBuffer)return;let ke,Re,qt,$r=Ut=>{window.setTimeout(()=>{d()&&P(ae,Ee)},Ut)};if(this.sourceBuffer.updating)q("Source buffer is updating; delaying appendBuffer"),$r(100);else{let Ut=Ie(),ur=k.currentTime;!this.paused&&k.buffered.length>1&&Z===ur&&Ut-oe>500&&(q("Stall suspected; trying to fix"),this._fixupStall()),Z!==ur&&(Z=ur,oe=Ut);let Lr=this._getBufferSizeSec();if(Lr>30)q(`Buffered ${Lr} seconds; delaying appendBuffer`),$r(2e3);else try{this.sourceBuffer.appendBuffer(ae),this.videoPlayStarted?(this.bufferStates.push({ts:Ut,buf:Lr}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(mi){if(mi.name==="QuotaExceededError")q("QuotaExceededError; delaying appendBuffer"),qt=this.sourceBuffer.buffered.length,qt!==0&&(ke=this.sourceBuffer.buffered.start(0),Re=ur,Re-ke>4&&this.sourceBuffer.remove(ke,Re-3)),$r(1e3);else throw mi}}},Q=()=>{H&&de&&(q([`Appending chunk, sz=${H.byteLength}:`,JSON.stringify(ne)]),P(H,function(){H=null,U()}))},j=ae=>e.fragUrlTemplate.replace("%%id%%",ae.chunkIdx),ze=ae=>{d()&&h(j(ae),(Ee,ke)=>{if(d()){if(ke/=1e3,H=Ee,ne=ae,n=ae.startTS,ke){let Re=Math.min(10,ae.dur/ke);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Re:Re}Q()}},()=>this._handleNetworkError())},or=ae=>{d()&&((0,We.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(j(ae),!1)))},Pt=ae=>{d()&&(e.cachedHeader=ae,P(ae,()=>{de=!0,Q()}))};s=!0,z.seek(ae=>{if(d()){if(V=Ie(),!ae){M();return}J=ae,!(0,We.isNullable)(w)||ae.startTS>w?ze(ae):(ne=ae,U())}},w),e.cachedHeader?Pt(e.cachedHeader):p(e.headerUrl,Pt,()=>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,We.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,We.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,We.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,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.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 m=Ie();if(this.chunkRateEstimator.addInterval(p,m,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:v}),!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&&Nu(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=Ie();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=si(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(en).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;Ne(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 Bb=X(Wr(),1),he=require("@vkontakte/videoplayer-shared/es2015"),Uu=class{constructor(){this.onDroopedVideoFramesLimit$=new he.Subject;this.subscription=new he.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new he.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,he.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,he.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,he.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,he.interval)(this.droppedFramesChecker.checkTime).pipe((0,he.filter)(()=>this.playing),(0,he.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,he.debounce)(this.droppedFramesChecker.checkTime)),r=(0,he.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,Bb.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,he.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}},tn=Uu;var rn=require("@vkontakte/videoplayer-shared/es2015"),Vb=require("@vkontakte/videoplayer-shared/es2015");var Zi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var YA=(a,e)=>new rn.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Zi()))},A(A({},r),e));i.observe(a);let s=(0,Vb.fromEvent)(document,"visibilitychange").pipe((0,rn.map)(n=>!document.hidden||Zi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ze=YA;var zA=["paused","playing","ready"],KA=["paused","playing","ready"],ea=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new W("stopped");this.representations$=new O.ValueSubject([]);this.droppedFramesManager=new tn;this.maxSeekBackTime$=new O.ValueSubject(1/0);this.zeroTime$=new O.ValueSubject(void 0);this.liveOffset=new Lt;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:O.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=er(u.name))!=null?r:(0,O.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p=A({},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,O.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,Hu.default)(KA,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,Hu.default)(zA,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(we(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(we(this.params.source.url,u))}return;default:return(0,O.assertNever)(e)}};this.textTracksManager=new Je(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:O.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,O.merge)(this.videoState.stateChangeStarted$.pipe((0,O.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,O.map)(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Be(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(Te(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=_e(this.video);this.subscription.add(this.representations$.pipe((0,O.map)(i=>i.map(({track:s})=>s)),(0,O.filter)(i=>!!i.length),(0,O.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,O.filterChanged)(),(0,O.map)(i=>-i/1e3)).subscribe(this.params.output.duration$)).add((0,O.combine)({zeroTime:this.zeroTime$.pipe((0,O.filter)(O.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(yt(this.video,this.params.desiredState.isLooped,t)).add(Oe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Xe(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(Ze(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&(0,O.videoQualityToHeight)(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).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,O.assertNever)(i.to)}},t)).add((0,O.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.observableFrom)(["init"])).pipe((0,O.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),Ve(this.video)}createLiveDashPlayer(){let e=new Ji({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,m;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,O.isNonNullable)(t)?t:rr(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=(m=e.find(({track:v})=>v.id===s))==null?void 0:m.representation;(0,O.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,O.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(we(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Ob=ea;var nS=X(lt(),1);var It=(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 F=require("@vkontakte/videoplayer-shared/es2015");var an=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}},ni=class extends an{constructor(){super(),this.listeners||an.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)}},ta=class{constructor(){Object.defineProperty(this,"signal",{value:new ni,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&&(ta.prototype[Symbol.toStringTag]="AbortController",ni.prototype[Symbol.toStringTag]="AbortSignal");function sn(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 ju(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!sn({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,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ra=sn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),_b=ra?ju({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,dt=ra?_b.fetch:window.fetch,YC=ra?_b.Request:window.Request,Ae=ra?ta:window.AbortController,zC=ra?ni:window.AbortSignal;var Sl=X(Qu(),1);var fn=X(ai(),1);var Ct=()=>window.ManagedMediaSource||window.MediaSource,nn=()=>{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 Et=require("@vkontakte/videoplayer-shared/es2015");var et=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,ia={mms:nn(),mse:ag(),hls:!!((ng=et.canPlayType)!=null&&ng.call(et,"application/x-mpegurl")||(og=et.canPlayType)!=null&&og.call(et,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ug,lg,Fe={mp4:!!((ug=et.canPlayType)!=null&&ug.call(et,"video/mp4")),webm:!!((lg=et.canPlayType)!=null&&lg.call(et,"video/webm")),cmaf:!0},un,cg,ln,dg,cn,pg,dn,hg,pn,fg,hn,mg,qe={h264:!!((cg=(un=Ct())==null?void 0:un.isTypeSupported)!=null&&cg.call(un,Tk)),h265:!!((dg=(ln=Ct())==null?void 0:ln.isTypeSupported)!=null&&dg.call(ln,Ik)),vp9:!!((pg=(cn=Ct())==null?void 0:cn.isTypeSupported)!=null&&pg.call(cn,bg)),av1:!!((hg=(dn=Ct())==null?void 0:dn.isTypeSupported)!=null&&hg.call(dn,gg)),aac:!!((fg=(pn=Ct())==null?void 0:pn.isTypeSupported)!=null&&fg.call(pn,Ek)),opus:!!((mg=(hn=Ct())==null?void 0:hn.isTypeSupported)!=null&&mg.call(hn,xk))},oi=(qe.h264||qe.h265)&&qe.aac,xr,Pk=()=>$(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(N(A({},a),{video:N(A({},a.video),{contentType:gg})})),window.navigator.mediaCapabilities.decodingInfo(N(A({},a),{video:N(A({},a.video),{contentType:bg})}))]);xr={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{Pk()}catch(a){console.error(a)}var ui=ia.hls&&Fe.mp4,vg=()=>Object.keys(qe).filter(a=>qe[a]),Sg=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=ia.mse&&(!r||!!window.MediaStreamTrack)||ia.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Fe.mp4&&oi;case"DASH_WEBM":return i&&Fe.webm&&qe.vp9&&qe.opus;case"DASH_WEBM_AV1":return i&&Fe.webm&&qe.av1&&qe.opus;case"DASH_STREAMS":return i&&(Fe.mp4&&oi||Fe.webm&&(qe.vp9||qe.av1)&&(qe.opus||qe.aac));case"DASH_LIVE":return i&&Fe.mp4&&oi;case"DASH_LIVE_CMAF":return i&&Fe.mp4&&oi&&Fe.cmaf;case"DASH_ONDEMAND":return i&&Fe.mp4&&oi;case"HLS":case"HLS_ONDEMAND":return ui||e&&i&&Fe.mp4&&oi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return ui;case"MPEG":return Fe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ia.webrtc&&ia.ws&&qe.h264&&(Fe.mp4||Fe.webm);default:return(0,Et.assertNever)(s)}})},on=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 xr?xr[t].smooth?[t,e]:xr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return xr?xr[t].powerEfficient?[t,e]:xr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,Et.assertNever)(a)}return[e,t]},yg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...on(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Et.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",...on(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...on(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...on(a),...i,"HLS","HLS_ONDEMAND"];default:(0,Et.assertNever)(e)}return ui?[...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=Et.clientChecker.isMac&&Et.clientChecker.isSafari;if(Et.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,Et.assertNever)(a)}else ui&&!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"]},Wu=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,fn.default)(t.value.split("."),0)}for(let t of a){let r=(0,fn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,fn.default)(e.value.split("."),0)};var Hg=X(Ug(),1),li=require("@vkontakte/videoplayer-shared/es2015"),jg=a=>{if(!a)return{id:"EmptyResponse",category:li.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:li.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:li.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:li.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:li.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var ir=(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 S=require("@vkontakte/videoplayer-shared/es2015");var mn=X(lt(),1),pi=X(ai(),1),bn=X(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),Gg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Qg=!Gg(window.requestIdleCallback)||!Gg(window.cancelIdleCallback),Ju=Qg?Uk:window.requestIdleCallback,sa=Qg?Hk:window.cancelIdleCallback;var Jv=X(Ys(),1);var tt=require("@vkontakte/videoplayer-shared/es2015");var jk=18,Wg=!1;try{Wg=tt.clientChecker.isSafari&&!!tt.clientChecker.macVersion&&tt.clientChecker.macVersion<=jk}catch(a){console.error(a)}var Zu=class{constructor(e){this.bufferFull$=new tt.Subject;this.error$=new tt.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:tt.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return $(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return $(this,null,function*(){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()})})}abort(e){return $(this,null,function*(){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:tt.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,tt.assertNever)(t)}}},Yg=Zu;var el=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/es2015");var ee=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 ci=class extends ee{};var na=class extends ee{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 oa=class extends ee{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 ua=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ce=class extends ee{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var la=class extends ce{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 ca=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var da=class extends ee{constructor(e,t){super(e,t),this.data=this.content}};var Pr=class extends ce{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 pa=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ha=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends ce{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 ma=class extends ce{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ba=class extends ce{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ga=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=class extends ce{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 Sa=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends ce{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ia=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ea=class extends ce{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 xa=class extends ce{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 Pa=class extends ce{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 wa=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Aa=class extends ce{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 ka=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var Qk={ftyp:oa,moov:ua,mvhd:la,moof:ca,mdat:da,sidx:Pr,trak:pa,mdia:ga,mfhd:Ta,tkhd:va,traf:Ia,tfhd:Ea,tfdt:xa,trun:Pa,minf:Sa,sv3d:ha,st3d:fa,prhd:ma,proj:ya,equi:ba,uuid:na,stbl:wa,stsd:Aa,avc1:ka,unknown:ci},Bt=class a{constructor(e={}){this.options=A({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=Qk[e];return r?new r(t,new a):new ci(t,new a)}};var ar=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 Pr(a,new Bt),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 Bt().parse(a),i=new ar(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 Bt().parse(a),r=new ar(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},Zk=a=>{var i;let t=new Bt().parse(a);return(i=new ar(t).find("sidx"))==null?void 0:i.timescale},eR=(a,e)=>{let r=new Bt().parse(a),s=new ar(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},tR=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 Bt().parse(a),i=new ar(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:tR,getIndexRange:()=>{},parseSegments:Kk,parseFeedableSegmentChunk:Xk,getChunkEndTime:eR,getServerLatencyTimestamps:Jk,getTimescaleFromIndex:Zk};var $a=X(lt(),1),Vt=require("@vkontakte/videoplayer-shared/es2015");var Xg=require("@vkontakte/videoplayer-shared/es2015");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=Ra(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=Ra(u),d=l*bt(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}},Ra=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*bt(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*bt(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*bt(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},pt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ra(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)}},wr=(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"&&wr(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 wr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=pt(o,n):s===17026?t=pt(o,n):s===17029&&(r=pt(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],rR=[231,22612,22743,167,171,163,160,175],iR=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return wr(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let v=pt(m,h);l=Ra(v)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=pt(m,h):p===17545?i=pt(m,h):p===21420&&l===475249515?u=pt(m,h):p===374648427?wr(m,({tag:v,type:I,value:E})=>v===30321?(c=pt(E,I)===1,!1):!0):s&&n&&(0,$a.default)(ev,p)&&(o=!0),!o}),(0,Vt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Vt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Vt.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}}}},aR=a=>{if((0,Vt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},sR=(a,e)=>{let t=!1,r=!1,i=o=>(0,Vt.isNonNullable)(o.time)&&(0,Vt.isNonNullable)(o.position),s=[],n;return wr(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=pt(l,u));break;case 183:break;case 241:n&&(n.position=pt(l,u));break;default:t&&(0,$a.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}}})},nR=a=>{let e=0,t=!1;try{wr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,$a.default)(rR,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,$a.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:iR,getIndexRange:aR,parseSegments:sR,parseFeedableSegmentChunk:nR};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 hl=X(Tv(),1),Wv=X(Wr(),1),Yv=X(Ov(),1),zv=X(ai(),1),fl=X(ii(),1);var _v=X(lt(),1),ol=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 Da=require("@vkontakte/videoplayer-shared/es2015");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=t$(),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 t$(){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=K(ai(),1);var Vv=require("@vkontakte/videoplayer-shared/es2015"),Bv=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?er(s):void 0)!=null?u:(0,Vv.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},_v=({id:a,bitrate:e})=>({id:a,bitrate:e}),Nv=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Fv=({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,Me=a=>a.type==="template",Ra=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var qv=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},Vt=(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,Uv.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,Hv.default)(s,parseInt(u,10),"0"))}return t},Gv=(a,e)=>{var k,q,Y,le,U,ee,te,_,re,X,ne,L,P,G,H,ve,Ye,Ft,Rr,ie,Ee,xe,ze,qt,$r,Ut,or,Lr,mi,xl,Pl,wl,Al,kl,Rl,$l,Ll,Ml,Dl,Cl,Ol,Vl,Bl,_l,Nl,Fl,ql,Ul,Hl,jl,Gl,Ql,Wl,Yl,zl,Kl,Xl,Jl,Zl,ec;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(it=>{var ue,ur;return(ur=(ue=it.textContent)==null?void 0:ue.trim())!=null?ur:""}),o=(k=(0,jv.default)(n,0))!=null?k:"",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],m=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g=[...s.getElementsByTagName("Period")],v=g.reduce((it,ue)=>N(A({},it),{[ue.id]:ue.children}),{}),T=g.reduce((it,ue)=>N(A({},it),{[ue.id]:ue.getAttribute("duration")}),{});p?d=qv(p):(0,cl.default)(T).filter(it=>it).length&&!u?d=(0,cl.default)(T).reduce((it,ue)=>{var ur;return it+((ur=qv(ue))!=null?ur:0)},0):m&&(d=parseInt(m,10));let I=0,x=(Y=(q=s.getAttribute("profiles"))==null?void 0:q.split(","))!=null?Y:[];for(let it of g.map(ue=>ue.id))for(let ue of v[it]){let ur=(le=ue.getAttribute("id"))!=null?le:"id"+(I++).toString(10),bi=(U=ue.getAttribute("mimeType"))!=null?U:"",An=(ee=ue.getAttribute("codecs"))!=null?ee:"",kn=(te=ue.getAttribute("contentType"))!=null?te:bi==null?void 0:bi.split("/")[0],PS=(re=(_=ue.getAttribute("profiles"))==null?void 0:_.split(","))!=null?re:[],tc=(ne=Ov((X=ue.getAttribute("lang"))!=null?X:""))!=null?ne:{},wS=(G=(P=(L=ue.querySelector("Label"))==null?void 0:L.textContent)==null?void 0:P.trim())!=null?G:void 0,AS=ue.querySelectorAll("Representation"),kS=ue.querySelector("SegmentTemplate"),RS=(ve=(H=ue.querySelector("Role"))==null?void 0:H.getAttribute("value"))!=null?ve:void 0,Mr=kn,fe={id:ur,language:tc.language,isDefault:RS==="main",label:wS,codecs:An,hdr:Mr==="video"&&il(An),mime:bi,representations:[]};for(let oe of AS){let Ht=(Ye=oe.getAttribute("lang"))!=null?Ye:void 0,gi=(Ft=oe.getAttribute("label"))!=null?Ft:void 0,Ka=(Ee=(ie=(Rr=oe.querySelector("BaseURL"))==null?void 0:Rr.textContent)==null?void 0:ie.trim())!=null?Ee:"",lr=new URL(Ka||o,e).toString(),jt=(xe=oe.getAttribute("mimeType"))!=null?xe:bi,Xa=(qt=(ze=oe.getAttribute("codecs"))!=null?ze:An)!=null?qt:"",Ja;if(kn==="text"){let Gt=oe.getAttribute("id")||"",Za=(($r=tc.privateuse)==null?void 0:$r.includes("x-auto"))||Gt.includes("_auto"),cr=oe.querySelector("SegmentTemplate");if(cr){let vi={representationId:(Ut=oe.getAttribute("id"))!=null?Ut:void 0,bandwidth:(or=oe.getAttribute("bandwidth"))!=null?or:void 0},es=parseInt((Lr=oe.getAttribute("bandwidth"))!=null?Lr:"",10)/1e3,ts=(xl=parseInt((mi=cr.getAttribute("startNumber"))!=null?mi:"",10))!=null?xl:1,Dr=parseInt((Pl=cr.getAttribute("timescale"))!=null?Pl:"",10),Rn=(wl=cr.querySelectorAll("SegmentTimeline S"))!=null?wl:[],Cr=cr.getAttribute("media");if(!Cr)continue;let rs=[],is=0,as="",Or=0,Si=ts,Re=0;for(let at of Rn){let dr=parseInt((Al=at.getAttribute("d"))!=null?Al:"",10),Ke=parseInt((kl=at.getAttribute("r"))!=null?kl:"",10)||0,Qt=parseInt((Rl=at.getAttribute("t"))!=null?Rl:"",10);Re=Number.isFinite(Qt)?Qt:Re;let pr=dr/Dr*1e3,Wt=Re/Dr*1e3;for(let ft=0;ft<Ke+1;ft++){let Yt=Vt(Cr,N(A({},vi),{segmentNumber:Si.toString(10),segmentTime:(Re+ft*dr).toString(10)})),Vr=(Wt!=null?Wt:0)+ft*pr,Ti=Vr+pr;Si++,rs.push({time:{from:Vr,to:Ti},url:Yt})}Re+=(Ke+1)*dr,is+=(Ke+1)*pr}Or=Re/Dr*1e3,as=Vt(Cr,N(A({},vi),{segmentNumber:Si.toString(10),segmentTime:Re.toString(10)}));let yi={time:{from:Or,to:1/0},url:as},Pt={type:"template",baseUrl:lr,segmentTemplateUrl:Cr,initUrl:"",totalSegmentsDurationMs:is,segments:rs,nextSegmentBeyondManifest:yi,timescale:Dr};Ja={id:Gt,kind:"text",segmentReference:Pt,profiles:[],duration:d,bitrate:es,mime:"",codecs:"",width:0,height:0,isAuto:Za}}else Ja={id:Gt,isAuto:Za,kind:"text",url:lr}}else{let Gt=(Ll=($l=oe.getAttribute("contentType"))!=null?$l:jt==null?void 0:jt.split("/")[0])!=null?Ll:kn,Za=(Dl=(Ml=ue.getAttribute("profiles"))==null?void 0:Ml.split(","))!=null?Dl:[],cr=parseInt((Cl=oe.getAttribute("width"))!=null?Cl:"",10),vi=parseInt((Ol=oe.getAttribute("height"))!=null?Ol:"",10),es=parseInt((Vl=oe.getAttribute("bandwidth"))!=null?Vl:"",10)/1e3,ts=(Bl=oe.getAttribute("frameRate"))!=null?Bl:"",Dr=(_l=oe.getAttribute("quality"))!=null?_l:void 0,Rn=ts?Cv(ts):void 0,Cr=(Nl=oe.getAttribute("id"))!=null?Nl:"id"+(I++).toString(10),rs=Gt==="video"?`${vi}p`:Gt==="audio"?`${es}Kbps`:Xa,is=`${Cr}@${rs}`,as=[...x,...PS,...Za],Or,Si=oe.querySelector("SegmentBase"),Re=(Fl=oe.querySelector("SegmentTemplate"))!=null?Fl:kS;if(Si){let Pt=(Ul=(ql=oe.querySelector("SegmentBase Initialization"))==null?void 0:ql.getAttribute("range"))!=null?Ul:"",[at,dr]=Pt.split("-").map(Yt=>parseInt(Yt,10)),Ke={from:at,to:dr},Qt=(Hl=oe.querySelector("SegmentBase"))==null?void 0:Hl.getAttribute("indexRange"),[pr,Wt]=Qt?Qt.split("-").map(Yt=>parseInt(Yt,10)):[],ft=Qt?{from:pr,to:Wt}:void 0;Or={type:"byteRange",url:lr,initRange:Ke,indexRange:ft}}else if(Re){let Pt={representationId:(jl=oe.getAttribute("id"))!=null?jl:void 0,bandwidth:(Gl=oe.getAttribute("bandwidth"))!=null?Gl:void 0},at=parseInt((Ql=Re.getAttribute("timescale"))!=null?Ql:"",10),dr=(Wl=Re.getAttribute("initialization"))!=null?Wl:"",Ke=Re.getAttribute("media"),Qt=(zl=parseInt((Yl=Re.getAttribute("startNumber"))!=null?Yl:"",10))!=null?zl:1,pr=Vt(dr,Pt);if(!Ke)throw new ReferenceError("No media attribute in SegmentTemplate");let Wt=(Kl=Re.querySelectorAll("SegmentTimeline S"))!=null?Kl:[],ft=[],Yt=0,Vr="",Ti=0;if(Wt.length){let ss=Qt,st=0;for(let Br of Wt){let mt=parseInt((Xl=Br.getAttribute("d"))!=null?Xl:"",10),hr=parseInt((Jl=Br.getAttribute("r"))!=null?Jl:"",10)||0,ns=parseInt((Zl=Br.getAttribute("t"))!=null?Zl:"",10);st=Number.isFinite(ns)?ns:st;let $n=mt/at*1e3,Ln=st/at*1e3;for(let os=0;os<hr+1;os++){let LS=Vt(Ke,N(A({},Pt),{segmentNumber:ss.toString(10),segmentTime:(st+os*mt).toString(10)})),rc=(Ln!=null?Ln:0)+os*$n,MS=rc+$n;ss++,ft.push({time:{from:rc,to:MS},url:LS})}st+=(hr+1)*mt,Yt+=(hr+1)*$n}Ti=st/at*1e3,Vr=Vt(Ke,N(A({},Pt),{segmentNumber:ss.toString(10),segmentTime:st.toString(10)}))}else if((0,$a.isNonNullable)(d)){let st=parseInt((ec=Re.getAttribute("duration"))!=null?ec:"",10)/at*1e3,Br=Math.ceil(d/st),mt=0;for(let hr=1;hr<Br;hr++){let ns=Vt(Ke,N(A({},Pt),{segmentNumber:hr.toString(10),segmentTime:mt.toString(10)}));ft.push({time:{from:mt,to:mt+st},url:ns}),mt+=st}Ti=mt,Vr=Vt(Ke,N(A({},Pt),{segmentNumber:Br.toString(10),segmentTime:mt.toString(10)}))}let $S={time:{from:Ti,to:1/0},url:Vr};Or={type:"template",baseUrl:lr,segmentTemplateUrl:Ke,initUrl:pr,totalSegmentsDurationMs:Yt,segments:ft,nextSegmentBeyondManifest:$S,timescale:at}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Gt||!jt)continue;let yi={video:"video",audio:"audio",text:"text"}[Gt];if(!yi)continue;Mr||(Mr=yi),Ja={id:is,kind:yi,segmentReference:Or,profiles:as,duration:d,bitrate:es,mime:jt,codecs:Xa,width:cr,height:vi,fps:Rn,quality:Dr}}fe.language||(fe.language=Ht),fe.label||(fe.label=gi),fe.mime||(fe.mime=jt),fe.codecs||(fe.codecs=Xa),fe.hdr||(fe.hdr=Mr==="video"&&il(Xa)),fe.representations.push(Ja)}if(Mr){let oe=i[Mr].find(Ht=>Ht.id===fe.id);if(oe&&fe.representations.every(Ht=>Me(Ht.segmentReference)))for(let Ht of oe.representations){let gi=fe.representations.find(jt=>jt.id===Ht.id),Ka=gi==null?void 0:gi.segmentReference,lr=Ht.segmentReference;lr.segments.push(...Ka.segments),lr.nextSegmentBeyondManifest=Ka.nextSegmentBeyondManifest}else i[Mr].push(fe)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var Qv=K(lt(),1),pl=require("@vkontakte/videoplayer-shared/es2015"),Fe=(a,e)=>(0,pl.isNonNullable)(a)&&(0,pl.isNonNullable)(e)&&a.readyState==="open"&&(0,Qv.default)([...a.activeSourceBuffers],e);var La=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new E.ValueSubject(0);this.currentLowLatencySegmentLength$=new E.ValueSubject(0);this.currentSegmentLength$=new E.ValueSubject(0);this.onLastSegment$=new E.ValueSubject(!1);this.fullyBuffered$=new E.ValueSubject(!1);this.playingRepresentation$=new E.ValueSubject(void 0);this.playingRepresentationInit$=new E.ValueSubject(void 0);this.error$=new E.Subject;this.gaps=[];this.subscription=new E.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ke;this.switchAbortController=new ke;this.destroyAbortController=new ke;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,E.abortable)(this.destroyAbortController.signal,function(e){return ge(this,null,function*(){let t=this.representations.get(e);(0,E.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 Hg(this.sourceBuffer),this.subscription.add((0,E.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,E.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:E.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Fe(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ku(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=It(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,E.assertNonNullable)(r,"No init buffer for starting representation"),(0,E.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.switchToOld=(0,E.abortable)(this.destroyAbortController.signal,function(e,t=!1){return ge(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,E.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,E.isNullable)(s)||(0,E.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,E.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Fe(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,E.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Dn(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,E.abortable)(this.destroyAbortController.signal,function(e){return ge(this,null,function*(){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(m=>m.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!Me(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,E.assertNonNullable)(i);let s=this.segments.get(r);(0,E.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,E.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}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ke,(0,E.abortable)(this.switchAbortController.signal,function(r,i=!1){return ge(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);(0,E.assertNonNullable)(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if((0,E.isNullable)(o)||(0,E.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),(0,E.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Fe(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,E.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,E.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return $(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ke,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if((0,E.isNullable)(e)||(0,E.isNullable)(this.downloadingRepresentationId)||(0,E.isNullable)(this.playingRepresentationId)||(0,E.isNullable)(this.sourceBuffer)||!Fe(this.mediaSource,this.sourceBuffer)||(0,E.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,E.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);(0,E.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=It(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=It(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(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,pi.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&It(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,pi.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,E.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||!Me(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>N(A({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,pi.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,E.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(!Me(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=Vt(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&&sa&&sa(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&sa&&sa(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}},m)=>{let g=p<=r&&h>=r,v=p>r||g||m===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&p<=r+T||h<=r+T;return(d==="none"||d==="partially_ejected"&&v&&I&&this.sourceBuffer&&Fe(this.mediaSource,this.sourceBuffer)&&!(ir(this.sourceBuffer.buffered,p)&&ir(this.sourceBuffer.buffered,h)))&&v&&I});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}loadSegments(e,t,r="auto"){return $(this,null,function*(){Me(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return $(this,null,function*(){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&&(yield(0,E.abortable)(o,function(){return ge(this,null,function*(){let c=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,E.now)(),!c)return;let d=new DataView(c),p=ka(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?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-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())Me(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return $(this,null,function*(){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&&(yield(0,E.abortable)(n,function(){return ge(this,null,function*(){let u=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,E.fromEvent)(window,"online").pipe((0,E.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=(0,E.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ra(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Me(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,pi.default)(e,0).byte.from,to:(0,pi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>$(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,E.now)(),yield 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:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!Me(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,E.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:E.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)}onSomeTemplateDataLoaded(n){return $(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){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){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=ka(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return $(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,m=d<i,g=p<=i;if(!m)continue;let v=ka(u.mime);if(c.status==="downloading"&&g){c.status="downloaded";let T=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(T,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let T=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),I=l.loadedBytes===h?T:v.parseFeedableSegmentChunk(T);I!=null&&I.byteLength&&(c.status="partially_fed",l.feedingBytes+=I.byteLength,(yield this.sourceBufferTaskQueue.append(I,s))&&!s.aborted?(l.fedBytes+=I.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!((0,E.isNullable)(this.sourceBuffer)||!Fe(this.mediaSource,this.sourceBuffer))){!this.isLive&&E.clientChecker.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ir(this.sourceBuffer.buffered,e.segment.time.from,100)&&ir(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:E.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,Wv.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return $(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,E.abortable)(this.destroyAbortController.signal,function(){return ge(this,null,function*(){let o=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ka(e.mime),i)).then(o=>$(this,null,function*(){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&&Me(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:E.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return $(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return $(this,null,function*(){if(!this.sourceBuffer||!Fe(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,E.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(A({},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?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return $(this,null,function*(){if(!this.sourceBuffer||!Fe(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||!Fe(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||!Fe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,E.isNullable)(e)?0:It(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Fe(this.mediaSource,this.sourceBuffer)))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||!Fe(this.mediaSource,this.sourceBuffer))){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:E.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,E.isNullable)(this.sourceBuffer)||!Fe(this.mediaSource,this.sourceBuffer)||(0,E.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")}}};var Ma=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Yv=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 J=require("@vkontakte/videoplayer-shared/es2015");var zv=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 J.ValueSubject(void 0);this.lastConnectionReused$=new J.ValueSubject(void 0);this.lastRequestFirstBytes$=new J.ValueSubject(void 0);this.abortAllController=new ke;this.subscription=new J.Subscription;this.fetchManifest=(0,J.abortable)(this.abortAllController.signal,function(e){return ge(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ma(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=zv(r));let i=yield dt(r,{signal:this.abortAllController.signal}).catch(Da);return i?(t.log("success",(0,J.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",(0,J.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,J.abortable)(this.abortAllController.signal,function(l){return ge(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var _,re;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let X=new URL(c,location.href);X.searchParams.append("bytes",`${r.from}-${r.to}`),c=X.toString();break}default:(0,J.assertNever)(t)}this.requestQuic&&(c=Ma(c));let h=this.abortAllController.signal,m;if(n){let X=new ke;if(m=(0,J.merge)((0,J.fromEvent)(this.abortAllController.signal,"abort"),(0,J.fromEvent)(n,"abort")).subscribe(()=>{try{X.abort()}catch(ne){Da(ne)}}),this.abortAllController.signal.aborted||n.aborted)try{X.abort()}catch(ne){Da(ne)}h=X.signal}let g=(0,J.now)();p.log("startRequest",(0,J.flattenObject)({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:g}));let v=yield dt(c,{priority:s,headers:d,signal:h}).catch(Da),T=(0,J.now)();if(!v)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(T-g),!v.ok||!v.body){m==null||m.unsubscribe();let X=`Fetch error ${v.status}: ${v.statusText}`;return p.error("error",{message:X}),p.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!i&&!o){m==null||m.unsubscribe();let X=(0,J.now)(),ne={requestStartedAt:g,requestEndedAt:X,duration:X-g};return p.log("endRequest",(0,J.flattenObject)(ne)),p.end(),v.arrayBuffer()}let[I,x]=v.body.tee(),w=I.getReader();o&&((re=this.throughputEstimator)==null||re.trackStream(x,u));let k=0,q=new Uint8Array(0),Y=!1,le=X=>{m==null||m.unsubscribe(),Y=!0,Da(X)},U=(0,J.abortable)(h,function(L){return ge(this,arguments,function*({done:X,value:ne}){if(k===0&&this.lastRequestFirstBytes$.next((0,J.now)()-g),h.aborted){m==null||m.unsubscribe();return}if(!X&&ne){let P=new Uint8Array(q.length+ne.length);P.set(q),P.set(ne,q.length),q=P,k+=ne.byteLength,i==null||i(new DataView(q.buffer),k),yield w==null?void 0:w.read().then(U,le)}})}.bind(this));yield w==null?void 0:w.read().then(U,le),m==null||m.unsubscribe();let ee=(0,J.now)(),te={failed:Y,requestStartedAt:g,requestEndedAt:ee,duration:ee-g};return Y?(p.error("endRequest",(0,J.flattenObject)(te)),p.end(),null):(p.log("endRequest",(0,J.flattenObject)(te)),p.end(),q.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,J.abortable)(this.abortAllController.signal,function(e,t,r){return ge(this,null,function*(){var T;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),m=(T=e.indexRange)!=null?T:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let I=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!I)return null;g=new DataView(I)}let v=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(d),segments:v}})}.bind(this));this.fetchTemplateRepresentation=(0,J.abortable)(this.abortAllController.signal,function(e,t){return ge(this,null,function*(){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(A({},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}=Yv(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return $(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,J.assertNever)(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Da=a=>{if(!Ra(a))throw a};var wr=(a,e,t)=>t*e+(1-t)*a,hl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Kv=(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 Ca=require("@vkontakte/videoplayer-shared/es2015");var sr=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 Ca.ValueSubject(e.initial),this.debounced$=new Ca.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+=bt(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,Ca.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 sr{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=wr(this.slow,e,this.params.emaAlphaSlow),this.fast=wr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var fn=class extends sr{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=hl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=wr(this.emaSmoothed,e,this.params.emaAlpha);let r=Kv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var mn=class extends sr{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?wr(this.smoothed,t,this.params.emaAlpha):t}};var Ar=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 fn({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(A({initial:e,label:"liveEdgeDelay"},t))}};var fl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var bn=require("@vkontakte/videoplayer-shared/es2015");var Oa=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(N(A({},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&&Me(t.segmentReference))}};var e$=["timeupdate","progress","play","seeked","stalled","waiting"],t$=["timeupdate","progress","loadeddata","playing","seeked"];var gn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new Q("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.currentLiveTextRepresentation$=new S.ValueSubject(null);this.isLive$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLatency$=new S.ValueSubject(void 0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.isLowLatency$=new S.ValueSubject(!1);this.isActiveLowLatency$=new S.ValueSubject(!1);this.currentStallDuration$=new S.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new S.ValueSubject(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new ke;this.initManifest=(0,S.abortable)(this.destroyController.signal,function(e,t,r){return ge(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ae(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:S.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,S.abortable)(this.destroyController.signal,function(){return ge(this,null,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:S.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=Ng(e))!=null?n:{id:"ManifestParsing",category:S.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,m;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((m=(h=Dt())==null?void 0:h.isTypeSupported)!=null&&m.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:m})=>r(u,h,m)),d=new Set(c.map(({codecs:h})=>h)),p=gg(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=i.video.some(v=>v.hdr),g=i.video.some(v=>!v.hdr);S.clientChecker.isHDR&&h&&m?i.video=i.video.filter(v=>v.hdr):g&&(i.video=i.video.filter(v=>!v.hdr))}}let s=N(A({},t),{streams:i});return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(s)),s})}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,function(e,t,r){return ge(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add((0,S.fromEvent)(p,"error").pipe((0,S.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?eg():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.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new La("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new La("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Oa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Oa(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,S.interval)(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=js(this.manifestUrlString,2);this.manifestUrlString=Ae(this.manifestUrlString,m+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...t$.map(p=>(0,S.fromEvent)(this.element,p))).pipe((0,S.map)(p=>this.element?It(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(h=>fl(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add((0,S.combine)({isActiveLowLatency:this.isActiveLowLatency$.pipe((0,S.filterChanged)()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe((0,S.filter)(({isActiveLowLatency:h,currentLowLatencySegmentLength:m})=>h&&!!m)).subscribe(({currentLowLatencySegmentLength:h})=>{let m=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(m,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add((0,S.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,S.filter)(({isLive:h})=>h),(0,S.map)(h=>A({},h)),(0,S.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,S.map)(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let v=js(this.manifestUrlString,2);return(h/2+m+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,S.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:m})=>{if(!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-g,x=1;Math.abs(I)>v&&(x=1+Math.sign(I)*T),fl(this.element,x)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,v;let m=0;if(h){let T=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;m=Math.min(...this.bufferManagers.map(x=>{var w,k;return(k=(w=x.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?k:T}))-T}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(g=>$(this,[g],function*({liveLoadBufferLength:h,bufferLength:m}){if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let v=this.element.playbackRate,T=js(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,q=isFinite(h)?h:m,Y=this.isActiveLowLatency$.getValue(),le=I<=this.tuning.live.activeLiveDelay&&T===0;this.isActiveLowLatency$.next(Y&&le);let U="none";if(Y?U="active_low_latency":this.isLowLatency$.getValue()&&le?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(ee=>ee.proceedLowLatencyLive()),U="active_low_latency"):T!==0&&q<x?U="live_forward_buffering":q<x+k&&(U="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),U==="live_forward_buffering"||U==="live_with_target_offset"){let ee=p-(x+w),te=this.normolizeLiveOffset(Math.trunc(T+ee/v)),_=Math.abs(te-T),re;!h||_<=this.tuning.dashCmafLive.offsetCalculationError?re=T:te>0&&_>this.tuning.dashCmafLive.offsetCalculationError?re=te:re=0,this.manifestUrlString=Ae(this.manifestUrlString,re,2)}U!=="none"&&U!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=(0,S.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,S.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,S.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:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{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,ml.default)((0,ml.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Me(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,S.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{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,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:S.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=Ar.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,A({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return $(this,null,function*(){var r,i,s;(0,S.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=Ae(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...e$.map(e=>(0,S.fromEvent)(this.element,e)),(0,S.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&ir(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,g,v,T,I,x,w,k,q;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=(0,S.now)(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(I=(T=this.videoBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?I:0,c=(w=(x=this.audioBufferManager)==null?void 0:x.getForwardBufferDuration())!=null?w: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),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let Y=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(Y),(q=this.audioBufferManager)==null||q.maintain(Y),i.position=Y}this.tracer.log("stallIntervalCallback",(0,S.flattenObject)(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return $(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){return $(this,null,function*(){var i,s,n,o,u;(0,S.assertNonNullable)(this.element),(0,S.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),ir(this.element.buffered,r)||(yield 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,S.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,S.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return $(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield 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={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=N(A({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,S.flattenObject)(t)))}}};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/bt(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=A({},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*bt(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 Jv=`attribute vec2 a_vertex;
|
|
70
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var ll=X(ai(),1);var qv=require("@vkontakte/videoplayer-shared/es2015"),Uv=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?er(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}),Gv=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),cl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,ll.default)(r.split("."),0),isDefault:i}),dl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,ll.default)(i.split("."),0)}),pl=a=>"url"in a,De=a=>a.type==="template",Ma=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Qv=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},Ot=(a,e)=>{let t=a;t=(0,hl.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,hl.default)(t,n,(o,u)=>(0,Da.isNullable)(s)?o:(0,Da.isNullable)(u)?s:(0,Yv.default)(s,parseInt(u,10),"0"))}return t},Kv=(a,e)=>{var k,q,z,de,H,ne,J,V,ie,Z,oe,M,U,P,Q,j,ze,or,Pt,ae,Ee,ke,Re,qt,$r,Ut,ur,Lr,mi,kl,Rl,$l,Ll,Ml,Dl,Cl,Bl,Vl,Ol,_l,Nl,Fl,ql,Ul,Hl,jl,Gl,Ql,Wl,Yl,zl,Kl,Xl,Jl,Zl,ec,tc,rc,ic,ac,sc;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(it=>{var le,lr;return(lr=(le=it.textContent)==null?void 0:le.trim())!=null?lr:""}),o=(k=(0,zv.default)(n,0))!=null?k:"",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],m=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g=[...s.getElementsByTagName("Period")],v=g.reduce((it,le)=>N(A({},it),{[le.id]:le.children}),{}),I=g.reduce((it,le)=>N(A({},it),{[le.id]:le.getAttribute("duration")}),{});p?d=Qv(p):(0,fl.default)(I).filter(it=>it).length&&!u?d=(0,fl.default)(I).reduce((it,le)=>{var lr;return it+((lr=Qv(le))!=null?lr:0)},0):m&&(d=parseInt(m,10));let E=0,x=(z=(q=s.getAttribute("profiles"))==null?void 0:q.split(","))!=null?z:[];for(let it of g.map(le=>le.id))for(let le of v[it]){let lr=(de=le.getAttribute("id"))!=null?de:"id"+(E++).toString(10),bi=(H=le.getAttribute("mimeType"))!=null?H:"",Mn=(ne=le.getAttribute("codecs"))!=null?ne:"",Dn=(J=le.getAttribute("contentType"))!=null?J:bi==null?void 0:bi.split("/")[0],$S=(ie=(V=le.getAttribute("profiles"))==null?void 0:V.split(","))!=null?ie:[],nc=(oe=Fv((Z=le.getAttribute("lang"))!=null?Z:""))!=null?oe:{},Za=(P=(U=(M=le.querySelector("Label"))==null?void 0:M.textContent)==null?void 0:U.trim())!=null?P:void 0,LS=le.querySelectorAll("Representation"),MS=le.querySelector("SegmentTemplate"),DS=(j=(Q=le.querySelector("Role"))==null?void 0:Q.getAttribute("value"))!=null?j:void 0,Mr=Dn,me={id:lr,language:nc.language,isDefault:DS==="main",label:Za,codecs:Mn,hdr:Mr==="video"&&ol(Mn),mime:bi,representations:[]};for(let ue of LS){let Ht=(ze=ue.getAttribute("lang"))!=null?ze:void 0,gi=(Pt=(or=Za!=null?Za:le.getAttribute("label"))!=null?or:ue.getAttribute("label"))!=null?Pt:void 0,es=(ke=(Ee=(ae=ue.querySelector("BaseURL"))==null?void 0:ae.textContent)==null?void 0:Ee.trim())!=null?ke:"",cr=new URL(es||o,e).toString(),jt=(Re=ue.getAttribute("mimeType"))!=null?Re:bi,ts=($r=(qt=ue.getAttribute("codecs"))!=null?qt:Mn)!=null?$r:"",rs;if(Dn==="text"){let Gt=ue.getAttribute("id")||"",is=((Ut=nc.privateuse)==null?void 0:Ut.includes("x-auto"))||Gt.includes("_auto"),dr=ue.querySelector("SegmentTemplate");if(dr){let vi={representationId:(ur=ue.getAttribute("id"))!=null?ur:void 0,bandwidth:(Lr=ue.getAttribute("bandwidth"))!=null?Lr:void 0},as=parseInt((mi=ue.getAttribute("bandwidth"))!=null?mi:"",10)/1e3,ss=(Rl=parseInt((kl=dr.getAttribute("startNumber"))!=null?kl:"",10))!=null?Rl:1,Dr=parseInt(($l=dr.getAttribute("timescale"))!=null?$l:"",10),Cn=(Ll=dr.querySelectorAll("SegmentTimeline S"))!=null?Ll:[],Cr=dr.getAttribute("media");if(!Cr)continue;let ns=[],os=0,us="",Br=0,Si=ss,$e=0;for(let at of Cn){let pr=parseInt((Ml=at.getAttribute("d"))!=null?Ml:"",10),Ke=parseInt((Dl=at.getAttribute("r"))!=null?Dl:"",10)||0,Qt=parseInt((Cl=at.getAttribute("t"))!=null?Cl:"",10);$e=Number.isFinite(Qt)?Qt:$e;let hr=pr/Dr*1e3,Wt=$e/Dr*1e3;for(let ft=0;ft<Ke+1;ft++){let Yt=Ot(Cr,N(A({},vi),{segmentNumber:Si.toString(10),segmentTime:($e+ft*pr).toString(10)})),Vr=(Wt!=null?Wt:0)+ft*hr,Ti=Vr+hr;Si++,ns.push({time:{from:Vr,to:Ti},url:Yt})}$e+=(Ke+1)*pr,os+=(Ke+1)*hr}Br=$e/Dr*1e3,us=Ot(Cr,N(A({},vi),{segmentNumber:Si.toString(10),segmentTime:$e.toString(10)}));let yi={time:{from:Br,to:1/0},url:us},wt={type:"template",baseUrl:cr,segmentTemplateUrl:Cr,initUrl:"",totalSegmentsDurationMs:os,segments:ns,nextSegmentBeyondManifest:yi,timescale:Dr};rs={id:Gt,kind:"text",segmentReference:wt,profiles:[],duration:d,bitrate:as,mime:"",codecs:"",width:0,height:0,isAuto:is}}else rs={id:Gt,isAuto:is,kind:"text",url:cr}}else{let Gt=(Vl=(Bl=ue.getAttribute("contentType"))!=null?Bl:jt==null?void 0:jt.split("/")[0])!=null?Vl:Dn,is=(_l=(Ol=le.getAttribute("profiles"))==null?void 0:Ol.split(","))!=null?_l:[],dr=parseInt((Nl=ue.getAttribute("width"))!=null?Nl:"",10),vi=parseInt((Fl=ue.getAttribute("height"))!=null?Fl:"",10),as=parseInt((ql=ue.getAttribute("bandwidth"))!=null?ql:"",10)/1e3,ss=(Ul=ue.getAttribute("frameRate"))!=null?Ul:"",Dr=(Hl=ue.getAttribute("quality"))!=null?Hl:void 0,Cn=ss?Nv(ss):void 0,Cr=(jl=ue.getAttribute("id"))!=null?jl:"id"+(E++).toString(10),ns=Gt==="video"?`${vi}p`:Gt==="audio"?`${as}Kbps`:ts,os=`${Cr}@${ns}`,us=[...x,...$S,...is],Br,Si=ue.querySelector("SegmentBase"),$e=(Gl=ue.querySelector("SegmentTemplate"))!=null?Gl:MS;if(Si){let wt=(Wl=(Ql=ue.querySelector("SegmentBase Initialization"))==null?void 0:Ql.getAttribute("range"))!=null?Wl:"",[at,pr]=wt.split("-").map(Yt=>parseInt(Yt,10)),Ke={from:at,to:pr},Qt=(Yl=ue.querySelector("SegmentBase"))==null?void 0:Yl.getAttribute("indexRange"),[hr,Wt]=Qt?Qt.split("-").map(Yt=>parseInt(Yt,10)):[],ft=Qt?{from:hr,to:Wt}:void 0;Br={type:"byteRange",url:cr,initRange:Ke,indexRange:ft}}else if($e){let wt={representationId:(zl=ue.getAttribute("id"))!=null?zl:void 0,bandwidth:(Kl=ue.getAttribute("bandwidth"))!=null?Kl:void 0},at=parseInt((Xl=$e.getAttribute("timescale"))!=null?Xl:"",10),pr=(Jl=$e.getAttribute("initialization"))!=null?Jl:"",Ke=$e.getAttribute("media"),Qt=(ec=parseInt((Zl=$e.getAttribute("startNumber"))!=null?Zl:"",10))!=null?ec:1,hr=Ot(pr,wt);if(!Ke)throw new ReferenceError("No media attribute in SegmentTemplate");let Wt=(tc=$e.querySelectorAll("SegmentTimeline S"))!=null?tc:[],ft=[],Yt=0,Vr="",Ti=0;if(Wt.length){let ls=Qt,st=0;for(let Or of Wt){let mt=parseInt((rc=Or.getAttribute("d"))!=null?rc:"",10),fr=parseInt((ic=Or.getAttribute("r"))!=null?ic:"",10)||0,cs=parseInt((ac=Or.getAttribute("t"))!=null?ac:"",10);st=Number.isFinite(cs)?cs:st;let Bn=mt/at*1e3,Vn=st/at*1e3;for(let ds=0;ds<fr+1;ds++){let BS=Ot(Ke,N(A({},wt),{segmentNumber:ls.toString(10),segmentTime:(st+ds*mt).toString(10)})),oc=(Vn!=null?Vn:0)+ds*Bn,VS=oc+Bn;ls++,ft.push({time:{from:oc,to:VS},url:BS})}st+=(fr+1)*mt,Yt+=(fr+1)*Bn}Ti=st/at*1e3,Vr=Ot(Ke,N(A({},wt),{segmentNumber:ls.toString(10),segmentTime:st.toString(10)}))}else if((0,Da.isNonNullable)(d)){let st=parseInt((sc=$e.getAttribute("duration"))!=null?sc:"",10)/at*1e3,Or=Math.ceil(d/st),mt=0;for(let fr=1;fr<Or;fr++){let cs=Ot(Ke,N(A({},wt),{segmentNumber:fr.toString(10),segmentTime:mt.toString(10)}));ft.push({time:{from:mt,to:mt+st},url:cs}),mt+=st}Ti=mt,Vr=Ot(Ke,N(A({},wt),{segmentNumber:Or.toString(10),segmentTime:mt.toString(10)}))}let CS={time:{from:Ti,to:1/0},url:Vr};Br={type:"template",baseUrl:cr,segmentTemplateUrl:Ke,initUrl:hr,totalSegmentsDurationMs:Yt,segments:ft,nextSegmentBeyondManifest:CS,timescale:at}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Gt||!jt)continue;let yi={video:"video",audio:"audio",text:"text"}[Gt];if(!yi)continue;Mr||(Mr=yi),rs={id:os,kind:yi,segmentReference:Br,profiles:us,duration:d,bitrate:as,mime:jt,codecs:ts,width:dr,height:vi,fps:Cn,quality:Dr}}me.language||(me.language=Ht),me.label||(me.label=gi),me.mime||(me.mime=jt),me.codecs||(me.codecs=ts),me.hdr||(me.hdr=Mr==="video"&&ol(ts)),me.representations.push(rs)}if(Mr){let ue=i[Mr].find(Ht=>Ht.id===me.id);if(ue&&me.representations.every(Ht=>De(Ht.segmentReference)))for(let Ht of ue.representations){let gi=me.representations.find(jt=>jt.id===Ht.id),es=gi==null?void 0:gi.segmentReference,cr=Ht.segmentReference;cr.segments.push(...es.segments),cr.nextSegmentBeyondManifest=es.nextSegmentBeyondManifest}else i[Mr].push(me)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var Xv=X(lt(),1),bl=require("@vkontakte/videoplayer-shared/es2015"),Ce=(a,e)=>(0,bl.isNonNullable)(a)&&(0,bl.isNonNullable)(e)&&a.readyState==="open"&&(0,Xv.default)([...a.activeSourceBuffers],e);var Ca=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 Ae;this.switchAbortController=new Ae;this.destroyAbortController=new Ae;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,function(e){return ge(this,null,function*(){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||!Ce(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,el(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=It(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let 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,function(e,t=!1){return ge(this,null,function*(){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||!Ce(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,yield new hs(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,function(e,t=!1){return ge(this,null,function*(){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||!Ce(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,yield new hs(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,function(e){return ge(this,null,function*(){var u,l;let t=(u=(0,bn.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(m=>m.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!De(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 Ae,(0,T.abortable)(this.switchAbortController.signal,function(r,i=!1){return ge(this,null,function*(){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||!Ce(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")}abort(){return $(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ae,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){var d,p;if((0,T.isNullable)(e)||(0,T.isNullable)(this.downloadingRepresentationId)||(0,T.isNullable)(this.playingRepresentationId)||(0,T.isNullable)(this.sourceBuffer)||!Ce(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(h=>e>=h.time.from&&e<h.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,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=It(this.sourceBuffer.buffered,e),m=i?i.time.to+n:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=i.time.to-e+n&&(s=m)}if(isFinite(this.bufferLimit)&&el(this.sourceBuffer.buffered)>=this.bufferLimit){let h=It(this.sourceBuffer.buffered,e),m=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,h<m);return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(r,t.segmentReference.type,s),u.length)){let h="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,mn.default)(u,i))h="high";else{let m=(0,pi.default)(u,0);m&&m.time.from-i.time.to>=this.forwardBufferTarget/2&&(h="low")}this.loadSegments(u,t,h)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!u.length&&It(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,pi.default)(r,-1),c=(p=(d=this.getDebugBufferState())==null?void 0:d.to)!=null?p:0;!this.isLive&&l&&c&&(this.fullyBuffered$.next(Math.abs(l.time.to-c*1e3)<n),this.onLastSegment$.next(i===l))}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,bn.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,bn.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||!De(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>N(A({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,pi.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(!De(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=Ot(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&&sa&&sa(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&sa&&sa(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}},m)=>{let g=p<=r&&h>=r,v=p>r||g||m===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"&&v&&E&&this.sourceBuffer&&Ce(this.mediaSource,this.sourceBuffer)&&!(ir(this.sourceBuffer.buffered,p)&&ir(this.sourceBuffer.buffered,h)))&&v&&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}loadSegments(e,t,r="auto"){return $(this,null,function*(){De(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return $(this,null,function*(){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&&(yield(0,T.abortable)(o,function(){return ge(this,null,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=yield 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?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ma(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())De(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return $(this,null,function*(){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&&(yield(0,T.abortable)(n,function(){return ge(this,null,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{yield 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),Ma(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(De(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,pi.default)(e,0).byte.from,to:(0,pi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>$(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)(),yield 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(!De(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,mn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return $(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){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){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=La(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return $(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,m=d<i,g=p<=i;if(!m)continue;let v=La(u.mime);if(c.status==="downloading"&&g){c.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(I,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),E=l.loadedBytes===h?I:v.parseFeedableSegmentChunk(I);E!=null&&E.byteLength&&(c.status="partially_fed",l.feedingBytes+=E.byteLength,(yield this.sourceBufferTaskQueue.append(E,s))&&!s.aborted?(l.fedBytes+=E.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!((0,T.isNullable)(this.sourceBuffer)||!Ce(this.mediaSource,this.sourceBuffer))){!this.isLive&&T.clientChecker.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ir(this.sourceBuffer.buffered,e.segment.time.from,100)&&ir(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",pl(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=Ju(()=>(0,Jv.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return $(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,T.abortable)(this.destroyAbortController.signal,function(){return ge(this,null,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(o=>$(this,null,function*(){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&&De(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})}dropBuffer(){return $(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return $(this,null,function*(){if(!this.sourceBuffer||!Ce(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(A({},u.time)),i=n(i);let l=pl(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,mn.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?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return $(this,null,function*(){if(!this.sourceBuffer||!Ce(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||!Ce(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||!Ce(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,T.isNullable)(e)?0:It(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Ce(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||!Ce(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=Ju(()=>{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)||!Ce(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")}}};var Ba=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 te=require("@vkontakte/videoplayer-shared/es2015");var eS=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var gn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new te.ValueSubject(void 0);this.lastConnectionReused$=new te.ValueSubject(void 0);this.lastRequestFirstBytes$=new te.ValueSubject(void 0);this.abortAllController=new Ae;this.subscription=new te.Subscription;this.fetchManifest=(0,te.abortable)(this.abortAllController.signal,function(e){return ge(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ba(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=eS(r));let i=yield dt(r,{signal:this.abortAllController.signal}).catch(Va);return i?(t.log("success",(0,te.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",(0,te.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,te.abortable)(this.abortAllController.signal,function(l){return ge(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var V,ie;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let Z=new URL(c,location.href);Z.searchParams.append("bytes",`${r.from}-${r.to}`),c=Z.toString();break}default:(0,te.assertNever)(t)}this.requestQuic&&(c=Ba(c));let h=this.abortAllController.signal,m;if(n){let Z=new Ae;if(m=(0,te.merge)((0,te.fromEvent)(this.abortAllController.signal,"abort"),(0,te.fromEvent)(n,"abort")).subscribe(()=>{try{Z.abort()}catch(oe){Va(oe)}}),this.abortAllController.signal.aborted||n.aborted)try{Z.abort()}catch(oe){Va(oe)}h=Z.signal}let g=(0,te.now)();p.log("startRequest",(0,te.flattenObject)({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:g}));let v=yield dt(c,{priority:s,headers:d,signal:h}).catch(Va),I=(0,te.now)();if(!v)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((V=this.throughputEstimator)==null||V.addRawRtt(I-g),!v.ok||!v.body){m==null||m.unsubscribe();let Z=`Fetch error ${v.status}: ${v.statusText}`;return p.error("error",{message:Z}),p.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!i&&!o){m==null||m.unsubscribe();let Z=(0,te.now)(),oe={requestStartedAt:g,requestEndedAt:Z,duration:Z-g};return p.log("endRequest",(0,te.flattenObject)(oe)),p.end(),v.arrayBuffer()}let[E,x]=v.body.tee(),w=E.getReader();o&&((ie=this.throughputEstimator)==null||ie.trackStream(x,u));let k=0,q=new Uint8Array(0),z=!1,de=Z=>{m==null||m.unsubscribe(),z=!0,Va(Z)},H=(0,te.abortable)(h,function(M){return ge(this,arguments,function*({done:Z,value:oe}){if(k===0&&this.lastRequestFirstBytes$.next((0,te.now)()-g),h.aborted){m==null||m.unsubscribe();return}if(!Z&&oe){let U=new Uint8Array(q.length+oe.length);U.set(q),U.set(oe,q.length),q=U,k+=oe.byteLength,i==null||i(new DataView(q.buffer),k),yield w==null?void 0:w.read().then(H,de)}})}.bind(this));yield w==null?void 0:w.read().then(H,de),m==null||m.unsubscribe();let ne=(0,te.now)(),J={failed:z,requestStartedAt:g,requestEndedAt:ne,duration:ne-g};return z?(p.error("endRequest",(0,te.flattenObject)(J)),p.end(),null):(p.log("endRequest",(0,te.flattenObject)(J)),p.end(),q.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,te.abortable)(this.abortAllController.signal,function(e,t,r){return ge(this,null,function*(){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),m=(I=e.indexRange)!=null?I:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let E=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!E)return null;g=new DataView(E)}let v=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(d),segments:v}})}.bind(this));this.fetchTemplateRepresentation=(0,te.abortable)(this.abortAllController.signal,function(e,t){return ge(this,null,function*(){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(A({},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)}fetchRepresentation(e,t,r="auto"){return $(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,te.assertNever)(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Va=a=>{if(!Ma(a))throw a};var Ar=(a,e,t)=>t*e+(1-t)*a,gl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,tS=(a,e,t,r)=>{let i=0,s=t,n=gl(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 Oa=require("@vkontakte/videoplayer-shared/es2015");var sr=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 Oa.ValueSubject(e.initial),this.debounced$=new Oa.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Me(`raw_${t}`),this.smoothedSeries$=new Me(`smoothed_${t}`),this.reportedSeries$=new Me(`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+=bt(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,Oa.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 vn=class extends sr{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ar(this.slow,e,this.params.emaAlphaSlow),this.fast=Ar(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Sn=class extends sr{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=gl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ar(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 yn=class extends sr{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?Ar(this.smoothed,t,this.params.emaAlpha):t}};var kr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new vn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Sn({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 yn(A({initial:e,label:"liveEdgeDelay"},t))}};var vl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var Tn=require("@vkontakte/videoplayer-shared/es2015");var _a=class a{constructor(e,t){this.currentRepresentation$=new Tn.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,Tn.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(N(A({},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&&De(t.segmentReference))}};var a$=["timeupdate","progress","play","seeked","stalled","waiting"],s$=["timeupdate","progress","loadeddata","playing","seeked"];var In=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new W("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.currentLiveTextRepresentation$=new S.ValueSubject(null);this.isLive$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLatency$=new S.ValueSubject(void 0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.isLowLatency$=new S.ValueSubject(!1);this.isActiveLowLatency$=new S.ValueSubject(!1);this.currentStallDuration$=new S.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new S.ValueSubject(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new Ae;this.initManifest=(0,S.abortable)(this.destroyController.signal,function(e,t,r){return ge(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=we(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:S.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,S.abortable)(this.destroyController.signal,function(){return ge(this,null,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:S.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:S.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,m;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((m=(h=Ct())==null?void 0:h.isTypeSupported)!=null&&m.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:m})=>r(u,h,m)),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,m=i.video.some(v=>v.hdr),g=i.video.some(v=>!v.hdr);S.clientChecker.isHDR&&h&&m?i.video=i.video.filter(v=>v.hdr):g&&(i.video=i.video.filter(v=>!v.hdr))}}let s=N(A({},t),{streams:i});return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(s)),s})}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,function(e,t,r){return ge(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add((0,S.fromEvent)(p,"error").pipe((0,S.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:S.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&&nn())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.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Ca("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Ca("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}_a.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new _a(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,S.interval)(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=zs(this.manifestUrlString,2);this.manifestUrlString=we(this.manifestUrlString,m+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...s$.map(p=>(0,S.fromEvent)(this.element,p))).pipe((0,S.map)(p=>this.element?It(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||vl(this.element,1)})),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add((0,S.combine)({isActiveLowLatency:this.isActiveLowLatency$.pipe((0,S.filterChanged)()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe((0,S.filter)(({isActiveLowLatency:h,currentLowLatencySegmentLength:m})=>h&&!!m)).subscribe(({currentLowLatencySegmentLength:h})=>{let m=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(m,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add((0,S.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,S.filter)(({isLive:h})=>h),(0,S.map)(h=>A({},h)),(0,S.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,S.map)(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let v=zs(this.manifestUrlString,2);return(h/2+m+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,S.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:m})=>{if(!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=h-g;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(E)>v&&(x=1+Math.sign(E)*I),vl(this.element,x)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,v;let m=0;if(h){let I=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;m=Math.min(...this.bufferManagers.map(x=>{var w,k;return(k=(w=x.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?k:I}))-I}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(g=>$(this,[g],function*({liveLoadBufferLength:h,bufferLength:m}){if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let v=this.element.playbackRate,I=zs(this.manifestUrlString,2),E=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(E,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,q=isFinite(h)?h:m,z=this.isActiveLowLatency$.getValue(),de=E<=this.tuning.live.activeLiveDelay&&I===0;this.isActiveLowLatency$.next(z&&de);let H="none";if(z?H="active_low_latency":this.isLowLatency$.getValue()&&de?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(ne=>ne.proceedLowLatencyLive()),H="active_low_latency"):I!==0&&q<x?H="live_forward_buffering":q<x+k&&(H="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),H==="live_forward_buffering"||H==="live_with_target_offset"){let ne=p-(x+w),J=this.normolizeLiveOffset(Math.trunc(I+ne/v)),V=Math.abs(J-I),ie;!h||V<=this.tuning.dashCmafLive.offsetCalculationError?ie=I:J>0&&V>this.tuning.dashCmafLive.offsetCalculationError?ie=J:ie=0,this.manifestUrlString=we(this.manifestUrlString,ie,2)}H!=="none"&&H!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=(0,S.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,S.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,S.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:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{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,Sl.default)((0,Sl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),De(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,S.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{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,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:S.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 gn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=kr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,A({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return $(this,null,function*(){var r,i,s;(0,S.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=we(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...a$.map(e=>(0,S.fromEvent)(this.element,e)),(0,S.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&ir(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,g,v,I,E,x,w,k,q;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=(0,S.now)(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(E=(I=this.videoBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?E:0,c=(w=(x=this.audioBufferManager)==null?void 0:x.getForwardBufferDuration())!=null?w: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),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let z=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(z),(q=this.audioBufferManager)==null||q.maintain(z),i.position=z}this.tracer.log("stallIntervalCallback",(0,S.flattenObject)(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return $(this,null,function*(){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)})}seek(e,t){return $(this,null,function*(){var i,s,n,o,u;(0,S.assertNonNullable)(this.element),(0,S.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),ir(this.element.buffered,r)||(yield 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,S.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,S.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}updateLive(){return $(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield 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={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=N(A({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,S.flattenObject)(t)))}}};var En=class{constructor(e,t){this.fov=e,this.orientation=t}};var xn=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/bt(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=A({},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*bt(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(Jv,this.gl.VERTEX_SHADER),r=this.createShader(Zv,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 Ie=require("@vkontakte/videoplayer-shared/es2015"),bl=class{constructor(){this.isSeeked$=new Ie.ValueSubject(!1);this.isBuffering$=new Ie.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Ie.Subscription}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add((0,Ie.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,Ie.filter)(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,Ie.combine)({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if((0,Ie.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:i,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=(0,Ie.now)(),p=n&&this.currentStallsCount>=n,h=i&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,m=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(p||h||m)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Ie.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,Ie.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},eS=bl;var qe=require("@vkontakte/videoplayer-shared/es2015"),Tn=class{constructor(){this.subscription=new qe.Subscription;this.pipSize$=new qe.ValueSubject(void 0);this.videoSize$=new qe.ValueSubject(void 0);this.elementSize$=new qe.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=qe.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,qe.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,qe.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,qe.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 kr=class{constructor(e){this.subscription=new F.Subscription;this.videoState=new Q("stopped");this.textTracksManager=new Je;this.droppedFramesManager=new Ks;this.stallsManager=new eS;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 zi;this.audioTrackSwitchHistory=new zi;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"),R(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"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&R(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"&&R(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"&&R(this.params.desiredState.playbackState,"paused");return;default:return(0,F.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.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(ye(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:F.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,F.filter)(c=>!!c.length),(0,F.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,F.map)(c=>c.to.state!=="none"),(0,F.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,F.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,F.filter)(F.isNonNullable),(0,F.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,F.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(yt(this.video,t.isLooped,i)),this.subscription.add(Oe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Xe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Ze(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,F.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of d.audio){h.push(nl(m));let g=[];for(let v of m.representations){let T=_v(v);g.push(T),this.audioTracksMap.set(T,{stream:m,representation:v})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(ol(h));let m=[];for(let g of h.representations){let v=Bv(N(A({},g),{streamId:h.id}));v&&(m.push(v),this.videoTracksMap.set(v,{stream:h,representation:g}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let m of h.representations){let g=Nv(h,m);this.textTracksMap.set(g,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:F.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,F.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,F.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,tS.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,m]=p,g=[...this.videoTracksMap.keys()].find(T=>{var I;return((I=this.videoTracksMap.get(T))==null?void 0:I.representation.id)===h.id});(0,F.isNonNullable)(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")this.player.initRepresentations(h.id,m==null?void 0:m.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),m){let T=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,T).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,F.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(ol(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,F.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(nl(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.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 u=t.playbackState.stateChangeStarted$.pipe((0,F.map)(({to:c})=>c==="ready"),(0,F.filterChanged)());this.subscription.add((0,F.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,F.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add((0,F.merge)(u,this.player.state$.stateChangeEnded$,(0,F.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,F.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,F.observableFrom)(["init"])).pipe((0,F.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var q,Y,le,U,ee,te,_,re,X,ne,L,P,G;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(q=e.videoTrack.getState())==null?void 0:q.id,n=[...this.videoTracksMap.keys()].find(({id:H})=>H===i),o=t.currentVideoTrack$.getValue(),u=((U=(le=e.videoStream.getState())!=null?le:n&&((Y=this.videoTracksMap.get(n))==null?void 0:Y.stream))!=null?U:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:H})=>H===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=It(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=(ee=e.audioStream.getState())!=null?ee:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(te=[...this.audioStreamsMap.keys()].find(({id:H})=>H===(m==null?void 0:m.id)))!=null?te:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let H=Ys(n,c,(_=this.audioStreamsMap.get(g))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(re=H==null?void 0:H.bitrate)!=null?re:-1/0)}if(o){let H=Ys(o,c,(X=this.audioStreamsMap.get(g))!=null?X:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(ne=H==null?void 0:H.bitrate)!=null?ne:-1/0)}}let T=rr(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:h,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}),I=r?T!=null?T:n:n!=null?n:T,x=g&&Eb(I,c,(L=this.audioStreamsMap.get(g))!=null?L:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),w=(P=this.videoTracksMap.get(I))==null?void 0:P.representation,k=x&&((G=this.audioTracksMap.get(x))==null?void 0:G.representation);if(w&&k)return[w,k];if(w&&!k&&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"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:F.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),Ce(this.video),this.tracer.end()}};var Ba=class extends kr{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 nr=require("@vkontakte/videoplayer-shared/es2015");var _a=class extends kr{constructor(e){super(e),this.liveOffset=new $t,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,nr.map)(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,nr.combine)({interval:(0,nr.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,nr.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,nr.map)(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Fv(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 rS=K(Hs(),1);var z=require("@vkontakte/videoplayer-shared/es2015");var ht={};var hi=(a,e)=>new z.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 z.Subscription;this.videoState=new Q("initializing");this.textTracksManager=new Je;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,z.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,z.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,z.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,z.assertNever)(e)}break;default:(0,z.assertNever)(t)}};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(ye(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:z.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,rS.default)(import("hls.js").then(i=>{e||(ht.Hls=i.default,ht.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,z.assertNonNullable)(ht.Hls,"hls.js not loaded"),this.hls=new ht.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,z.assertNonNullable)(ht.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:z.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(yt(this.video,e.isLooped,r)),this.subscription.add(Oe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Xe(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ze(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,z.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(hi(this.hls,ht.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:z.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"),R(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(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(hi(this.hls,ht.Events.MANIFEST_PARSED).pipe((0,z.map)(({levels:l})=>l.reduce((c,d)=>{var I,x;let p=d.name||d.height.toString(10),{width:h,height:m}=d,g=(x=er((I=d.attrs.QUALITY)!=null?I:""))!=null?x:(0,z.videoSizeToQuality)({width:h,height:m});if(!g)return c;let v=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:v};return this.trackLevels.set(p,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(hi(this.hls,ht.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||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(hi(this.hls,ht.Events.LEVEL_LOADING).pipe((0,z.map)(({url:l})=>ye(l))),t.hostname$),s(hi(this.hls,ht.Events.FRAG_CHANGED),l=>{var p,h,m,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((((m=d==null?void 0:d.endPTS)!=null?m:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(Zt(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=hi(this.hls,ht.Events.LEVEL_SWITCHED).pipe((0,z.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,z.filter)(z.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Zt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if((0,z.isNullable)(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.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,z.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,z.observableFrom)(["init"])).pipe((0,z.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)}playIfAllowed(){return $(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:z.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),R(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"),R(this.params.desiredState.playbackState,"stopped",!0)}};var iS="X-Playback-Duration",gl=a=>$(void 0,null,function*(){var i;let e=yield dt(a),t=yield 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(iS)?parseInt(e.headers.get(iS),10):void 0});var W=require("@vkontakte/videoplayer-shared/es2015");var Sl=K(No(),1);var In=require("@vkontakte/videoplayer-shared/es2015");var n$=a=>{let e=null;if(a.QUALITY&&(e=er(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},o$=(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,
|
|
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([N(A({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return $(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ke;let{textTracks:e}=yield this.fetchManifestData(),t=yield 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}})}fetchManifestData(){return $(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield 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 W.Subscription;this.videoState=new Q("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new W.ValueSubject([]);this.liveOffset=new $t;this.manifestStartTime$=new W.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"),R(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"?R(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),R(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"&&R(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"&&(R(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,W.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:W.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 Je,t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:W.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:W.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(ye(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new W.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:W.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(Oe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Xe(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ze(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"),R(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(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,W.filterChanged)(),(0,W.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,W.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(ye(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,W.combine)({startTime:this.manifestStartTime$.pipe((0,W.filter)(W.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,W.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,W.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,W.observableFrom)(["init"])).pipe((0,W.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,W.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 m=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ae(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,W.isNullable)(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();((0,W.isNullable)(p)||!isFinite(p))&&dt(n).then(h=>h.text()).then(h=>{var g;let m=(g=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:g[1];if(m){let v=new URL(m,n).toString();gl(v).then(T=>{(0,W.isNullable)(T)||this.maxSeekBackTime$.next(T)})}}).catch(()=>{})}})}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:W.ErrorCategory.DOM,thrown:e}))}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=Ae(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};var Z=require("@vkontakte/videoplayer-shared/es2015");var qa=class{constructor(e){this.subscription=new Z.Subscription;this.videoState=new Q("stopped");this.textTracksManager=new Je;this.manifests$=new Z.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"),R(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"?R(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),R(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"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,Z.assertNever)(t)}};this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Z.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(ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),En(Ae(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks: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:Z.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&&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:Z.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,Z.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(yt(this.video,t.isLooped,r)),this.subscription.add(Oe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Xe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(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,Z.isNonNullable)(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let g=this.manifests$.getValue().find(v=>v.id===m);g&&(this.params.output.currentVideoTrack$.next(g),this.params.output.hostname$.next(ye(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 m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,Z.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)),!Z.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,Z.merge)((0,Z.fromEvent)(o,"addtrack"),(0,Z.fromEvent)(o,"removetrack"),(0,Z.fromEvent)(o,"change"),(0,Z.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,Z.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,Z.observableFrom)(["init"])).pipe((0,Z.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,Z.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"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Z.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var sS=K(Wr(),1),Ua=K(ii(),1);var se=require("@vkontakte/videoplayer-shared/es2015");var Ha=class{constructor(e){this.subscription=new se.Subscription;this.videoState=new Q("stopped");this.trackUrls={};this.textTracksManager=new Je;this.syncPlayback=()=>{var u,l,c;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"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?R(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),R(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"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return(0,se.assertNever)(e)}};this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),(0,sS.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,Ua.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:se.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,se.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(yt(this.video,t.isLooped,r)),this.subscription.add(Oe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Xe(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ze(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(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,se.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,se.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,se.observableFrom)(["init"])).pipe((0,se.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,se.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,se.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ma(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ye(t))}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:se.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Ua.default)(this.trackUrls).find(d=>!(0,se.isInvariantQuality)(d.track.quality)&&(0,se.isLowerOrEqual)(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&(0,se.isHigherOrEqual)(c.quality,u.quality)&&(t=u),!t){let d=(0,Ua.default)(this.trackUrls).filter(h=>!(0,se.isInvariantQuality)(h.track.quality)&&(0,se.isHigher)(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Ua.default)(this.trackUrls).map(l=>l.track);t=rr(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};var ce=require("@vkontakte/videoplayer-shared/es2015");var oS=require("@vkontakte/videoplayer-shared/es2015");var nS=["stun:videostun.mycdn.me:80"],l$=1e3,c$=3,yl=()=>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=yl;this.externalStopCallback=yl;this.externalErrorCallback=yl;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}}handleUpdateMessage(e){return $(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return $(this,null,function*(){try{let e={iceServers:[{urls:nS}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return $(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return $(this,null,function*(){if(e)try{this.peerConnection&&(yield 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:oS.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return $(this,null,function*(){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()))}}createOffer(){return $(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield 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),l$)}normalizeOptions(e={}){let t={stunServerList:nS,maxRetryNumber:c$,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 Q("stopped");this.maxSeekBackTime$=new ce.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"),R(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"),R(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"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return(0,ce.assertNever)(e)}};this.subscription=new ce.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=De(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),Ce(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ce.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,ce.merge)(this.videoState.stateChangeStarted$.pipe((0,ce.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ce.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(Ze(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(Oe(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,ce.assertNever)(n.to)}},r)).add((0,ce.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ce.observableFrom)(["init"])).pipe((0,ce.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(ye(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:ce.VideoQuality.INVARIANT}),this.video.srcObject=e,R(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:ce.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ce.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ga=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/es2015");var Bt=require("@vkontakte/videoplayer-shared/es2015"),uS=a=>new Bt.Observable(e=>{let t=new Bt.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Bt.map)(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Bt.map)(({type:l})=>l!==void 0)),n=new Bt.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 rt=require("@vkontakte/videoplayer-shared/es2015");function lS(){return new(window.AudioContext||window.webkitAudioContext)}var cS=require("@vkontakte/videoplayer-shared/es2015");var Qa=class Qa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ke;this.subscriptions=new rt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,rt.filter)(s=>!!s.type),(0,rt.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){cS.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,rt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,rt.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,rt.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}initAudioContextOnce(e){return $(this,null,function*(){let{volumeMultiplier:t}=this,r=lS();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield 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:rt.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Qa.errorId} exception`,thrown:e})}};Qa.errorId="VolumeMultiplierManager";var fi=Qa;var d$={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([...bg(this.params.tuning),...mg(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,Tl.default)(i,l)),...t.filter(l=>(0,Tl.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new Ga(s);let n=[...Hu(!0),...Hu(!1)];this.chromecastFormatsIterator=new Ga(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&&fi.isSupported()&&(this.volumeMultiplierManager=new fi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){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 Ba(N(A({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new _a(N(A({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),ui||!this.params.tuning.useHlsJs?new qa(N(A({},n),{source:o})):new Na(N(A({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Fa(N(A({},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(A({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Mb(N(A({},n),{source:o,config:N(A({},d$),{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 Wi({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 N(A({},e),{url:r(e.url)})}return(0,pS.default)((0,dS.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))),uS({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(A({},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 B=require("@vkontakte/videoplayer-shared/es2015");var p$=5e3,hS="one_video_throughput",fS="one_video_rtt",_t=window.navigator.connection,mS=()=>{let a=_t==null?void 0:_t.downlink;if((0,B.isNonNullable)(a)&&a!==10)return a*1e3},bS=()=>{let a=_t==null?void 0:_t.rtt;if((0,B.isNonNullable)(a)&&a!==3e3)return a},gS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Il=class a{constructor(e){this.subscription=new B.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(hS)||(e.useBrowserEstimation?mS():void 0)||p$,r=(s=(i=a.load(fS))!=null?i:e.useBrowserEstimation?bS():void 0)!=null?s:0;if(this.throughput$=new B.ValueSubject(t),this.rtt$=new B.ValueSubject(r),this.rttAdjustedThroughput$=new B.ValueSubject(gS(t,r,e.rttPenaltyRequestSize)),this.throughput=Ar.getSmoothedValue(t,-1,e),this.rtt=Ar.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=mS();u&&this.throughput.next(u);let l=bS();(0,B.isNonNullable)(l)&&this.rtt.next(l)};_t&&"onchange"in _t&&this.subscription.add((0,B.fromEvent)(_t,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{B.safeStorage.set(hS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{B.safeStorage.set(fS,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,B.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,B.map)(({throughput:n,rtt:o})=>gS(n,o,e.rttPenaltyRequestSize)),(0,B.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,B.now)(),i=new B.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,B.fromEvent)(e,"progress").pipe((0,B.once)()).subscribe(s=>{t=s.loaded,r=(0,B.now)()}));break;case 1:case 0:i.add((0,B.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,B.now)()}));break}i.add((0,B.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,B.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,B.now)(),n=0,o=(0,B.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>$(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,(0,B.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=(0,B.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let g=o-s;g&&this.addRawSpeed(n,g,1,t),n=d.byteLength,s=(0,B.now)()}else n+=d.byteLength;o=(0,B.now)()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,B.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,B.now)()-o,this.concurrentDownloads.size),n=0,o=(0,B.now)());yield 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=B.safeStorage.get(e);if((0,B.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},vS=Il;var Ya=require("@vkontakte/videoplayer-shared/es2015");var SS={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:Ya.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ya.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:{stallDurationBeforeQualityDecrease:0,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,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},yS=a=>{var e;return N(A({},(0,Ya.fillWithDefault)(a,SS)),{configName:[...(e=a.configName)!=null?e:[],...SS.configName]})};var f=require("@vkontakte/videoplayer-shared/es2015");var Nt=require("@vkontakte/videoplayer-shared/es2015"),El=({seekState:a,position$:e})=>(0,Nt.merge)(a.stateChangeEnded$.pipe((0,Nt.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Nt.filter)(Nt.isNonNullable)),e.pipe((0,Nt.filter)(()=>a.getState().state==="none")));var TS=require("@vkontakte/videoplayer-shared/es2015"),IS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,TS.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var wn=require("@vkontakte/videoplayer-shared/es2015"),ES=(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 za=class{constructor(e={configName:[]},t=f.Tracer.createRootTracer(!1)){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new Q("stopped"),seekState:new Q({state:"none"}),volume:new Q({volume:1,muted:!1}),videoTrack:new Q(void 0),videoStream:new Q(void 0),audioStream:new Q(void 0),autoVideoTrackSwitching:new Q(!0),autoVideoTrackLimits:new Q({}),isLooped:new Q(!1),isLowLatency:new Q(!1),playbackRate:new Q(1),externalTextTracks:new Q([]),internalTextTracks:new Q([]),currentTextTrack:new Q(void 0),textTrackCuesSettings:new Q({}),cameraOrientation:new Q({x:0,y:0})};this.info={playbackState$:new f.ValueSubject("stopped"),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),liveLatency$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:gb,getCurrentTime$:new f.ValueSubject(null)};if(this.initLogs(),this.tuning=yS(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 vS(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new f.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,m)=>{let g=typeof m;return(0,xS.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:f.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=sc(i,["container"]);return this.tracer.log("initVideo",(0,f.flattenObject)(r)),this.domContainer=IS(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new Wa({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],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(),(u=this.internalsExposure)==null||u.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&&!Zi()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.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-.1),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,f.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,f.filter)(r=>r.length>0),(0,f.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,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;(0,f.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,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>A({type:"external"},t))),this}selectTextTrack(e){var t;return ES(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",A({},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,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,f.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,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.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,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState(N(A({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,f.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,f.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,f.isInvariantQuality)(u)?1:(0,f.isInvariantQuality)(l)?-1:(0,f.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,f.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,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.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,f.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,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.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,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:El({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(El({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.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,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.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,f.once)(),(0,f.map)(n=>n!=null?n:(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.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 f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>r.next(!1)));let i=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,f.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,f.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,f.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,f.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 f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.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=rr(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,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.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,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),bb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>mb(r)),this.providerContainer.current$.subscribe(({type:r})=>Yi("provider",r)),e.duration$.subscribe(r=>Yi("duration",r)),e.availableVideoTracks$.pipe((0,f.filter)(r=>!!r.length),(0,f.once)()).subscribe(r=>Yi("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,f.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)),Yi("codecs",hg())}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.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,f.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,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),(0,f.filterChanged)((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(r=>r>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(r=>r>0),(0,f.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,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(r=>r.end>0),(0,f.filterChanged)((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:r,rtt:i})=>!!r&&!!i),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.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=()=>$(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(i)})})});this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.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,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.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 xt=require("@vkontakte/videoplayer-shared/es2015"),h$=`@vkontakte/videoplayer-core@${Cn}`;
|
|
124
|
+
`;var Pn=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 En(this.params.fov,this.params.orientation),this.cameraRotationManager=new xn(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 Se=require("@vkontakte/videoplayer-shared/es2015"),yl=class{constructor(){this.isSeeked$=new Se.ValueSubject(!1);this.isBuffering$=new Se.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Se.Subscription;this.severeStallOccurred$=new Se.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,Se.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,Se.filter)(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,Se.combine)({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if((0,Se.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=(0,Se.now)(),d=i&&this.currentStallsCount>=i,p=r&&c-this.lastUniqueVideoTrackSelectedTimestamp>=r+o&&c-l>=r+o&&t>=r;(d||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Se.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&u>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,Se.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},sS=yl;var Ue=require("@vkontakte/videoplayer-shared/es2015"),wn=class{constructor(){this.subscription=new Ue.Subscription;this.pipSize$=new Ue.ValueSubject(void 0);this.videoSize$=new Ue.ValueSubject(void 0);this.elementSize$=new Ue.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Ue.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,Ue.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,Ue.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Ue.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 Rr=class{constructor(e){this.subscription=new F.Subscription;this.videoState=new W("stopped");this.droppedFramesManager=new tn;this.stallsManager=new sS;this.elementSizeManager=new wn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new zi;this.audioTrackSwitchHistory=new zi;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"),R(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"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&R(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"&&R(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"&&R(this.params.desiredState.playbackState,"paused");return;default:return(0,F.assertNever)(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Pn(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 Je(e.source.url),this.params=e,this.video=Be(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(Te(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 In({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=_e(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:F.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,F.filter)(c=>!!c.length),(0,F.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,F.map)(c=>c.to.state!=="none"),(0,F.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,F.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,F.filter)(F.isNonNullable),(0,F.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,F.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(yt(this.video,t.isLooped,i)),this.subscription.add(Oe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Xe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Ze(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,F.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of d.audio){h.push(cl(m));let g=[];for(let v of m.representations){let I=Hv(v);g.push(I),this.audioTracksMap.set(I,{stream:m,representation:v})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(dl(h));let m=[];for(let g of h.representations){let v=Uv(N(A({},g),{streamId:h.id}));v&&(m.push(v),this.videoTracksMap.set(v,{stream:h,representation:g}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let m of h.representations){let g=jv(h,m);this.textTracksMap.set(g,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:F.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,F.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,F.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,nS.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,m]=p,g=[...this.videoTracksMap.keys()].find(I=>{var E;return((E=this.videoTracksMap.get(I))==null?void 0:E.representation.id)===h.id});(0,F.isNonNullable)(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")this.player.initRepresentations(h.id,m==null?void 0:m.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),m){let I=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,I).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,F.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(dl(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,F.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(cl(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.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 u=t.playbackState.stateChangeStarted$.pipe((0,F.map)(({to:c})=>c==="ready"),(0,F.filterChanged)());this.subscription.add((0,F.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,F.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add((0,F.merge)(u,this.player.state$.stateChangeEnded$,(0,F.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,F.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,F.observableFrom)(["init"])).pipe((0,F.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var z,de,H,ne,J,V,ie,Z,oe,M,U,P,Q;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(z=e.videoTrack.getState())==null?void 0:z.id,n=[...this.videoTracksMap.keys()].find(({id:j})=>j===i),o=t.currentVideoTrack$.getValue(),u=((ne=(H=e.videoStream.getState())!=null?H:n&&((de=this.videoTracksMap.get(n))==null?void 0:de.stream))!=null?ne:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:j})=>j===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=It(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(p,h||1/0),1),g=(J=e.audioStream.getState())!=null?J:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(V=[...this.audioStreamsMap.keys()].find(({id:j})=>j===(g==null?void 0:g.id)))!=null?V:this.audioStreamsMap.keys().next().value,I=0;if(v){if(n&&!r){let j=Zs(n,c,(ie=this.audioStreamsMap.get(v))!=null?ie:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(Z=j==null?void 0:j.bitrate)!=null?Z:-1/0)}if(o){let j=Zs(o,c,(oe=this.audioStreamsMap.get(v))!=null?oe:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(M=j==null?void 0:j.bitrate)!=null?M:-1/0)}}let E=rr(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:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),x=r?E!=null?E:n:n!=null?n:E,w=v&&kb(x,c,(U=this.audioStreamsMap.get(v))!=null?U:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),k=(P=this.videoTracksMap.get(x))==null?void 0:P.representation,q=w&&((Q=this.audioTracksMap.get(w))==null?void 0:Q.representation);if(k&&q)return[k,q];if(k&&!q&&this.audioTracksMap.size===0)return[k,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:F.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),Ve(this.video),this.tracer.end()}};var Fa=class extends Rr{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 nr=require("@vkontakte/videoplayer-shared/es2015");var qa=class extends Rr{constructor(e){super(e),this.liveOffset=new Lt,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,nr.map)(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,nr.combine)({interval:(0,nr.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,nr.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,nr.map)(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Gv(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 oS=X(Ys(),1);var K=require("@vkontakte/videoplayer-shared/es2015");var ht={};var hi=(a,e)=>new K.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ua=class{constructor(e){this.subscription=new K.Subscription;this.videoState=new W("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,K.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,K.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,K.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,K.assertNever)(e)}break;default:(0,K.assertNever)(t)}};this.textTracksManager=new Je(e.source.url),this.video=Be(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(Te(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),Ve(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:K.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||(ht.Hls=i.default,ht.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,K.assertNonNullable)(ht.Hls,"hls.js not loaded"),this.hls=new ht.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,K.assertNonNullable)(ht.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:K.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=_e(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(yt(this.video,e.isLooped,r)),this.subscription.add(Oe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Xe(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ze(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,K.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(hi(this.hls,ht.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:K.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"),R(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(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(hi(this.hls,ht.Events.MANIFEST_PARSED).pipe((0,K.map)(({levels:l})=>l.reduce((c,d)=>{var E,x;let p=d.name||d.height.toString(10),{width:h,height:m}=d,g=(x=er((E=d.attrs.QUALITY)!=null?E:""))!=null?x:(0,K.videoSizeToQuality)({width:h,height:m});if(!g)return c;let v=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:m},fps:v};return this.trackLevels.set(p,{track:I,level:d}),c.push(I),c},[]))),t.availableVideoTracks$),s(hi(this.hls,ht.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||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(hi(this.hls,ht.Events.LEVEL_LOADING).pipe((0,K.map)(({url:l})=>Te(l))),t.hostname$),s(hi(this.hls,ht.Events.FRAG_CHANGED),l=>{var p,h,m,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((((m=d==null?void 0:d.endPTS)!=null?m:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(Zt(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=hi(this.hls,ht.Events.LEVEL_SWITCHED).pipe((0,K.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,K.filter)(K.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Zt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if((0,K.isNullable)(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.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,K.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,K.observableFrom)(["init"])).pipe((0,K.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)}playIfAllowed(){return $(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:K.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),R(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"),R(this.params.desiredState.playbackState,"stopped",!0)}};var uS="X-Playback-Duration",Tl=a=>$(void 0,null,function*(){var i;let e=yield dt(a),t=yield 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 Y=require("@vkontakte/videoplayer-shared/es2015");var El=X(Ho(),1);var An=require("@vkontakte/videoplayer-shared/es2015");var c$=a=>{let e=null;if(a.QUALITY&&(e=er(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=(0,An.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},d$=(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,El.default)(l[1].split(",").map(E=>E.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=c$(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,v;if(d.RESOLUTION){let[E,x]=d.RESOLUTION.split("x").map(w=>parseInt(w,10));E&&x&&(v={width:E,height:x})}let I=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:I,bandwidth:m,size:v,fps:g})}if(c){let d=(0,El.default)(c[1].split(",").map(g=>{let v=g.indexOf("=");return[g.substring(0,v),g.substring(v+1)]}).map(([g,v])=>[g,v.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&i.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},p$=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Il=0,lS=(i,...s)=>$(void 0,[i,...s],function*(a,e=a,t,r){let o=yield(yield dt(a,r)).text();Il+=1;try{let{qualityManifests:u,textTracks:l}=d$(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(Il<=t.manifestRetryMaxCount)return yield p$((0,An.getExponentialDelay)(Il-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),lS(a,e,t)}return{qualityManifests:[],textTracks:[]}}),kn=lS;var Ye=require("@vkontakte/videoplayer-shared/es2015");var Rn=class{constructor(e,t,r,i,s){this.subscription=new Ye.Subscription;this.abortControllers={destroy:new Ae,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Ye.ValueSubject(null);this.getCurrentTime$=new Ye.ValueSubject(null);this.error$=new Ye.Subject;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe((0,Ye.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()}prepare(e){return $(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=yield this.fetchManifestData();yield this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return $(this,null,function*(){try{let r=yield this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}})}parseTextTracks(e,t){return $(this,null,function*(){for(let r of e){let i=new URL(r.url,t).toString(),n=yield(yield dt(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,Ye.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([N(A({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return $(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new Ae;let{textTracks:e}=yield this.fetchManifestData(),t=yield 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}})}fetchManifestData(){return $(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:Ye.ErrorCategory.WTF,thrown:t,message:e})}};var Ha=class{constructor(e){this.subscription=new Y.Subscription;this.videoState=new W("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Y.ValueSubject([]);this.liveOffset=new Lt;this.manifestStartTime$=new Y.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"),R(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"?R(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),R(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"&&R(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"&&(R(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,Y.assertNever)(t)}};var r;this.params=e,this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Y.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,s)=>kn(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 Rn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Je(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:Y.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:Y.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(Te(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Y.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:Y.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=_e(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(Oe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Xe(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ze(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"),R(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(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,Y.filterChanged)(),(0,Y.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,Y.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(Te(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,Y.combine)({startTime:this.manifestStartTime$.pipe((0,Y.filter)(Y.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,Y.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,Y.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,Y.observableFrom)(["init"])).pipe((0,Y.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),Ve(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if((0,Y.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 m=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=we(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Tl(n).then(c=>{var d;if(!(0,Y.isNullable)(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();((0,Y.isNullable)(p)||!isFinite(p))&&dt(n).then(h=>h.text()).then(h=>{var g;let m=(g=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:g[1];if(m){let v=new URL(m,n).toString();Tl(v).then(I=>{(0,Y.isNullable)(I)||this.maxSeekBackTime$.next(I)})}}).catch(()=>{})}})}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Y.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=we(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 re=require("@vkontakte/videoplayer-shared/es2015");var ja=class{constructor(e){this.subscription=new re.Subscription;this.videoState=new W("stopped");this.manifests$=new re.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"),R(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"?R(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),R(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"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,re.assertNever)(t)}};this.textTracksManager=new Je(e.source.url),this.params=e,this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:re.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(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),kn(we(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:re.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&&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:re.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},i=_e(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,re.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(yt(this.video,t.isLooped,r)),this.subscription.add(Oe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Xe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(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,re.isNonNullable)(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let g=this.manifests$.getValue().find(v=>v.id===m);g&&(this.params.output.currentVideoTrack$.next(g),this.params.output.hostname$.next(Te(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 m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,re.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)),!re.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,re.merge)((0,re.fromEvent)(o,"addtrack"),(0,re.fromEvent)(o,"removetrack"),(0,re.fromEvent)(o,"change"),(0,re.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,re.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ve(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,re.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(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var cS=X(Wr(),1),Ga=X(ii(),1);var se=require("@vkontakte/videoplayer-shared/es2015");var Qa=class{constructor(e){this.subscription=new se.Subscription;this.videoState=new W("stopped");this.trackUrls={};this.textTracksManager=new Je;this.syncPlayback=()=>{var u,l,c;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"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?R(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),R(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"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return(0,se.assertNever)(e)}};this.params=e,this.video=Be(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,Ga.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:se.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=_e(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,se.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(yt(this.video,t.isLooped,r)),this.subscription.add(Oe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Xe(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ze(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(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,se.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,se.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,se.observableFrom)(["init"])).pipe((0,se.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),Ve(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,se.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,se.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ba(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Te(t))}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:se.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Ga.default)(this.trackUrls).find(d=>!(0,se.isInvariantQuality)(d.track.quality)&&(0,se.isLowerOrEqual)(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&(0,se.isHigherOrEqual)(c.quality,u.quality)&&(t=u),!t){let d=(0,Ga.default)(this.trackUrls).filter(h=>!(0,se.isInvariantQuality)(h.track.quality)&&(0,se.isHigher)(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Ga.default)(this.trackUrls).map(l=>l.track);t=rr(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};var pe=require("@vkontakte/videoplayer-shared/es2015");var pS=require("@vkontakte/videoplayer-shared/es2015");var dS=["stun:videostun.mycdn.me:80"],h$=1e3,f$=3,xl=()=>null,$n=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=xl;this.externalStopCallback=xl;this.externalErrorCallback=xl;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}}handleUpdateMessage(e){return $(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return $(this,null,function*(){try{let e={iceServers:[{urls:dS}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return $(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return $(this,null,function*(){if(e)try{this.peerConnection&&(yield 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:pS.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return $(this,null,function*(){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()))}}createOffer(){return $(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield 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),h$)}normalizeOptions(e={}){let t={stunServerList:dS,maxRetryNumber:f$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Wa=class{constructor(e){this.videoState=new W("stopped");this.maxSeekBackTime$=new pe.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"),R(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"),R(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"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return(0,pe.assertNever)(e)}};this.subscription=new pe.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Be(e.container,e.tuning),this.liveStreamClient=new $n(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),Ve(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:pe.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,pe.merge)(this.videoState.stateChangeStarted$.pipe((0,pe.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,pe.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=_e(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(Ze(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(Oe(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,pe.assertNever)(n.to)}},r)).add((0,pe.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,pe.observableFrom)(["init"])).pipe((0,pe.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(Te(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:pe.VideoQuality.INVARIANT}),this.video.srcObject=e,R(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:pe.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pe.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ya=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/es2015");var _t=require("@vkontakte/videoplayer-shared/es2015"),hS=a=>new _t.Observable(e=>{let t=new _t.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,_t.map)(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,_t.map)(({type:l})=>l!==void 0)),n=new _t.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 rt=require("@vkontakte/videoplayer-shared/es2015");function fS(){return new(window.AudioContext||window.webkitAudioContext)}var mS=require("@vkontakte/videoplayer-shared/es2015");var za=class za{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new Ae;this.subscriptions=new rt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,rt.filter)(s=>!!s.type),(0,rt.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){mS.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,rt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,rt.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,rt.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}initAudioContextOnce(e){return $(this,null,function*(){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"&&(yield 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:za.errorId,category:rt.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${za.errorId} exception`,thrown:e})}};za.errorId="VolumeMultiplierManager";var fi=za;var m$={chunkDuration:5e3,maxParallelRequests:5},Ka=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=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,Pl.default)(i,l)),...t.filter(l=>(0,Pl.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new Ya(s);let n=[...Wu(!0),...Wu(!1)];this.chromecastFormatsIterator=new Ya(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&&fi.isSupported()&&(this.volumeMultiplierManager=new fi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){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 Fa(N(A({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new qa(N(A({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),ui||!this.params.tuning.useHlsJs?new ja(N(A({},n),{source:o})):new Ua(N(A({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ha(N(A({},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 Qa(N(A({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ob(N(A({},n),{source:o,config:N(A({},m$),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Wa({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 Wi({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 N(A({},e),{url:r(e.url)})}return(0,gS.default)((0,bS.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))),hS({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(A({},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 _=require("@vkontakte/videoplayer-shared/es2015");var b$=5e3,vS="one_video_throughput",SS="one_video_rtt",Nt=window.navigator.connection,yS=()=>{let a=Nt==null?void 0:Nt.downlink;if((0,_.isNonNullable)(a)&&a!==10)return a*1e3},TS=()=>{let a=Nt==null?void 0:Nt.rtt;if((0,_.isNonNullable)(a)&&a!==3e3)return a},IS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},wl=class a{constructor(e){this.subscription=new _.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(vS)||(e.useBrowserEstimation?yS():void 0)||b$,r=(s=(i=a.load(SS))!=null?i:e.useBrowserEstimation?TS():void 0)!=null?s:0;if(this.throughput$=new _.ValueSubject(t),this.rtt$=new _.ValueSubject(r),this.rttAdjustedThroughput$=new _.ValueSubject(IS(t,r,e.rttPenaltyRequestSize)),this.throughput=kr.getSmoothedValue(t,-1,e),this.rtt=kr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=yS();u&&this.throughput.next(u);let l=TS();(0,_.isNonNullable)(l)&&this.rtt.next(l)};Nt&&"onchange"in Nt&&this.subscription.add((0,_.fromEvent)(Nt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{_.safeStorage.set(vS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{_.safeStorage.set(SS,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,_.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,_.map)(({throughput:n,rtt:o})=>IS(n,o,e.rttPenaltyRequestSize)),(0,_.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,_.now)(),i=new _.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,_.fromEvent)(e,"progress").pipe((0,_.once)()).subscribe(s=>{t=s.loaded,r=(0,_.now)()}));break;case 1:case 0:i.add((0,_.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,_.now)()}));break}i.add((0,_.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,_.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,_.now)(),n=0,o=(0,_.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>$(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,(0,_.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=(0,_.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let g=o-s;g&&this.addRawSpeed(n,g,1,t),n=d.byteLength,s=(0,_.now)()}else n+=d.byteLength;o=(0,_.now)()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,_.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,_.now)()-o,this.concurrentDownloads.size),n=0,o=(0,_.now)());yield 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=_.safeStorage.get(e);if((0,_.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},ES=wl;var Xa=require("@vkontakte/videoplayer-shared/es2015");var xS={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:Xa.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Xa.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,ignoreStallsOnSeek:!1},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},PS=a=>{var e;return N(A({},(0,Xa.fillWithDefault)(a,xS)),{configName:[...(e=a.configName)!=null?e:[],...xS.configName]})};var f=require("@vkontakte/videoplayer-shared/es2015");var Ft=require("@vkontakte/videoplayer-shared/es2015"),Al=({seekState:a,position$:e})=>(0,Ft.merge)(a.stateChangeEnded$.pipe((0,Ft.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Ft.filter)(Ft.isNonNullable)),e.pipe((0,Ft.filter)(()=>a.getState().state==="none")));var wS=require("@vkontakte/videoplayer-shared/es2015"),AS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,wS.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var Ln=require("@vkontakte/videoplayer-shared/es2015"),kS=(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,Ln.filter)(i=>i.length>0),(0,Ln.once)()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Ja=class{constructor(e={configName:[]},t=f.Tracer.createRootTracer(!1)){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new W("stopped"),seekState:new W({state:"none"}),volume:new W({volume:1,muted:!1}),videoTrack:new W(void 0),videoStream:new W(void 0),audioStream:new W(void 0),autoVideoTrackSwitching:new W(!0),autoVideoTrackLimits:new W({}),isLooped:new W(!1),isLowLatency:new W(!1),playbackRate:new W(1),externalTextTracks:new W([]),internalTextTracks:new W([]),currentTextTrack:new W(void 0),textTrackCuesSettings:new W({}),cameraOrientation:new W({x:0,y:0})};this.info={playbackState$:new f.ValueSubject("stopped"),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),liveLatency$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:Ib,getCurrentTime$:new f.ValueSubject(null)};if(this.initLogs(),this.tuning=PS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ys({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ES(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new f.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,m)=>{let g=typeof m;return(0,RS.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:f.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=cc(i,["container"]);return this.tracer.log("initVideo",(0,f.flattenObject)(r)),this.domContainer=AS(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new Ka({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],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(),(u=this.internalsExposure)==null||u.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&&!Zi()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.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,f.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,f.filter)(r=>r.length>0),(0,f.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,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;(0,f.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,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>A({type:"external"},t))),this}selectTextTrack(e){var t;return kS(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",A({},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,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,f.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,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.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,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState(N(A({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,f.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,f.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,f.isInvariantQuality)(u)?1:(0,f.isInvariantQuality)(l)?-1:(0,f.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,f.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,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.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,f.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,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.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,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Al({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(Al({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.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,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.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,f.once)(),(0,f.map)(n=>n!=null?n:(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.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 f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>r.next(!1)));let i=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,f.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,f.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,f.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,f.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 f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.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=rr(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,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.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,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),Tb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>yb(r)),this.providerContainer.current$.subscribe(({type:r})=>Yi("provider",r)),e.duration$.subscribe(r=>Yi("duration",r)),e.availableVideoTracks$.pipe((0,f.filter)(r=>!!r.length),(0,f.once)()).subscribe(r=>Yi("tracks",r)),this.events.fatalError$.subscribe(new Me("fatalError")),this.events.managedError$.subscribe(new Me("managedError")),e.position$.subscribe(new Me("position")),e.currentVideoTrack$.pipe((0,f.map)(r=>r==null?void 0:r.quality)).subscribe(new Me("quality")),this.info.currentBuffer$.subscribe(new Me("buffer")),e.isBuffering$.subscribe(new Me("isBuffering"))].forEach(r=>this.subscription.add(r)),Yi("codecs",vg())}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.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,f.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,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),(0,f.filterChanged)((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(r=>r>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(r=>r>0),(0,f.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,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(r=>r.end>0),(0,f.filterChanged)((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:r,rtt:i})=>!!r&&!!i),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.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=()=>$(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(i)})})});this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.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,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.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 xt=require("@vkontakte/videoplayer-shared/es2015"),g$=`@vkontakte/videoplayer-core@${_n}`;
|