@vkontakte/videoplayer-core 2.0.108-dev.ce9f9a29.0 → 2.0.108-dev.f2d9491a.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2018.esm.js CHANGED
@@ -1,10 +1,13 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.108-dev.ce9f9a29.0
3
- * Tue, 03 Sep 2024 12:57:06 GMT
2
+ * @vkontakte/videoplayer-core v2.0.108-dev.f2d9491a.0
3
+ * Wed, 04 Sep 2024 19:25:55 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-108/doc/
5
5
  */
6
- var qS=Object.create;var kl=Object.defineProperty;var US=Object.getOwnPropertyDescriptor;var HS=Object.getOwnPropertyNames;var jS=Object.getPrototypeOf,GS=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var WS=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of HS(e))!GS.call(a,i)&&i!==t&&kl(a,i,{get:()=>e[i],enumerable:!(r=US(e,i))||r.enumerable});return a};var Fe=(a,e,t)=>(t=a!=null?qS(jS(a)):{},WS(e||!a||!a.__esModule?kl(t,"default",{value:a,enumerable:!0}):t,a));var be=m((jL,Bl)=>{"use strict";Bl.exports=function(a){try{return!!a()}catch(e){return!0}}});var Or=m((GL,Vl)=>{"use strict";var ev=be();Vl.exports=!ev(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var oe=m((WL,Fl)=>{"use strict";var _l=Or(),Nl=Function.prototype,ln=Nl.call,tv=_l&&Nl.bind.bind(ln,ln);Fl.exports=_l?tv:function(a){return function(){return ln.apply(a,arguments)}}});var Jt=m((YL,Ul)=>{"use strict";var ql=oe(),rv=ql({}.toString),iv=ql("".slice);Ul.exports=function(a){return iv(rv(a),8,-1)}});var jl=m((QL,Hl)=>{"use strict";var av=oe(),sv=be(),nv=Jt(),cn=Object,ov=av("".split);Hl.exports=sv(function(){return!cn("z").propertyIsEnumerable(0)})?function(a){return nv(a)==="String"?ov(a,""):cn(a)}:cn});var Xt=m((zL,Gl)=>{"use strict";Gl.exports=function(a){return a==null}});var Br=m((KL,Wl)=>{"use strict";var uv=Xt(),lv=TypeError;Wl.exports=function(a){if(uv(a))throw new lv("Can't call method on "+a);return a}});var Zt=m((JL,Yl)=>{"use strict";var cv=jl(),dv=Br();Yl.exports=function(a){return cv(dv(a))}});var dn=m((XL,Ql)=>{"use strict";Ql.exports=function(){}});var Pt=m((ZL,zl)=>{"use strict";zl.exports={}});var W=m((pn,Kl)=>{"use strict";var Vr=function(a){return a&&a.Math===Math&&a};Kl.exports=Vr(typeof globalThis=="object"&&globalThis)||Vr(typeof window=="object"&&window)||Vr(typeof self=="object"&&self)||Vr(typeof global=="object"&&global)||Vr(typeof pn=="object"&&pn)||function(){return this}()||Function("return this")()});var G=m((e$,Jl)=>{"use strict";var hn=typeof document=="object"&&document.all;Jl.exports=typeof hn=="undefined"&&hn!==void 0?function(a){return typeof a=="function"||a===hn}:function(a){return typeof a=="function"}});var ec=m((t$,Zl)=>{"use strict";var pv=W(),hv=G(),Xl=pv.WeakMap;Zl.exports=hv(Xl)&&/native code/.test(String(Xl))});var Ie=m((r$,tc)=>{"use strict";var fv=G();tc.exports=function(a){return typeof a=="object"?a!==null:fv(a)}});var Ee=m((i$,rc)=>{"use strict";var mv=be();rc.exports=!mv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ba=m((a$,ac)=>{"use strict";var bv=W(),ic=Ie(),fn=bv.document,gv=ic(fn)&&ic(fn.createElement);ac.exports=function(a){return gv?fn.createElement(a):{}}});var mn=m((s$,sc)=>{"use strict";var Sv=Ee(),vv=be(),yv=ba();sc.exports=!Sv&&!vv(function(){return Object.defineProperty(yv("div"),"a",{get:function(){return 7}}).a!==7})});var bn=m((n$,nc)=>{"use strict";var Tv=Ee(),Iv=be();nc.exports=Tv&&Iv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var qe=m((o$,oc)=>{"use strict";var Ev=Ie(),xv=String,Pv=TypeError;oc.exports=function(a){if(Ev(a))return a;throw new Pv(xv(a)+" is not an object")}});var ge=m((u$,uc)=>{"use strict";var Av=Or(),ga=Function.prototype.call;uc.exports=Av?ga.bind(ga):function(){return ga.apply(ga,arguments)}});var Sa=m((l$,lc)=>{"use strict";lc.exports={}});var Ge=m((c$,dc)=>{"use strict";var gn=Sa(),Sn=W(),wv=G(),cc=function(a){return wv(a)?a:void 0};dc.exports=function(a,e){return arguments.length<2?cc(gn[a])||cc(Sn[a]):gn[a]&&gn[a][e]||Sn[a]&&Sn[a][e]}});var _r=m((d$,pc)=>{"use strict";var kv=oe();pc.exports=kv({}.isPrototypeOf)});var er=m((p$,mc)=>{"use strict";var Rv=W(),hc=Rv.navigator,fc=hc&&hc.userAgent;mc.exports=fc?String(fc):""});var yn=m((h$,Tc)=>{"use strict";var yc=W(),vn=er(),bc=yc.process,gc=yc.Deno,Sc=bc&&bc.versions||gc&&gc.version,vc=Sc&&Sc.v8,Ce,va;vc&&(Ce=vc.split("."),va=Ce[0]>0&&Ce[0]<4?1:+(Ce[0]+Ce[1]));!va&&vn&&(Ce=vn.match(/Edge\/(\d+)/),(!Ce||Ce[1]>=74)&&(Ce=vn.match(/Chrome\/(\d+)/),Ce&&(va=+Ce[1])));Tc.exports=va});var Tn=m((f$,Ec)=>{"use strict";var Ic=yn(),Lv=be(),$v=W(),Mv=$v.String;Ec.exports=!!Object.getOwnPropertySymbols&&!Lv(function(){var a=Symbol("symbol detection");return!Mv(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Ic&&Ic<41})});var In=m((m$,xc)=>{"use strict";var Cv=Tn();xc.exports=Cv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var En=m((b$,Pc)=>{"use strict";var Dv=Ge(),Ov=G(),Bv=_r(),Vv=In(),_v=Object;Pc.exports=Vv?function(a){return typeof a=="symbol"}:function(a){var e=Dv("Symbol");return Ov(e)&&Bv(e.prototype,_v(a))}});var Nr=m((g$,Ac)=>{"use strict";var Nv=String;Ac.exports=function(a){try{return Nv(a)}catch(e){return"Object"}}});var We=m((S$,wc)=>{"use strict";var Fv=G(),qv=Nr(),Uv=TypeError;wc.exports=function(a){if(Fv(a))return a;throw new Uv(qv(a)+" is not a function")}});var Fr=m((v$,kc)=>{"use strict";var Hv=We(),jv=Xt();kc.exports=function(a,e){var t=a[e];return jv(t)?void 0:Hv(t)}});var Lc=m((y$,Rc)=>{"use strict";var xn=ge(),Pn=G(),An=Ie(),Gv=TypeError;Rc.exports=function(a,e){var t,r;if(e==="string"&&Pn(t=a.toString)&&!An(r=xn(t,a))||Pn(t=a.valueOf)&&!An(r=xn(t,a))||e!=="string"&&Pn(t=a.toString)&&!An(r=xn(t,a)))return r;throw new Gv("Can't convert object to primitive value")}});var De=m((T$,$c)=>{"use strict";$c.exports=!0});var Dc=m((I$,Cc)=>{"use strict";var Mc=W(),Wv=Object.defineProperty;Cc.exports=function(a,e){try{Wv(Mc,a,{value:e,configurable:!0,writable:!0})}catch(t){Mc[a]=e}return e}});var qr=m((E$,Vc)=>{"use strict";var Yv=De(),Qv=W(),zv=Dc(),Oc="__core-js_shared__",Bc=Vc.exports=Qv[Oc]||zv(Oc,{});(Bc.versions||(Bc.versions=[])).push({version:"3.38.0",mode:Yv?"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 wn=m((x$,Nc)=>{"use strict";var _c=qr();Nc.exports=function(a,e){return _c[a]||(_c[a]=e||{})}});var Ur=m((P$,Fc)=>{"use strict";var Kv=Br(),Jv=Object;Fc.exports=function(a){return Jv(Kv(a))}});var Oe=m((A$,qc)=>{"use strict";var Xv=oe(),Zv=Ur(),ey=Xv({}.hasOwnProperty);qc.exports=Object.hasOwn||function(e,t){return ey(Zv(e),t)}});var kn=m((w$,Uc)=>{"use strict";var ty=oe(),ry=0,iy=Math.random(),ay=ty(1 .toString);Uc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+ay(++ry+iy,36)}});var te=m((k$,jc)=>{"use strict";var sy=W(),ny=wn(),Hc=Oe(),oy=kn(),uy=Tn(),ly=In(),tr=sy.Symbol,Rn=ny("wks"),cy=ly?tr.for||tr:tr&&tr.withoutSetter||oy;jc.exports=function(a){return Hc(Rn,a)||(Rn[a]=uy&&Hc(tr,a)?tr[a]:cy("Symbol."+a)),Rn[a]}});var Qc=m((R$,Yc)=>{"use strict";var dy=ge(),Gc=Ie(),Wc=En(),py=Fr(),hy=Lc(),fy=te(),my=TypeError,by=fy("toPrimitive");Yc.exports=function(a,e){if(!Gc(a)||Wc(a))return a;var t=py(a,by),r;if(t){if(e===void 0&&(e="default"),r=dy(t,a,e),!Gc(r)||Wc(r))return r;throw new my("Can't convert object to primitive value")}return e===void 0&&(e="number"),hy(a,e)}});var Ln=m((L$,zc)=>{"use strict";var gy=Qc(),Sy=En();zc.exports=function(a){var e=gy(a,"string");return Sy(e)?e:e+""}});var At=m(Jc=>{"use strict";var vy=Ee(),yy=mn(),Ty=bn(),ya=qe(),Kc=Ln(),Iy=TypeError,$n=Object.defineProperty,Ey=Object.getOwnPropertyDescriptor,Mn="enumerable",Cn="configurable",Dn="writable";Jc.f=vy?Ty?function(e,t,r){if(ya(e),t=Kc(t),ya(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Dn in r&&!r[Dn]){var i=Ey(e,t);i&&i[Dn]&&(e[t]=r.value,r={configurable:Cn in r?r[Cn]:i[Cn],enumerable:Mn in r?r[Mn]:i[Mn],writable:!1})}return $n(e,t,r)}:$n:function(e,t,r){if(ya(e),t=Kc(t),ya(r),yy)try{return $n(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Iy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Hr=m((M$,Xc)=>{"use strict";Xc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var rr=m((C$,Zc)=>{"use strict";var xy=Ee(),Py=At(),Ay=Hr();Zc.exports=xy?function(a,e,t){return Py.f(a,e,Ay(1,t))}:function(a,e,t){return a[e]=t,a}});var Ta=m((D$,td)=>{"use strict";var wy=wn(),ky=kn(),ed=wy("keys");td.exports=function(a){return ed[a]||(ed[a]=ky(a))}});var Ia=m((O$,rd)=>{"use strict";rd.exports={}});var _n=m((B$,sd)=>{"use strict";var Ry=ec(),ad=W(),Ly=Ie(),$y=rr(),On=Oe(),Bn=qr(),My=Ta(),Cy=Ia(),id="Object already initialized",Vn=ad.TypeError,Dy=ad.WeakMap,Ea,jr,xa,Oy=function(a){return xa(a)?jr(a):Ea(a,{})},By=function(a){return function(e){var t;if(!Ly(e)||(t=jr(e)).type!==a)throw new Vn("Incompatible receiver, "+a+" required");return t}};Ry||Bn.state?(Be=Bn.state||(Bn.state=new Dy),Be.get=Be.get,Be.has=Be.has,Be.set=Be.set,Ea=function(a,e){if(Be.has(a))throw new Vn(id);return e.facade=a,Be.set(a,e),e},jr=function(a){return Be.get(a)||{}},xa=function(a){return Be.has(a)}):(wt=My("state"),Cy[wt]=!0,Ea=function(a,e){if(On(a,wt))throw new Vn(id);return e.facade=a,$y(a,wt,e),e},jr=function(a){return On(a,wt)?a[wt]:{}},xa=function(a){return On(a,wt)});var Be,wt;sd.exports={set:Ea,get:jr,has:xa,enforce:Oy,getterFor:By}});var Nn=m((V$,ld)=>{"use strict";var Vy=Or(),ud=Function.prototype,nd=ud.apply,od=ud.call;ld.exports=typeof Reflect=="object"&&Reflect.apply||(Vy?od.bind(nd):function(){return od.apply(nd,arguments)})});var Fn=m((_$,cd)=>{"use strict";var _y=Jt(),Ny=oe();cd.exports=function(a){if(_y(a)==="Function")return Ny(a)}});var fd=m(hd=>{"use strict";var dd={}.propertyIsEnumerable,pd=Object.getOwnPropertyDescriptor,Fy=pd&&!dd.call({1:2},1);hd.f=Fy?function(e){var t=pd(this,e);return!!t&&t.enumerable}:dd});var gd=m(bd=>{"use strict";var qy=Ee(),Uy=ge(),Hy=fd(),jy=Hr(),Gy=Zt(),Wy=Ln(),Yy=Oe(),Qy=mn(),md=Object.getOwnPropertyDescriptor;bd.f=qy?md:function(e,t){if(e=Gy(e),t=Wy(t),Qy)try{return md(e,t)}catch(r){}if(Yy(e,t))return jy(!Uy(Hy.f,e,t),e[t])}});var qn=m((q$,Sd)=>{"use strict";var zy=be(),Ky=G(),Jy=/#|\.prototype\./,Gr=function(a,e){var t=Zy[Xy(a)];return t===tT?!0:t===eT?!1:Ky(e)?zy(e):!!e},Xy=Gr.normalize=function(a){return String(a).replace(Jy,".").toLowerCase()},Zy=Gr.data={},eT=Gr.NATIVE="N",tT=Gr.POLYFILL="P";Sd.exports=Gr});var Wr=m((U$,yd)=>{"use strict";var vd=Fn(),rT=We(),iT=Or(),aT=vd(vd.bind);yd.exports=function(a,e){return rT(a),e===void 0?a:iT?aT(a,e):function(){return a.apply(e,arguments)}}});var xe=m((H$,Id)=>{"use strict";var Yr=W(),sT=Nn(),nT=Fn(),oT=G(),uT=gd().f,lT=qn(),ir=Sa(),cT=Wr(),ar=rr(),Td=Oe();qr();var dT=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 sT(a,this,arguments)};return e.prototype=a.prototype,e};Id.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Yr:i?Yr[t]:Yr[t]&&Yr[t].prototype,o=r?ir:ir[t]||ar(ir,t,{})[t],u=o.prototype,l,c,p,d,h,f,b,g,y;for(d in e)l=lT(r?d:t+(i?".":"#")+d,a.forced),c=!l&&n&&Td(n,d),f=o[d],c&&(a.dontCallGetSet?(y=uT(n,d),b=y&&y.value):b=n[d]),h=c&&b?b:e[d],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=cT(h,Yr):a.wrap&&c?g=dT(h):s&&oT(h)?g=nT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&ar(g,"sham",!0),ar(o,d,g),s&&(p=t+"Prototype",Td(ir,p)||ar(ir,p,{}),ar(ir[p],d,h),a.real&&u&&(l||!u[d])&&ar(u,d,h)))}});var Pd=m((j$,xd)=>{"use strict";var Un=Ee(),pT=Oe(),Ed=Function.prototype,hT=Un&&Object.getOwnPropertyDescriptor,Hn=pT(Ed,"name"),fT=Hn&&function(){}.name==="something",mT=Hn&&(!Un||Un&&hT(Ed,"name").configurable);xd.exports={EXISTS:Hn,PROPER:fT,CONFIGURABLE:mT}});var wd=m((G$,Ad)=>{"use strict";var bT=Math.ceil,gT=Math.floor;Ad.exports=Math.trunc||function(e){var t=+e;return(t>0?gT:bT)(t)}});var Pa=m((W$,kd)=>{"use strict";var ST=wd();kd.exports=function(a){var e=+a;return e!==e||e===0?0:ST(e)}});var Ld=m((Y$,Rd)=>{"use strict";var vT=Pa(),yT=Math.max,TT=Math.min;Rd.exports=function(a,e){var t=vT(a);return t<0?yT(t+e,0):TT(t,e)}});var Md=m((Q$,$d)=>{"use strict";var IT=Pa(),ET=Math.min;$d.exports=function(a){var e=IT(a);return e>0?ET(e,9007199254740991):0}});var Aa=m((z$,Cd)=>{"use strict";var xT=Md();Cd.exports=function(a){return xT(a.length)}});var Bd=m((K$,Od)=>{"use strict";var PT=Zt(),AT=Ld(),wT=Aa(),Dd=function(a){return function(e,t,r){var i=PT(e),s=wT(i);if(s===0)return!a&&-1;var n=AT(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}};Od.exports={includes:Dd(!0),indexOf:Dd(!1)}});var Nd=m((J$,_d)=>{"use strict";var kT=oe(),jn=Oe(),RT=Zt(),LT=Bd().indexOf,$T=Ia(),Vd=kT([].push);_d.exports=function(a,e){var t=RT(a),r=0,i=[],s;for(s in t)!jn($T,s)&&jn(t,s)&&Vd(i,s);for(;e.length>r;)jn(t,s=e[r++])&&(~LT(i,s)||Vd(i,s));return i}});var Gn=m((X$,Fd)=>{"use strict";Fd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Ud=m((Z$,qd)=>{"use strict";var MT=Nd(),CT=Gn();qd.exports=Object.keys||function(e){return MT(e,CT)}});var jd=m(Hd=>{"use strict";var DT=Ee(),OT=bn(),BT=At(),VT=qe(),_T=Zt(),NT=Ud();Hd.f=DT&&!OT?Object.defineProperties:function(e,t){VT(e);for(var r=_T(t),i=NT(t),s=i.length,n=0,o;s>n;)BT.f(e,o=i[n++],r[o]);return e}});var Wn=m((tM,Gd)=>{"use strict";var FT=Ge();Gd.exports=FT("document","documentElement")});var Kn=m((rM,Xd)=>{"use strict";var qT=qe(),UT=jd(),Wd=Gn(),HT=Ia(),jT=Wn(),GT=ba(),WT=Ta(),Yd=">",Qd="<",Qn="prototype",zn="script",Kd=WT("IE_PROTO"),Yn=function(){},Jd=function(a){return Qd+zn+Yd+a+Qd+"/"+zn+Yd},zd=function(a){a.write(Jd("")),a.close();var e=a.parentWindow.Object;return a=null,e},YT=function(){var a=GT("iframe"),e="java"+zn+":",t;return a.style.display="none",jT.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Jd("document.F=Object")),t.close(),t.F},wa,ka=function(){try{wa=new ActiveXObject("htmlfile")}catch(e){}ka=typeof document!="undefined"?document.domain&&wa?zd(wa):YT():zd(wa);for(var a=Wd.length;a--;)delete ka[Qn][Wd[a]];return ka()};HT[Kd]=!0;Xd.exports=Object.create||function(e,t){var r;return e!==null?(Yn[Qn]=qT(e),r=new Yn,Yn[Qn]=null,r[Kd]=e):r=ka(),t===void 0?r:UT.f(r,t)}});var ep=m((iM,Zd)=>{"use strict";var QT=be();Zd.exports=!QT(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Xn=m((aM,rp)=>{"use strict";var zT=Oe(),KT=G(),JT=Ur(),XT=Ta(),ZT=ep(),tp=XT("IE_PROTO"),Jn=Object,eI=Jn.prototype;rp.exports=ZT?Jn.getPrototypeOf:function(a){var e=JT(a);if(zT(e,tp))return e[tp];var t=e.constructor;return KT(t)&&e instanceof t?t.prototype:e instanceof Jn?eI:null}});var sr=m((sM,ip)=>{"use strict";var tI=rr();ip.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:tI(a,e,t),a}});var ro=m((nM,np)=>{"use strict";var rI=be(),iI=G(),aI=Ie(),sI=Kn(),ap=Xn(),nI=sr(),oI=te(),uI=De(),to=oI("iterator"),sp=!1,Ye,Zn,eo;[].keys&&(eo=[].keys(),"next"in eo?(Zn=ap(ap(eo)),Zn!==Object.prototype&&(Ye=Zn)):sp=!0);var lI=!aI(Ye)||rI(function(){var a={};return Ye[to].call(a)!==a});lI?Ye={}:uI&&(Ye=sI(Ye));iI(Ye[to])||nI(Ye,to,function(){return this});np.exports={IteratorPrototype:Ye,BUGGY_SAFARI_ITERATORS:sp}});var Ra=m((oM,up)=>{"use strict";var cI=te(),dI=cI("toStringTag"),op={};op[dI]="z";up.exports=String(op)==="[object z]"});var Qr=m((uM,lp)=>{"use strict";var pI=Ra(),hI=G(),La=Jt(),fI=te(),mI=fI("toStringTag"),bI=Object,gI=La(function(){return arguments}())==="Arguments",SI=function(a,e){try{return a[e]}catch(t){}};lp.exports=pI?La:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=SI(e=bI(a),mI))=="string"?t:gI?La(e):(r=La(e))==="Object"&&hI(e.callee)?"Arguments":r}});var dp=m((lM,cp)=>{"use strict";var vI=Ra(),yI=Qr();cp.exports=vI?{}.toString:function(){return"[object "+yI(this)+"]"}});var zr=m((cM,hp)=>{"use strict";var TI=Ra(),II=At().f,EI=rr(),xI=Oe(),PI=dp(),AI=te(),pp=AI("toStringTag");hp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(xI(i,pp)||II(i,pp,{configurable:!0,value:e}),r&&!TI&&EI(i,"toString",PI))}});var mp=m((dM,fp)=>{"use strict";var wI=ro().IteratorPrototype,kI=Kn(),RI=Hr(),LI=zr(),$I=Pt(),MI=function(){return this};fp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=kI(wI,{next:RI(+!r,t)}),LI(a,i,!1,!0),$I[i]=MI,a}});var gp=m((pM,bp)=>{"use strict";var CI=oe(),DI=We();bp.exports=function(a,e,t){try{return CI(DI(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var vp=m((hM,Sp)=>{"use strict";var OI=Ie();Sp.exports=function(a){return OI(a)||a===null}});var Tp=m((fM,yp)=>{"use strict";var BI=vp(),VI=String,_I=TypeError;yp.exports=function(a){if(BI(a))return a;throw new _I("Can't set "+VI(a)+" as a prototype")}});var io=m((mM,Ip)=>{"use strict";var NI=gp(),FI=Ie(),qI=Br(),UI=Tp();Ip.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=NI(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return qI(i),UI(s),FI(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Cp=m((bM,Mp)=>{"use strict";var HI=xe(),jI=ge(),$a=De(),Lp=Pd(),GI=G(),WI=mp(),Ep=Xn(),xp=io(),YI=zr(),QI=rr(),ao=sr(),zI=te(),Pp=Pt(),$p=ro(),KI=Lp.PROPER,JI=Lp.CONFIGURABLE,Ap=$p.IteratorPrototype,Ma=$p.BUGGY_SAFARI_ITERATORS,Kr=zI("iterator"),wp="keys",Jr="values",kp="entries",Rp=function(){return this};Mp.exports=function(a,e,t,r,i,s,n){WI(t,e,r);var o=function(y){if(y===i&&d)return d;if(!Ma&&y&&y in c)return c[y];switch(y){case wp:return function(){return new t(this,y)};case Jr:return function(){return new t(this,y)};case kp:return function(){return new t(this,y)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,p=c[Kr]||c["@@iterator"]||i&&c[i],d=!Ma&&p||o(i),h=e==="Array"&&c.entries||p,f,b,g;if(h&&(f=Ep(h.call(new a)),f!==Object.prototype&&f.next&&(!$a&&Ep(f)!==Ap&&(xp?xp(f,Ap):GI(f[Kr])||ao(f,Kr,Rp)),YI(f,u,!0,!0),$a&&(Pp[u]=Rp))),KI&&i===Jr&&p&&p.name!==Jr&&(!$a&&JI?QI(c,"name",Jr):(l=!0,d=function(){return jI(p,this)})),i)if(b={values:o(Jr),keys:s?d:o(wp),entries:o(kp)},n)for(g in b)(Ma||l||!(g in c))&&ao(c,g,b[g]);else HI({target:e,proto:!0,forced:Ma||l},b);return(!$a||n)&&c[Kr]!==d&&ao(c,Kr,d,{name:i}),Pp[e]=d,b}});var Op=m((gM,Dp)=>{"use strict";Dp.exports=function(a,e){return{value:a,done:e}}});var no=m((SM,Fp)=>{"use strict";var XI=Zt(),so=dn(),Bp=Pt(),_p=_n(),ZI=At().f,eE=Cp(),Ca=Op(),tE=De(),rE=Ee(),Np="Array Iterator",iE=_p.set,aE=_p.getterFor(Np);Fp.exports=eE(Array,"Array",function(a,e){iE(this,{type:Np,target:XI(a),index:0,kind:e})},function(){var a=aE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ca(void 0,!0);switch(a.kind){case"keys":return Ca(t,!1);case"values":return Ca(e[t],!1)}return Ca([t,e[t]],!1)},"values");var Vp=Bp.Arguments=Bp.Array;so("keys");so("values");so("entries");if(!tE&&rE&&Vp.name!=="values")try{ZI(Vp,"name",{value:"values"})}catch(a){}});var Up=m((vM,qp)=>{"use strict";var sE=te(),nE=Pt(),oE=sE("iterator"),uE=Array.prototype;qp.exports=function(a){return a!==void 0&&(nE.Array===a||uE[oE]===a)}});var oo=m((yM,jp)=>{"use strict";var lE=Qr(),Hp=Fr(),cE=Xt(),dE=Pt(),pE=te(),hE=pE("iterator");jp.exports=function(a){if(!cE(a))return Hp(a,hE)||Hp(a,"@@iterator")||dE[lE(a)]}});var Wp=m((TM,Gp)=>{"use strict";var fE=ge(),mE=We(),bE=qe(),gE=Nr(),SE=oo(),vE=TypeError;Gp.exports=function(a,e){var t=arguments.length<2?SE(a):e;if(mE(t))return bE(fE(t,a));throw new vE(gE(a)+" is not iterable")}});var zp=m((IM,Qp)=>{"use strict";var yE=ge(),Yp=qe(),TE=Fr();Qp.exports=function(a,e,t){var r,i;Yp(a);try{if(r=TE(a,"return"),!r){if(e==="throw")throw t;return t}r=yE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Yp(r),t}});var Oa=m((EM,Zp)=>{"use strict";var IE=Wr(),EE=ge(),xE=qe(),PE=Nr(),AE=Up(),wE=Aa(),Kp=_r(),kE=Wp(),RE=oo(),Jp=zp(),LE=TypeError,Da=function(a,e){this.stopped=a,this.result=e},Xp=Da.prototype;Zp.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=IE(e,r),l,c,p,d,h,f,b,g=function(I){return l&&Jp(l,"normal",I),new Da(!0,I)},y=function(I){return i?(xE(I),o?u(I[0],I[1],g):u(I[0],I[1])):o?u(I,g):u(I)};if(s)l=a.iterator;else if(n)l=a;else{if(c=RE(a),!c)throw new LE(PE(a)+" is not iterable");if(AE(c)){for(p=0,d=wE(a);d>p;p++)if(h=y(a[p]),h&&Kp(Xp,h))return h;return new Da(!1)}l=kE(a,c)}for(f=s?a.next:l.next;!(b=EE(f,l)).done;){try{h=y(b.value)}catch(I){Jp(l,"throw",I)}if(typeof h=="object"&&h&&Kp(Xp,h))return h}return new Da(!1)}});var th=m((xM,eh)=>{"use strict";var $E=Ee(),ME=At(),CE=Hr();eh.exports=function(a,e,t){$E?ME.f(a,e,CE(0,t)):a[e]=t}});var rh=m(()=>{"use strict";var DE=xe(),OE=Oa(),BE=th();DE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return OE(e,function(r,i){BE(t,r,i)},{AS_ENTRIES:!0}),t}})});var ah=m((wM,ih)=>{"use strict";no();rh();var VE=Sa();ih.exports=VE.Object.fromEntries});var nh=m((kM,sh)=>{"use strict";sh.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 uh=m(()=>{"use strict";no();var _E=nh(),NE=W(),FE=zr(),oh=Pt();for(Ba in _E)FE(NE[Ba],Ba),oh[Ba]=oh.Array;var Ba});var ch=m(($M,lh)=>{"use strict";var qE=ah();uh();lh.exports=qE});var uo=m((MM,dh)=>{"use strict";var UE=ch();dh.exports=UE});var ph=m(()=>{"use strict"});var lo=m((OM,hh)=>{"use strict";var Xr=W(),HE=er(),jE=Jt(),Va=function(a){return HE.slice(0,a.length)===a};hh.exports=function(){return Va("Bun/")?"BUN":Va("Cloudflare-Workers")?"CLOUDFLARE":Va("Deno/")?"DENO":Va("Node.js/")?"NODE":Xr.Bun&&typeof Bun.version=="string"?"BUN":Xr.Deno&&typeof Deno.version=="object"?"DENO":jE(Xr.process)==="process"?"NODE":Xr.window&&Xr.document?"BROWSER":"REST"}()});var _a=m((BM,fh)=>{"use strict";var GE=lo();fh.exports=GE==="NODE"});var bh=m((VM,mh)=>{"use strict";var WE=At();mh.exports=function(a,e,t){return WE.f(a,e,t)}});var vh=m((_M,Sh)=>{"use strict";var YE=Ge(),QE=bh(),zE=te(),KE=Ee(),gh=zE("species");Sh.exports=function(a){var e=YE(a);KE&&e&&!e[gh]&&QE(e,gh,{configurable:!0,get:function(){return this}})}});var Th=m((NM,yh)=>{"use strict";var JE=_r(),XE=TypeError;yh.exports=function(a,e){if(JE(e,a))return a;throw new XE("Incorrect invocation")}});var po=m((FM,Ih)=>{"use strict";var ZE=oe(),ex=G(),co=qr(),tx=ZE(Function.toString);ex(co.inspectSource)||(co.inspectSource=function(a){return tx(a)});Ih.exports=co.inspectSource});var kh=m((qM,wh)=>{"use strict";var rx=oe(),ix=be(),Eh=G(),ax=Qr(),sx=Ge(),nx=po(),xh=function(){},Ph=sx("Reflect","construct"),ho=/^\s*(?:class|function)\b/,ox=rx(ho.exec),ux=!ho.test(xh),Zr=function(e){if(!Eh(e))return!1;try{return Ph(xh,[],e),!0}catch(t){return!1}},Ah=function(e){if(!Eh(e))return!1;switch(ax(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return ux||!!ox(ho,nx(e))}catch(t){return!0}};Ah.sham=!0;wh.exports=!Ph||ix(function(){var a;return Zr(Zr.call)||!Zr(Object)||!Zr(function(){a=!0})||a})?Ah:Zr});var Lh=m((UM,Rh)=>{"use strict";var lx=kh(),cx=Nr(),dx=TypeError;Rh.exports=function(a){if(lx(a))return a;throw new dx(cx(a)+" is not a constructor")}});var fo=m((HM,Mh)=>{"use strict";var $h=qe(),px=Lh(),hx=Xt(),fx=te(),mx=fx("species");Mh.exports=function(a,e){var t=$h(a).constructor,r;return t===void 0||hx(r=$h(t)[mx])?e:px(r)}});var Dh=m((jM,Ch)=>{"use strict";var bx=oe();Ch.exports=bx([].slice)});var Bh=m((GM,Oh)=>{"use strict";var gx=TypeError;Oh.exports=function(a,e){if(a<e)throw new gx("Not enough arguments");return a}});var mo=m((WM,Vh)=>{"use strict";var Sx=er();Vh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Sx)});var xo=m((YM,Wh)=>{"use strict";var Se=W(),vx=Nn(),yx=Wr(),_h=G(),Tx=Oe(),Gh=be(),Nh=Wn(),Ix=Dh(),Fh=ba(),Ex=Bh(),xx=mo(),Px=_a(),To=Se.setImmediate,Io=Se.clearImmediate,Ax=Se.process,bo=Se.Dispatch,wx=Se.Function,qh=Se.MessageChannel,kx=Se.String,go=0,ei={},Uh="onreadystatechange",ti,kt,So,vo;Gh(function(){ti=Se.location});var Eo=function(a){if(Tx(ei,a)){var e=ei[a];delete ei[a],e()}},yo=function(a){return function(){Eo(a)}},Hh=function(a){Eo(a.data)},jh=function(a){Se.postMessage(kx(a),ti.protocol+"//"+ti.host)};(!To||!Io)&&(To=function(e){Ex(arguments.length,1);var t=_h(e)?e:wx(e),r=Ix(arguments,1);return ei[++go]=function(){vx(t,void 0,r)},kt(go),go},Io=function(e){delete ei[e]},Px?kt=function(a){Ax.nextTick(yo(a))}:bo&&bo.now?kt=function(a){bo.now(yo(a))}:qh&&!xx?(So=new qh,vo=So.port2,So.port1.onmessage=Hh,kt=yx(vo.postMessage,vo)):Se.addEventListener&&_h(Se.postMessage)&&!Se.importScripts&&ti&&ti.protocol!=="file:"&&!Gh(jh)?(kt=jh,Se.addEventListener("message",Hh,!1)):Uh in Fh("script")?kt=function(a){Nh.appendChild(Fh("script"))[Uh]=function(){Nh.removeChild(this),Eo(a)}}:kt=function(a){setTimeout(yo(a),0)});Wh.exports={set:To,clear:Io}});var zh=m((QM,Qh)=>{"use strict";var Yh=W(),Rx=Ee(),Lx=Object.getOwnPropertyDescriptor;Qh.exports=function(a){if(!Rx)return Yh[a];var e=Lx(Yh,a);return e&&e.value}});var Po=m((zM,Jh)=>{"use strict";var Kh=function(){this.head=null,this.tail=null};Kh.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}}};Jh.exports=Kh});var Zh=m((KM,Xh)=>{"use strict";var $x=er();Xh.exports=/ipad|iphone|ipod/i.test($x)&&typeof Pebble!="undefined"});var tf=m((JM,ef)=>{"use strict";var Mx=er();ef.exports=/web0s(?!.*chrome)/i.test(Mx)});var lf=m((XM,uf)=>{"use strict";var or=W(),Cx=zh(),rf=Wr(),Ao=xo().set,Dx=Po(),Ox=mo(),Bx=Zh(),Vx=tf(),wo=_a(),af=or.MutationObserver||or.WebKitMutationObserver,sf=or.document,nf=or.process,Na=or.Promise,Lo=Cx("queueMicrotask"),nr,ko,Ro,Fa,of;Lo||(ri=new Dx,ii=function(){var a,e;for(wo&&(a=nf.domain)&&a.exit();e=ri.get();)try{e()}catch(t){throw ri.head&&nr(),t}a&&a.enter()},!Ox&&!wo&&!Vx&&af&&sf?(ko=!0,Ro=sf.createTextNode(""),new af(ii).observe(Ro,{characterData:!0}),nr=function(){Ro.data=ko=!ko}):!Bx&&Na&&Na.resolve?(Fa=Na.resolve(void 0),Fa.constructor=Na,of=rf(Fa.then,Fa),nr=function(){of(ii)}):wo?nr=function(){nf.nextTick(ii)}:(Ao=rf(Ao,or),nr=function(){Ao(ii)}),Lo=function(a){ri.head||nr(),ri.add(a)});var ri,ii;uf.exports=Lo});var df=m((ZM,cf)=>{"use strict";cf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var qa=m((eC,pf)=>{"use strict";pf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Rt=m((tC,hf)=>{"use strict";var _x=W();hf.exports=_x.Promise});var ur=m((rC,gf)=>{"use strict";var Nx=W(),ai=Rt(),Fx=G(),qx=qn(),Ux=po(),Hx=te(),ff=lo(),jx=De(),$o=yn(),mf=ai&&ai.prototype,Gx=Hx("species"),Mo=!1,bf=Fx(Nx.PromiseRejectionEvent),Wx=qx("Promise",function(){var a=Ux(ai),e=a!==String(ai);if(!e&&$o===66||jx&&!(mf.catch&&mf.finally))return!0;if(!$o||$o<51||!/native code/.test(a)){var t=new ai(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Gx]=r,Mo=t.then(function(){})instanceof r,!Mo)return!0}return!e&&(ff==="BROWSER"||ff==="DENO")&&!bf});gf.exports={CONSTRUCTOR:Wx,REJECTION_EVENT:bf,SUBCLASSING:Mo}});var lr=m((iC,vf)=>{"use strict";var Sf=We(),Yx=TypeError,Qx=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new Yx("Bad Promise constructor");e=r,t=i}),this.resolve=Sf(e),this.reject=Sf(t)};vf.exports.f=function(a){return new Qx(a)}});var _f=m(()=>{"use strict";var zx=xe(),Kx=De(),Ga=_a(),ut=W(),hr=ge(),yf=sr(),Tf=io(),Jx=zr(),Xx=vh(),Zx=We(),ja=G(),eP=Ie(),tP=Th(),rP=fo(),Af=xo().set,Vo=lf(),iP=df(),aP=qa(),sP=Po(),wf=_n(),Wa=Rt(),_o=ur(),kf=lr(),Ya="Promise",Rf=_o.CONSTRUCTOR,nP=_o.REJECTION_EVENT,oP=_o.SUBCLASSING,Co=wf.getterFor(Ya),uP=wf.set,cr=Wa&&Wa.prototype,Lt=Wa,Ua=cr,Lf=ut.TypeError,Do=ut.document,No=ut.process,Oo=kf.f,lP=Oo,cP=!!(Do&&Do.createEvent&&ut.dispatchEvent),$f="unhandledrejection",dP="rejectionhandled",If=0,Mf=1,pP=2,Fo=1,Cf=2,Ha,Ef,hP,xf,Df=function(a){var e;return eP(a)&&ja(e=a.then)?e:!1},Of=function(a,e){var t=e.value,r=e.state===Mf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Cf&&mP(e),e.rejection=Fo),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Lf("Promise-chain cycle")):(l=Df(u))?hr(l,u,s,n):s(u)):n(t)}catch(p){o&&!c&&o.exit(),n(p)}},Bf=function(a,e){a.notified||(a.notified=!0,Vo(function(){for(var t=a.reactions,r;r=t.get();)Of(r,a);a.notified=!1,e&&!a.rejection&&fP(a)}))},Vf=function(a,e,t){var r,i;cP?(r=Do.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),ut.dispatchEvent(r)):r={promise:e,reason:t},!nP&&(i=ut["on"+a])?i(r):a===$f&&iP("Unhandled promise rejection",t)},fP=function(a){hr(Af,ut,function(){var e=a.facade,t=a.value,r=Pf(a),i;if(r&&(i=aP(function(){Ga?No.emit("unhandledRejection",t,e):Vf($f,e,t)}),a.rejection=Ga||Pf(a)?Cf:Fo,i.error))throw i.value})},Pf=function(a){return a.rejection!==Fo&&!a.parent},mP=function(a){hr(Af,ut,function(){var e=a.facade;Ga?No.emit("rejectionHandled",e):Vf(dP,e,a.value)})},dr=function(a,e,t){return function(r){a(e,r,t)}},pr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=pP,Bf(a,!0))},Bo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Lf("Promise can't be resolved itself");var r=Df(e);r?Vo(function(){var i={done:!1};try{hr(r,e,dr(Bo,i,a),dr(pr,i,a))}catch(s){pr(i,s,a)}}):(a.value=e,a.state=Mf,Bf(a,!1))}catch(i){pr({done:!1},i,a)}}};if(Rf&&(Lt=function(e){tP(this,Ua),Zx(e),hr(Ha,this);var t=Co(this);try{e(dr(Bo,t),dr(pr,t))}catch(r){pr(t,r)}},Ua=Lt.prototype,Ha=function(e){uP(this,{type:Ya,done:!1,notified:!1,parent:!1,reactions:new sP,rejection:!1,state:If,value:void 0})},Ha.prototype=yf(Ua,"then",function(e,t){var r=Co(this),i=Oo(rP(this,Lt));return r.parent=!0,i.ok=ja(e)?e:!0,i.fail=ja(t)&&t,i.domain=Ga?No.domain:void 0,r.state===If?r.reactions.add(i):Vo(function(){Of(i,r)}),i.promise}),Ef=function(){var a=new Ha,e=Co(a);this.promise=a,this.resolve=dr(Bo,e),this.reject=dr(pr,e)},kf.f=Oo=function(a){return a===Lt||a===hP?new Ef(a):lP(a)},!Kx&&ja(Wa)&&cr!==Object.prototype)){xf=cr.then,oP||yf(cr,"then",function(e,t){var r=this;return new Lt(function(i,s){hr(xf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete cr.constructor}catch(a){}Tf&&Tf(cr,Ua)}zx({global:!0,constructor:!0,wrap:!0,forced:Rf},{Promise:Lt});Jx(Lt,Ya,!1,!0);Xx(Ya)});var Hf=m((nC,Uf)=>{"use strict";var bP=te(),Ff=bP("iterator"),qf=!1;try{Nf=0,qo={next:function(){return{done:!!Nf++}},return:function(){qf=!0}},qo[Ff]=function(){return this},Array.from(qo,function(){throw 2})}catch(a){}var Nf,qo;Uf.exports=function(a,e){try{if(!e&&!qf)return!1}catch(i){return!1}var t=!1;try{var r={};r[Ff]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Uo=m((oC,jf)=>{"use strict";var gP=Rt(),SP=Hf(),vP=ur().CONSTRUCTOR;jf.exports=vP||!SP(function(a){gP.all(a).then(void 0,function(){})})});var Gf=m(()=>{"use strict";var yP=xe(),TP=ge(),IP=We(),EP=lr(),xP=qa(),PP=Oa(),AP=Uo();yP({target:"Promise",stat:!0,forced:AP},{all:function(e){var t=this,r=EP.f(t),i=r.resolve,s=r.reject,n=xP(function(){var o=IP(t.resolve),u=[],l=0,c=1;PP(e,function(p){var d=l++,h=!1;c++,TP(o,t,p).then(function(f){h||(h=!0,u[d]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Yf=m(()=>{"use strict";var wP=xe(),kP=De(),RP=ur().CONSTRUCTOR,jo=Rt(),LP=Ge(),$P=G(),MP=sr(),Wf=jo&&jo.prototype;wP({target:"Promise",proto:!0,forced:RP,real:!0},{catch:function(a){return this.then(void 0,a)}});!kP&&$P(jo)&&(Ho=LP("Promise").prototype.catch,Wf.catch!==Ho&&MP(Wf,"catch",Ho,{unsafe:!0}));var Ho});var Qf=m(()=>{"use strict";var CP=xe(),DP=ge(),OP=We(),BP=lr(),VP=qa(),_P=Oa(),NP=Uo();CP({target:"Promise",stat:!0,forced:NP},{race:function(e){var t=this,r=BP.f(t),i=r.reject,s=VP(function(){var n=OP(t.resolve);_P(e,function(o){DP(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var zf=m(()=>{"use strict";var FP=xe(),qP=lr(),UP=ur().CONSTRUCTOR;FP({target:"Promise",stat:!0,forced:UP},{reject:function(e){var t=qP.f(this),r=t.reject;return r(e),t.promise}})});var Go=m((bC,Kf)=>{"use strict";var HP=qe(),jP=Ie(),GP=lr();Kf.exports=function(a,e){if(HP(a),jP(e)&&e.constructor===a)return e;var t=GP.f(a),r=t.resolve;return r(e),t.promise}});var Zf=m(()=>{"use strict";var WP=xe(),YP=Ge(),Jf=De(),QP=Rt(),Xf=ur().CONSTRUCTOR,zP=Go(),KP=YP("Promise"),JP=Jf&&!Xf;WP({target:"Promise",stat:!0,forced:Jf||Xf},{resolve:function(e){return zP(JP&&this===KP?QP:this,e)}})});var em=m(()=>{"use strict";_f();Gf();Yf();Qf();zf();Zf()});var am=m(()=>{"use strict";var XP=xe(),ZP=De(),Qa=Rt(),eA=be(),rm=Ge(),im=G(),tA=fo(),tm=Go(),rA=sr(),Yo=Qa&&Qa.prototype,iA=!!Qa&&eA(function(){Yo.finally.call({then:function(){}},function(){})});XP({target:"Promise",proto:!0,real:!0,forced:iA},{finally:function(a){var e=tA(this,rm("Promise")),t=im(a);return this.then(t?function(r){return tm(e,a()).then(function(){return r})}:a,t?function(r){return tm(e,a()).then(function(){throw r})}:a)}});!ZP&&im(Qa)&&(Wo=rm("Promise").prototype.finally,Yo.finally!==Wo&&rA(Yo,"finally",Wo,{unsafe:!0}));var Wo});var za=m((EC,sm)=>{"use strict";var aA=Ge();sm.exports=aA});var om=m((xC,nm)=>{"use strict";ph();em();am();var sA=za();nm.exports=sA("Promise","finally")});var lm=m((PC,um)=>{"use strict";var nA=om();um.exports=nA});var Ka=m((AC,cm)=>{"use strict";var oA=lm();cm.exports=oA});var Om=m(()=>{"use strict";var BA=xe(),VA=Ur(),_A=Aa(),NA=Pa(),FA=dn();BA({target:"Array",proto:!0},{at:function(e){var t=VA(this),r=_A(t),i=NA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});FA("at")});var Vm=m((OD,Bm)=>{"use strict";Om();var qA=za();Bm.exports=qA("Array","at")});var Nm=m((BD,_m)=>{"use strict";var UA=Vm();_m.exports=UA});var ui=m((VD,Fm)=>{"use strict";var HA=Nm();Fm.exports=HA});var _b=m(()=>{"use strict"});var Nb=m(()=>{"use strict"});var qb=m((VV,Fb)=>{"use strict";var Zw=Ie(),ek=Jt(),tk=te(),rk=tk("match");Fb.exports=function(a){var e;return Zw(a)&&((e=a[rk])!==void 0?!!e:ek(a)==="RegExp")}});var Hb=m((_V,Ub)=>{"use strict";var ik=Qr(),ak=String;Ub.exports=function(a){if(ik(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return ak(a)}});var Gb=m((NV,jb)=>{"use strict";var sk=qe();jb.exports=function(){var a=sk(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 Qb=m((FV,Yb)=>{"use strict";var nk=ge(),ok=Oe(),uk=_r(),lk=Gb(),Wb=RegExp.prototype;Yb.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Wb)&&!ok(a,"flags")&&uk(Wb,a)?nk(lk,a):e}});var Kb=m((qV,zb)=>{"use strict";var Eu=oe(),ck=Ur(),dk=Math.floor,Tu=Eu("".charAt),pk=Eu("".replace),Iu=Eu("".slice),hk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,fk=/\$([$&'`]|\d{1,2})/g;zb.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=fk;return i!==void 0&&(i=ck(i),u=hk),pk(s,u,function(l,c){var p;switch(Tu(c,0)){case"$":return"$";case"&":return a;case"`":return Iu(e,0,t);case"'":return Iu(e,n);case"<":p=i[Iu(c,1,-1)];break;default:var d=+c;if(d===0)return l;if(d>o){var h=dk(d/10);return h===0?l:h<=o?r[h-1]===void 0?Tu(c,1):r[h-1]+Tu(c,1):l}p=r[d-1]}return p===void 0?"":p})}});var Zb=m(()=>{"use strict";var mk=xe(),bk=ge(),Pu=oe(),Jb=Br(),gk=G(),Sk=Xt(),vk=qb(),Er=Hb(),yk=Fr(),Tk=Qb(),Ik=Kb(),Ek=te(),xk=De(),Pk=Ek("replace"),Ak=TypeError,xu=Pu("".indexOf),wk=Pu("".replace),Xb=Pu("".slice),kk=Math.max;mk({target:"String",proto:!0},{replaceAll:function(e,t){var r=Jb(this),i,s,n,o,u,l,c,p,d,h,f=0,b="";if(!Sk(e)){if(i=vk(e),i&&(s=Er(Jb(Tk(e))),!~xu(s,"g")))throw new Ak("`.replaceAll` does not allow non-global regexes");if(n=yk(e,Pk),n)return bk(n,e,r,t);if(xk&&i)return wk(Er(r),e,t)}for(o=Er(r),u=Er(e),l=gk(t),l||(t=Er(t)),c=u.length,p=kk(1,c),d=xu(o,u);d!==-1;)h=l?Er(t(u,d,o)):Ik(u,o,d,[],void 0,t),b+=Xb(o,f,d)+h,f=d+c,d=d+p>o.length?-1:xu(o,u,d+p);return f<o.length&&(b+=Xb(o,f)),b}})});var tg=m((jV,eg)=>{"use strict";_b();Nb();Zb();var Rk=za();eg.exports=Rk("String","replaceAll")});var ig=m((GV,rg)=>{"use strict";var Lk=tg();rg.exports=Lk});var sg=m((WV,ag)=>{"use strict";var $k=ig();ag.exports=$k});var Rl="2.0.108-dev.ce9f9a29.0";var ne=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ne||{}),ot=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(ot||{});var ha=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ha||{}),sn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(sn||{});var nn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(nn||{});import{assertNever as Ol,assertNonNullable as YS,isNonNullable as fa,ValueSubject as on,Subject as QS,Subscription as zS,merge as KS,observableFrom as JS,fromEvent as $l,map as Ml,tap as Cl,filterChanged as XS,isNullable as un,ErrorCategory as Dl}from"@vkontakte/videoplayer-shared";var Ll=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var ma=class{constructor(e){this.connection$=new on(void 0);this.castState$=new on("NOT_AVAILABLE");this.errorEvent$=new QS;this.realCastState$=new on("NOT_AVAILABLE");this.subscription=new zS;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=fa((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Ll("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Dl.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(){fa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();un(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();un(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add($l(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Ol(i.sessionState)}})).add(KS($l(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Cl(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Ml(i=>i.castState)),JS([r.getCastState()])).pipe(XS(),Ml(ZS),Cl(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o;let s=i==="CONNECTED",n=fa(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();YS(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;(un(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?fa(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:Dl.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},ZS=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 Ol(a)}};var rS=Fe(uo(),1);var ym=Fe(Ka(),1);import{assertNever as dm}from"@vkontakte/videoplayer-shared";var ee=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:dm(t)}return a},Qo=(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:dm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as uA,Subject as Ja,merge as pm}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new Ja;this.transitionEnded$=new Ja;this.transitionUpdated$=new Ja;this.forceChanged$=new Ja;this.stateChangeStarted$=pm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=pm(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||uA(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}};import{assertNever as lA}from"@vkontakte/videoplayer-shared";var hm=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 lA(a)}};import{assertNever as fr,assertNonNullable as $t,debounce as fm,ErrorCategory as mm,fromEvent as Mt,isNonNullable as bm,map as gm,merge as Sm,observableFrom as cA,Subject as dA,Subscription as zo,timeout as pA,getHighestQuality as hA}from"@vkontakte/videoplayer-shared";var fA=5,mA=5,bA=500,vm=7e3,si=class{constructor(e){this.subscription=new zo;this.loadMediaTimeoutSubscription=new zo;this.videoState=new $("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:fr(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:fr(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:fr(e)}break}default:fr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(hm(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 zo;this.subscription.add(e),this.subscription.add(Sm(this.videoState.stateChangeStarted$.pipe(gm(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(gm(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 dA;e.add(i.pipe(fm(bA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Mt(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)>fA)&&i.next(o),s=o})),e.add(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Mt(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<mA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(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:fr(n)}}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Sm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,cA(["init"])).pipe(fm(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"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(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"),E(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"),E(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"&&E(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];$t(c);let p=hA(Object.keys(c));$t(p);let d=c[p];$t(d),r=d,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];$t(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];$t(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];$t(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];$t(c),r=ee(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",p=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:mm.VIDEO_PIPELINE,message:c,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return fr(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 bm(o)&&(n.metadata.title=o),bm(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(pA(vm).subscribe(()=>s(`timeout(${vm})`)))});(0,ym.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:mm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Im}from"@vkontakte/videoplayer-shared";import{clearVideoElement as gA}from"@vkontakte/videoplayer-shared";var Tm=a=>{try{a.pause(),a.playbackRate=0,gA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as SA,Subscription as vA}from"@vkontakte/videoplayer-shared";var Ko=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)}},Jo=window.WeakMap?new WeakMap:new Ko,Xo=window.WeakMap?new WeakMap:new Map,yA=(a,e=20)=>{let t=0;return SA(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},ue=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Im(t):(t=document.createElement("video"),a.appendChild(t)),Jo.set(t,r);let i=new vA;return i.add(yA(t,e)),Xo.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},le=a=>{let e=Xo.get(a);e==null||e.unsubscribe(),Xo.delete(a);let t=Jo.get(a);Jo.delete(a),t?Im(a):Tm(a)};import{assertNonNullable as ni,isNonNullable as He,isNullable as EA,fromEvent as mr,merge as Em,observableFrom as xm,filterChanged as Pm,map as oi,Subject as Am,Subscription as xA,ValueSubject as PA,ErrorCategory as AA}from"@vkontakte/videoplayer-shared";import{isNonNullable as Zo,isNullable as TA,Subscription as IA}from"@vkontakte/videoplayer-shared";var Xa=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=TA(i),l=new IA;return i&&l.add(i.subscribe(c=>{let p=a.getState();r(c,p)&&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},Ue=(a,e,t)=>Xa(e,()=>a.loop,r=>{Zo(r)&&(a.loop=r)},{onError:t}),ce=(a,e,t,r)=>Xa(e,()=>({muted:a.muted,volume:a.volume}),i=>{Zo(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}),Pe=(a,e,t,r)=>Xa(e,()=>a.playbackRate,i=>{Zo(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),lt=Xa;var wA=a=>["__",a.language,a.label].join("|"),kA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},eu=class a{constructor(){this.available$=new Am;this.current$=new PA(void 0);this.error$=new Am;this.subscription=new xA;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:AA.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(lt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{He(s)&&this.setInternal(s)},{equal:(s,n)=>He(s)&&He(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(oi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(lt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{He(s)&&this.setExternal(s)},{equal:(s,n)=>He(s)&&He(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(oi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(lt(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(lt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ni(this.video);let{textTracks:e}=this.video;this.subscription.add(mr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Em(mr(e,"addtrack"),mr(e,"removetrack"),xm(["init"])).pipe(oi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Pm((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Em(mr(e,"change"),xm(["init"])).pipe(oi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),oi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Pm()).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(mr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,p,d,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((d=(p=o.target)==null?void 0:p.cues)!=null?d:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(mr(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;He(t.align)&&(i.align=t.align),He(t.position)&&(i.position=t.position),He(t.size)&&(i.size=t.size),He(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){ni(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,i=e.id?e.id:wA(e),s=this.externalTracks.has(i),n=i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(i))==null?void 0:o.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(i))==null?void 0:u.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){ni(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(EA(e)||!kA(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){ni(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){ni(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)}},Ae=eu;var ze=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 wm=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},tu=a=>{let e=wm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},km=a=>{let e=wm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as we,map as ct,merge as Lm,filterChanged as LA,isNonNullable as $m,Subject as $A,filter as Mm,mapTo as Cm,combine as MA,once as CA,ErrorCategory as DA,ValueSubject as Dm,clientChecker as OA}from"@vkontakte/videoplayer-shared";var RA=3,Rm=(a,e,t=RA)=>{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 de=a=>{let e=S=>we(a,S).pipe(Cm(void 0)),r=Lm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>we(a,S))).pipe(ct(S=>S.type==="ended"?a.readyState<2:a.readyState<3),LA()),i=Lm(we(a,"progress"),we(a,"timeupdate")).pipe(ct(()=>Rm(a.buffered,a.currentTime))),s=OA.isSafari?MA({play:e("play").pipe(CA()),playing:e("playing")}).pipe(Cm(void 0)):e("playing"),n=we(a,"volumechange").pipe(ct(()=>({muted:a.muted,volume:a.volume}))),o=we(a,"ratechange").pipe(ct(()=>a.playbackRate)),u=we(a,"error").pipe(Mm(()=>!!(a.error||a.played.length)),ct(()=>{var v;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:DA.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(v=a.error)!=null?v:void 0}})),l=we(a,"timeupdate").pipe(ct(()=>a.currentTime)),c=new $A,p=.3,d;l.subscribe(S=>{a.loop&&$m(d)&&$m(S)&&d>=a.duration-p&&S<=p&&c.next(d),d=S});let h=e("pause").pipe(Mm(()=>!a.error&&d!==a.duration)),f=we(a,"enterpictureinpicture"),b=we(a,"leavepictureinpicture"),g=new Dm(km(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let y=new Dm(tu(a));return we(a,"fullscreenchange").pipe(ct(()=>tu(a))).subscribe(y),{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$:we(a,"durationchange").pipe(ct(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:y}};import{VideoQuality as dt}from"@vkontakte/videoplayer-shared";var pt=a=>{switch(a){case"mobile":return dt.Q_144P;case"lowest":return dt.Q_240P;case"low":return dt.Q_360P;case"sd":case"medium":return dt.Q_480P;case"hd":case"high":return dt.Q_720P;case"fullhd":case"full":return dt.Q_1080P;case"quadhd":case"quad":return dt.Q_1440P;case"ultrahd":case"ultra":return dt.Q_2160P}};var nu=Fe(ui(),1);import{isNonNullable as ht,isNullable as iu,now as Wm,isHigher as au,isHigherOrEqual as jm,isInvariantQuality as Gm,isLower as su,isLowerOrEqual as jA,videoSizeToQuality as GA,assertNotEmptyArray as WA}from"@vkontakte/videoplayer-shared";var ru=!1,Ke={},qm=a=>{ru=a},Um=()=>{Ke={}},Hm=a=>{a(Ke)},li=(a,e)=>{var t;ru&&(Ke.meta=(t=Ke.meta)!=null?t:{},Ke.meta[a]=e)},re=class{constructor(e){this.name=e}next(e){var r,i;if(!ru)return;Ke.series=(r=Ke.series)!=null?r:{};let t=(i=Ke.series[this.name])!=null?i:[];t.push([Date.now(),e]),Ke.series[this.name]=t}};var YA=new re("best_bitrate"),QA=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t,Za=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Wm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},zA='Assertion "ABR Tracks is empty array" failed',KA=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:c,abrLogger:p})=>{var R,L,w,q,K;WA(a,zA);let d=r.usePixelRatio&&(R=window.devicePixelRatio)!=null?R:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*d*r.containerSizeFactor,height:e.height*d*r.containerSizeFactor},f=h&&GA(h),b=r.considerPlaybackRate&&ht(o)?o:1,g=a.filter(k=>!Gm(k.quality)).sort((k,x)=>au(k.quality,x.quality)?-1:1),y=(L=(0,nu.default)(g,-1))==null?void 0:L.quality,I=(w=(0,nu.default)(g,0))==null?void 0:w.quality,S=iu(i)||ht(i.min)&&ht(i.max)&&su(i.max,i.min)||ht(i.min)&&I&&au(i.min,I)||ht(i.max)&&y&&su(i.max,y),v=b*QA(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),T={},M=g.filter(k=>(f?su(k.quality,f):!0)?(ht(t)&&isFinite(t)&&ht(k.bitrate)?t-s>=k.bitrate*v:!0)?r.lazyQualitySwitch&&ht(r.minBufferToSwitchUp)&&u&&!Gm(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&au(k.quality,u.quality)?(T[k.quality]="Buffer",!1):!!c&&jm(k.quality,c)?(T[k.quality]="DroppedFramesLimit",!1):S||(iu(i.max)||jA(k.quality,i.max))&&(iu(i.min)||jm(k.quality,i.min))?!0:(T[k.quality]="FitsQualityLimits",!1):(T[k.quality]="FitsThroughput",!1):(T[k.quality]="FitsContainer",!1))[0];M&&M.bitrate&&YA.next(M.bitrate);let A=(q=M!=null?M:g[Math.ceil((g.length-1)/2)])!=null?q:a[0];A.quality!==((K=l==null?void 0:l.last)==null?void 0:K.quality)&&p({message:`
7
- [available tracks]
6
+ var tv=Object.create;var Cc=Object.defineProperty;var rv=Object.getOwnPropertyDescriptor;var iv=Object.getOwnPropertyNames;var av=Object.getPrototypeOf,sv=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var nv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of iv(e))!sv.call(a,i)&&i!==t&&Cc(a,i,{get:()=>e[i],enumerable:!(r=rv(e,i))||r.enumerable});return a};var Ue=(a,e,t)=>(t=a!=null?tv(av(a)):{},nv(e||!a||!a.__esModule?Cc(t,"default",{value:a,enumerable:!0}):t,a));var ve=m((eL,qc)=>{"use strict";qc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Fr=m((tL,Uc)=>{"use strict";var fv=ve();Uc.exports=!fv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var ce=m((rL,Gc)=>{"use strict";var Hc=Fr(),jc=Function.prototype,mn=jc.call,mv=Hc&&jc.bind.bind(mn,mn);Gc.exports=Hc?mv:function(a){return function(){return mn.apply(a,arguments)}}});var tr=m((iL,Yc)=>{"use strict";var Wc=ce(),bv=Wc({}.toString),gv=Wc("".slice);Yc.exports=function(a){return gv(bv(a),8,-1)}});var zc=m((aL,Qc)=>{"use strict";var Sv=ce(),vv=ve(),yv=tr(),bn=Object,Tv=Sv("".split);Qc.exports=vv(function(){return!bn("z").propertyIsEnumerable(0)})?function(a){return yv(a)==="String"?Tv(a,""):bn(a)}:bn});var rr=m((sL,Kc)=>{"use strict";Kc.exports=function(a){return a==null}});var qr=m((nL,Jc)=>{"use strict";var Iv=rr(),Ev=TypeError;Jc.exports=function(a){if(Iv(a))throw new Ev("Can't call method on "+a);return a}});var ir=m((oL,Xc)=>{"use strict";var xv=zc(),Pv=qr();Xc.exports=function(a){return xv(Pv(a))}});var gn=m((uL,Zc)=>{"use strict";Zc.exports=function(){}});var $t=m((cL,el)=>{"use strict";el.exports={}});var Y=m((Sn,tl)=>{"use strict";var Ur=function(a){return a&&a.Math===Math&&a};tl.exports=Ur(typeof globalThis=="object"&&globalThis)||Ur(typeof window=="object"&&window)||Ur(typeof self=="object"&&self)||Ur(typeof global=="object"&&global)||Ur(typeof Sn=="object"&&Sn)||function(){return this}()||Function("return this")()});var W=m((lL,rl)=>{"use strict";var vn=typeof document=="object"&&document.all;rl.exports=typeof vn=="undefined"&&vn!==void 0?function(a){return typeof a=="function"||a===vn}:function(a){return typeof a=="function"}});var sl=m((dL,al)=>{"use strict";var Av=Y(),wv=W(),il=Av.WeakMap;al.exports=wv(il)&&/native code/.test(String(il))});var Pe=m((pL,nl)=>{"use strict";var kv=W();nl.exports=function(a){return typeof a=="object"?a!==null:kv(a)}});var Ae=m((hL,ol)=>{"use strict";var Rv=ve();ol.exports=!Rv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ea=m((fL,cl)=>{"use strict";var $v=Y(),ul=Pe(),yn=$v.document,Lv=ul(yn)&&ul(yn.createElement);cl.exports=function(a){return Lv?yn.createElement(a):{}}});var Tn=m((mL,ll)=>{"use strict";var Mv=Ae(),Cv=ve(),Dv=Ea();ll.exports=!Mv&&!Cv(function(){return Object.defineProperty(Dv("div"),"a",{get:function(){return 7}}).a!==7})});var In=m((bL,dl)=>{"use strict";var Bv=Ae(),Ov=ve();dl.exports=Bv&&Ov(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var He=m((gL,pl)=>{"use strict";var Vv=Pe(),_v=String,Nv=TypeError;pl.exports=function(a){if(Vv(a))return a;throw new Nv(_v(a)+" is not an object")}});var ye=m((SL,hl)=>{"use strict";var Fv=Fr(),xa=Function.prototype.call;hl.exports=Fv?xa.bind(xa):function(){return xa.apply(xa,arguments)}});var Pa=m((vL,fl)=>{"use strict";fl.exports={}});var Ye=m((yL,bl)=>{"use strict";var En=Pa(),xn=Y(),qv=W(),ml=function(a){return qv(a)?a:void 0};bl.exports=function(a,e){return arguments.length<2?ml(En[a])||ml(xn[a]):En[a]&&En[a][e]||xn[a]&&xn[a][e]}});var Hr=m((TL,gl)=>{"use strict";var Uv=ce();gl.exports=Uv({}.isPrototypeOf)});var ar=m((IL,yl)=>{"use strict";var Hv=Y(),Sl=Hv.navigator,vl=Sl&&Sl.userAgent;yl.exports=vl?String(vl):""});var An=m((EL,Al)=>{"use strict";var Pl=Y(),Pn=ar(),Tl=Pl.process,Il=Pl.Deno,El=Tl&&Tl.versions||Il&&Il.version,xl=El&&El.v8,Be,Aa;xl&&(Be=xl.split("."),Aa=Be[0]>0&&Be[0]<4?1:+(Be[0]+Be[1]));!Aa&&Pn&&(Be=Pn.match(/Edge\/(\d+)/),(!Be||Be[1]>=74)&&(Be=Pn.match(/Chrome\/(\d+)/),Be&&(Aa=+Be[1])));Al.exports=Aa});var wn=m((xL,kl)=>{"use strict";var wl=An(),jv=ve(),Gv=Y(),Wv=Gv.String;kl.exports=!!Object.getOwnPropertySymbols&&!jv(function(){var a=Symbol("symbol detection");return!Wv(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&wl&&wl<41})});var kn=m((PL,Rl)=>{"use strict";var Yv=wn();Rl.exports=Yv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Rn=m((AL,$l)=>{"use strict";var Qv=Ye(),zv=W(),Kv=Hr(),Jv=kn(),Xv=Object;$l.exports=Jv?function(a){return typeof a=="symbol"}:function(a){var e=Qv("Symbol");return zv(e)&&Kv(e.prototype,Xv(a))}});var jr=m((wL,Ll)=>{"use strict";var Zv=String;Ll.exports=function(a){try{return Zv(a)}catch(e){return"Object"}}});var Qe=m((kL,Ml)=>{"use strict";var ey=W(),ty=jr(),ry=TypeError;Ml.exports=function(a){if(ey(a))return a;throw new ry(ty(a)+" is not a function")}});var Gr=m((RL,Cl)=>{"use strict";var iy=Qe(),ay=rr();Cl.exports=function(a,e){var t=a[e];return ay(t)?void 0:iy(t)}});var Bl=m(($L,Dl)=>{"use strict";var $n=ye(),Ln=W(),Mn=Pe(),sy=TypeError;Dl.exports=function(a,e){var t,r;if(e==="string"&&Ln(t=a.toString)&&!Mn(r=$n(t,a))||Ln(t=a.valueOf)&&!Mn(r=$n(t,a))||e!=="string"&&Ln(t=a.toString)&&!Mn(r=$n(t,a)))return r;throw new sy("Can't convert object to primitive value")}});var Oe=m((LL,Ol)=>{"use strict";Ol.exports=!0});var Nl=m((ML,_l)=>{"use strict";var Vl=Y(),ny=Object.defineProperty;_l.exports=function(a,e){try{ny(Vl,a,{value:e,configurable:!0,writable:!0})}catch(t){Vl[a]=e}return e}});var Wr=m((CL,Ul)=>{"use strict";var oy=Oe(),uy=Y(),cy=Nl(),Fl="__core-js_shared__",ql=Ul.exports=uy[Fl]||cy(Fl,{});(ql.versions||(ql.versions=[])).push({version:"3.38.0",mode:oy?"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 Cn=m((DL,jl)=>{"use strict";var Hl=Wr();jl.exports=function(a,e){return Hl[a]||(Hl[a]=e||{})}});var Yr=m((BL,Gl)=>{"use strict";var ly=qr(),dy=Object;Gl.exports=function(a){return dy(ly(a))}});var Ve=m((OL,Wl)=>{"use strict";var py=ce(),hy=Yr(),fy=py({}.hasOwnProperty);Wl.exports=Object.hasOwn||function(e,t){return fy(hy(e),t)}});var Dn=m((VL,Yl)=>{"use strict";var my=ce(),by=0,gy=Math.random(),Sy=my(1 .toString);Yl.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Sy(++by+gy,36)}});var te=m((_L,zl)=>{"use strict";var vy=Y(),yy=Cn(),Ql=Ve(),Ty=Dn(),Iy=wn(),Ey=kn(),sr=vy.Symbol,Bn=yy("wks"),xy=Ey?sr.for||sr:sr&&sr.withoutSetter||Ty;zl.exports=function(a){return Ql(Bn,a)||(Bn[a]=Iy&&Ql(sr,a)?sr[a]:xy("Symbol."+a)),Bn[a]}});var Zl=m((NL,Xl)=>{"use strict";var Py=ye(),Kl=Pe(),Jl=Rn(),Ay=Gr(),wy=Bl(),ky=te(),Ry=TypeError,$y=ky("toPrimitive");Xl.exports=function(a,e){if(!Kl(a)||Jl(a))return a;var t=Ay(a,$y),r;if(t){if(e===void 0&&(e="default"),r=Py(t,a,e),!Kl(r)||Jl(r))return r;throw new Ry("Can't convert object to primitive value")}return e===void 0&&(e="number"),wy(a,e)}});var On=m((FL,ed)=>{"use strict";var Ly=Zl(),My=Rn();ed.exports=function(a){var e=Ly(a,"string");return My(e)?e:e+""}});var Lt=m(rd=>{"use strict";var Cy=Ae(),Dy=Tn(),By=In(),wa=He(),td=On(),Oy=TypeError,Vn=Object.defineProperty,Vy=Object.getOwnPropertyDescriptor,_n="enumerable",Nn="configurable",Fn="writable";rd.f=Cy?By?function(e,t,r){if(wa(e),t=td(t),wa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Fn in r&&!r[Fn]){var i=Vy(e,t);i&&i[Fn]&&(e[t]=r.value,r={configurable:Nn in r?r[Nn]:i[Nn],enumerable:_n in r?r[_n]:i[_n],writable:!1})}return Vn(e,t,r)}:Vn:function(e,t,r){if(wa(e),t=td(t),wa(r),Dy)try{return Vn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Oy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Qr=m((UL,id)=>{"use strict";id.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var nr=m((HL,ad)=>{"use strict";var _y=Ae(),Ny=Lt(),Fy=Qr();ad.exports=_y?function(a,e,t){return Ny.f(a,e,Fy(1,t))}:function(a,e,t){return a[e]=t,a}});var ka=m((jL,nd)=>{"use strict";var qy=Cn(),Uy=Dn(),sd=qy("keys");nd.exports=function(a){return sd[a]||(sd[a]=Uy(a))}});var Ra=m((GL,od)=>{"use strict";od.exports={}});var jn=m((WL,ld)=>{"use strict";var Hy=sl(),cd=Y(),jy=Pe(),Gy=nr(),qn=Ve(),Un=Wr(),Wy=ka(),Yy=Ra(),ud="Object already initialized",Hn=cd.TypeError,Qy=cd.WeakMap,$a,zr,La,zy=function(a){return La(a)?zr(a):$a(a,{})},Ky=function(a){return function(e){var t;if(!jy(e)||(t=zr(e)).type!==a)throw new Hn("Incompatible receiver, "+a+" required");return t}};Hy||Un.state?(_e=Un.state||(Un.state=new Qy),_e.get=_e.get,_e.has=_e.has,_e.set=_e.set,$a=function(a,e){if(_e.has(a))throw new Hn(ud);return e.facade=a,_e.set(a,e),e},zr=function(a){return _e.get(a)||{}},La=function(a){return _e.has(a)}):(Mt=Wy("state"),Yy[Mt]=!0,$a=function(a,e){if(qn(a,Mt))throw new Hn(ud);return e.facade=a,Gy(a,Mt,e),e},zr=function(a){return qn(a,Mt)?a[Mt]:{}},La=function(a){return qn(a,Mt)});var _e,Mt;ld.exports={set:$a,get:zr,has:La,enforce:zy,getterFor:Ky}});var Gn=m((YL,fd)=>{"use strict";var Jy=Fr(),hd=Function.prototype,dd=hd.apply,pd=hd.call;fd.exports=typeof Reflect=="object"&&Reflect.apply||(Jy?pd.bind(dd):function(){return pd.apply(dd,arguments)})});var Wn=m((QL,md)=>{"use strict";var Xy=tr(),Zy=ce();md.exports=function(a){if(Xy(a)==="Function")return Zy(a)}});var vd=m(Sd=>{"use strict";var bd={}.propertyIsEnumerable,gd=Object.getOwnPropertyDescriptor,eT=gd&&!bd.call({1:2},1);Sd.f=eT?function(e){var t=gd(this,e);return!!t&&t.enumerable}:bd});var Id=m(Td=>{"use strict";var tT=Ae(),rT=ye(),iT=vd(),aT=Qr(),sT=ir(),nT=On(),oT=Ve(),uT=Tn(),yd=Object.getOwnPropertyDescriptor;Td.f=tT?yd:function(e,t){if(e=sT(e),t=nT(t),uT)try{return yd(e,t)}catch(r){}if(oT(e,t))return aT(!rT(iT.f,e,t),e[t])}});var Yn=m((JL,Ed)=>{"use strict";var cT=ve(),lT=W(),dT=/#|\.prototype\./,Kr=function(a,e){var t=hT[pT(a)];return t===mT?!0:t===fT?!1:lT(e)?cT(e):!!e},pT=Kr.normalize=function(a){return String(a).replace(dT,".").toLowerCase()},hT=Kr.data={},fT=Kr.NATIVE="N",mT=Kr.POLYFILL="P";Ed.exports=Kr});var Jr=m((XL,Pd)=>{"use strict";var xd=Wn(),bT=Qe(),gT=Fr(),ST=xd(xd.bind);Pd.exports=function(a,e){return bT(a),e===void 0?a:gT?ST(a,e):function(){return a.apply(e,arguments)}}});var we=m((ZL,wd)=>{"use strict";var Xr=Y(),vT=Gn(),yT=Wn(),TT=W(),IT=Id().f,ET=Yn(),or=Pa(),xT=Jr(),ur=nr(),Ad=Ve();Wr();var PT=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 vT(a,this,arguments)};return e.prototype=a.prototype,e};wd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Xr:i?Xr[t]:Xr[t]&&Xr[t].prototype,o=r?or:or[t]||ur(or,t,{})[t],u=o.prototype,c,l,d,p,h,f,b,g,y;for(p in e)c=ET(r?p:t+(i?".":"#")+p,a.forced),l=!c&&n&&Ad(n,p),f=o[p],l&&(a.dontCallGetSet?(y=IT(n,p),b=y&&y.value):b=n[p]),h=l&&b?b:e[p],!(!c&&!s&&typeof f==typeof h)&&(a.bind&&l?g=xT(h,Xr):a.wrap&&l?g=PT(h):s&&TT(h)?g=yT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&ur(g,"sham",!0),ur(o,p,g),s&&(d=t+"Prototype",Ad(or,d)||ur(or,d,{}),ur(or[d],p,h),a.real&&u&&(c||!u[p])&&ur(u,p,h)))}});var $d=m((eM,Rd)=>{"use strict";var Qn=Ae(),AT=Ve(),kd=Function.prototype,wT=Qn&&Object.getOwnPropertyDescriptor,zn=AT(kd,"name"),kT=zn&&function(){}.name==="something",RT=zn&&(!Qn||Qn&&wT(kd,"name").configurable);Rd.exports={EXISTS:zn,PROPER:kT,CONFIGURABLE:RT}});var Md=m((tM,Ld)=>{"use strict";var $T=Math.ceil,LT=Math.floor;Ld.exports=Math.trunc||function(e){var t=+e;return(t>0?LT:$T)(t)}});var Ma=m((rM,Cd)=>{"use strict";var MT=Md();Cd.exports=function(a){var e=+a;return e!==e||e===0?0:MT(e)}});var Bd=m((iM,Dd)=>{"use strict";var CT=Ma(),DT=Math.max,BT=Math.min;Dd.exports=function(a,e){var t=CT(a);return t<0?DT(t+e,0):BT(t,e)}});var Vd=m((aM,Od)=>{"use strict";var OT=Ma(),VT=Math.min;Od.exports=function(a){var e=OT(a);return e>0?VT(e,9007199254740991):0}});var Ca=m((sM,_d)=>{"use strict";var _T=Vd();_d.exports=function(a){return _T(a.length)}});var qd=m((nM,Fd)=>{"use strict";var NT=ir(),FT=Bd(),qT=Ca(),Nd=function(a){return function(e,t,r){var i=NT(e),s=qT(i);if(s===0)return!a&&-1;var n=FT(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}};Fd.exports={includes:Nd(!0),indexOf:Nd(!1)}});var jd=m((oM,Hd)=>{"use strict";var UT=ce(),Kn=Ve(),HT=ir(),jT=qd().indexOf,GT=Ra(),Ud=UT([].push);Hd.exports=function(a,e){var t=HT(a),r=0,i=[],s;for(s in t)!Kn(GT,s)&&Kn(t,s)&&Ud(i,s);for(;e.length>r;)Kn(t,s=e[r++])&&(~jT(i,s)||Ud(i,s));return i}});var Jn=m((uM,Gd)=>{"use strict";Gd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Yd=m((cM,Wd)=>{"use strict";var WT=jd(),YT=Jn();Wd.exports=Object.keys||function(e){return WT(e,YT)}});var zd=m(Qd=>{"use strict";var QT=Ae(),zT=In(),KT=Lt(),JT=He(),XT=ir(),ZT=Yd();Qd.f=QT&&!zT?Object.defineProperties:function(e,t){JT(e);for(var r=XT(t),i=ZT(t),s=i.length,n=0,o;s>n;)KT.f(e,o=i[n++],r[o]);return e}});var Xn=m((dM,Kd)=>{"use strict";var eI=Ye();Kd.exports=eI("document","documentElement")});var ro=m((pM,ip)=>{"use strict";var tI=He(),rI=zd(),Jd=Jn(),iI=Ra(),aI=Xn(),sI=Ea(),nI=ka(),Xd=">",Zd="<",eo="prototype",to="script",tp=nI("IE_PROTO"),Zn=function(){},rp=function(a){return Zd+to+Xd+a+Zd+"/"+to+Xd},ep=function(a){a.write(rp("")),a.close();var e=a.parentWindow.Object;return a=null,e},oI=function(){var a=sI("iframe"),e="java"+to+":",t;return a.style.display="none",aI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(rp("document.F=Object")),t.close(),t.F},Da,Ba=function(){try{Da=new ActiveXObject("htmlfile")}catch(e){}Ba=typeof document!="undefined"?document.domain&&Da?ep(Da):oI():ep(Da);for(var a=Jd.length;a--;)delete Ba[eo][Jd[a]];return Ba()};iI[tp]=!0;ip.exports=Object.create||function(e,t){var r;return e!==null?(Zn[eo]=tI(e),r=new Zn,Zn[eo]=null,r[tp]=e):r=Ba(),t===void 0?r:rI.f(r,t)}});var sp=m((hM,ap)=>{"use strict";var uI=ve();ap.exports=!uI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ao=m((fM,op)=>{"use strict";var cI=Ve(),lI=W(),dI=Yr(),pI=ka(),hI=sp(),np=pI("IE_PROTO"),io=Object,fI=io.prototype;op.exports=hI?io.getPrototypeOf:function(a){var e=dI(a);if(cI(e,np))return e[np];var t=e.constructor;return lI(t)&&e instanceof t?t.prototype:e instanceof io?fI:null}});var cr=m((mM,up)=>{"use strict";var mI=nr();up.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:mI(a,e,t),a}});var uo=m((bM,dp)=>{"use strict";var bI=ve(),gI=W(),SI=Pe(),vI=ro(),cp=ao(),yI=cr(),TI=te(),II=Oe(),oo=TI("iterator"),lp=!1,ze,so,no;[].keys&&(no=[].keys(),"next"in no?(so=cp(cp(no)),so!==Object.prototype&&(ze=so)):lp=!0);var EI=!SI(ze)||bI(function(){var a={};return ze[oo].call(a)!==a});EI?ze={}:II&&(ze=vI(ze));gI(ze[oo])||yI(ze,oo,function(){return this});dp.exports={IteratorPrototype:ze,BUGGY_SAFARI_ITERATORS:lp}});var Oa=m((gM,hp)=>{"use strict";var xI=te(),PI=xI("toStringTag"),pp={};pp[PI]="z";hp.exports=String(pp)==="[object z]"});var Zr=m((SM,fp)=>{"use strict";var AI=Oa(),wI=W(),Va=tr(),kI=te(),RI=kI("toStringTag"),$I=Object,LI=Va(function(){return arguments}())==="Arguments",MI=function(a,e){try{return a[e]}catch(t){}};fp.exports=AI?Va:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=MI(e=$I(a),RI))=="string"?t:LI?Va(e):(r=Va(e))==="Object"&&wI(e.callee)?"Arguments":r}});var bp=m((vM,mp)=>{"use strict";var CI=Oa(),DI=Zr();mp.exports=CI?{}.toString:function(){return"[object "+DI(this)+"]"}});var ei=m((yM,Sp)=>{"use strict";var BI=Oa(),OI=Lt().f,VI=nr(),_I=Ve(),NI=bp(),FI=te(),gp=FI("toStringTag");Sp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(_I(i,gp)||OI(i,gp,{configurable:!0,value:e}),r&&!BI&&VI(i,"toString",NI))}});var yp=m((TM,vp)=>{"use strict";var qI=uo().IteratorPrototype,UI=ro(),HI=Qr(),jI=ei(),GI=$t(),WI=function(){return this};vp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=UI(qI,{next:HI(+!r,t)}),jI(a,i,!1,!0),GI[i]=WI,a}});var Ip=m((IM,Tp)=>{"use strict";var YI=ce(),QI=Qe();Tp.exports=function(a,e,t){try{return YI(QI(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var xp=m((EM,Ep)=>{"use strict";var zI=Pe();Ep.exports=function(a){return zI(a)||a===null}});var Ap=m((xM,Pp)=>{"use strict";var KI=xp(),JI=String,XI=TypeError;Pp.exports=function(a){if(KI(a))return a;throw new XI("Can't set "+JI(a)+" as a prototype")}});var co=m((PM,wp)=>{"use strict";var ZI=Ip(),eE=Pe(),tE=qr(),rE=Ap();wp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=ZI(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return tE(i),rE(s),eE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var _p=m((AM,Vp)=>{"use strict";var iE=we(),aE=ye(),_a=Oe(),Bp=$d(),sE=W(),nE=yp(),kp=ao(),Rp=co(),oE=ei(),uE=nr(),lo=cr(),cE=te(),$p=$t(),Op=uo(),lE=Bp.PROPER,dE=Bp.CONFIGURABLE,Lp=Op.IteratorPrototype,Na=Op.BUGGY_SAFARI_ITERATORS,ti=cE("iterator"),Mp="keys",ri="values",Cp="entries",Dp=function(){return this};Vp.exports=function(a,e,t,r,i,s,n){nE(t,e,r);var o=function(y){if(y===i&&p)return p;if(!Na&&y&&y in l)return l[y];switch(y){case Mp:return function(){return new t(this,y)};case ri:return function(){return new t(this,y)};case Cp:return function(){return new t(this,y)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[ti]||l["@@iterator"]||i&&l[i],p=!Na&&d||o(i),h=e==="Array"&&l.entries||d,f,b,g;if(h&&(f=kp(h.call(new a)),f!==Object.prototype&&f.next&&(!_a&&kp(f)!==Lp&&(Rp?Rp(f,Lp):sE(f[ti])||lo(f,ti,Dp)),oE(f,u,!0,!0),_a&&($p[u]=Dp))),lE&&i===ri&&d&&d.name!==ri&&(!_a&&dE?uE(l,"name",ri):(c=!0,p=function(){return aE(d,this)})),i)if(b={values:o(ri),keys:s?p:o(Mp),entries:o(Cp)},n)for(g in b)(Na||c||!(g in l))&&lo(l,g,b[g]);else iE({target:e,proto:!0,forced:Na||c},b);return(!_a||n)&&l[ti]!==p&&lo(l,ti,p,{name:i}),$p[e]=p,b}});var Fp=m((wM,Np)=>{"use strict";Np.exports=function(a,e){return{value:a,done:e}}});var ho=m((kM,Gp)=>{"use strict";var pE=ir(),po=gn(),qp=$t(),Hp=jn(),hE=Lt().f,fE=_p(),Fa=Fp(),mE=Oe(),bE=Ae(),jp="Array Iterator",gE=Hp.set,SE=Hp.getterFor(jp);Gp.exports=fE(Array,"Array",function(a,e){gE(this,{type:jp,target:pE(a),index:0,kind:e})},function(){var a=SE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Fa(void 0,!0);switch(a.kind){case"keys":return Fa(t,!1);case"values":return Fa(e[t],!1)}return Fa([t,e[t]],!1)},"values");var Up=qp.Arguments=qp.Array;po("keys");po("values");po("entries");if(!mE&&bE&&Up.name!=="values")try{hE(Up,"name",{value:"values"})}catch(a){}});var Yp=m((RM,Wp)=>{"use strict";var vE=te(),yE=$t(),TE=vE("iterator"),IE=Array.prototype;Wp.exports=function(a){return a!==void 0&&(yE.Array===a||IE[TE]===a)}});var fo=m(($M,zp)=>{"use strict";var EE=Zr(),Qp=Gr(),xE=rr(),PE=$t(),AE=te(),wE=AE("iterator");zp.exports=function(a){if(!xE(a))return Qp(a,wE)||Qp(a,"@@iterator")||PE[EE(a)]}});var Jp=m((LM,Kp)=>{"use strict";var kE=ye(),RE=Qe(),$E=He(),LE=jr(),ME=fo(),CE=TypeError;Kp.exports=function(a,e){var t=arguments.length<2?ME(a):e;if(RE(t))return $E(kE(t,a));throw new CE(LE(a)+" is not iterable")}});var eh=m((MM,Zp)=>{"use strict";var DE=ye(),Xp=He(),BE=Gr();Zp.exports=function(a,e,t){var r,i;Xp(a);try{if(r=BE(a,"return"),!r){if(e==="throw")throw t;return t}r=DE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Xp(r),t}});var Ua=m((CM,ah)=>{"use strict";var OE=Jr(),VE=ye(),_E=He(),NE=jr(),FE=Yp(),qE=Ca(),th=Hr(),UE=Jp(),HE=fo(),rh=eh(),jE=TypeError,qa=function(a,e){this.stopped=a,this.result=e},ih=qa.prototype;ah.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=OE(e,r),c,l,d,p,h,f,b,g=function(I){return c&&rh(c,"normal",I),new qa(!0,I)},y=function(I){return i?(_E(I),o?u(I[0],I[1],g):u(I[0],I[1])):o?u(I,g):u(I)};if(s)c=a.iterator;else if(n)c=a;else{if(l=HE(a),!l)throw new jE(NE(a)+" is not iterable");if(FE(l)){for(d=0,p=qE(a);p>d;d++)if(h=y(a[d]),h&&th(ih,h))return h;return new qa(!1)}c=UE(a,l)}for(f=s?a.next:c.next;!(b=VE(f,c)).done;){try{h=y(b.value)}catch(I){rh(c,"throw",I)}if(typeof h=="object"&&h&&th(ih,h))return h}return new qa(!1)}});var nh=m((DM,sh)=>{"use strict";var GE=Ae(),WE=Lt(),YE=Qr();sh.exports=function(a,e,t){GE?WE.f(a,e,YE(0,t)):a[e]=t}});var oh=m(()=>{"use strict";var QE=we(),zE=Ua(),KE=nh();QE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return zE(e,function(r,i){KE(t,r,i)},{AS_ENTRIES:!0}),t}})});var ch=m((VM,uh)=>{"use strict";ho();oh();var JE=Pa();uh.exports=JE.Object.fromEntries});var dh=m((_M,lh)=>{"use strict";lh.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 hh=m(()=>{"use strict";ho();var XE=dh(),ZE=Y(),ex=ei(),ph=$t();for(Ha in XE)ex(ZE[Ha],Ha),ph[Ha]=ph.Array;var Ha});var mh=m((qM,fh)=>{"use strict";var tx=ch();hh();fh.exports=tx});var mo=m((UM,bh)=>{"use strict";var rx=mh();bh.exports=rx});var gh=m(()=>{"use strict"});var bo=m((GM,Sh)=>{"use strict";var ii=Y(),ix=ar(),ax=tr(),ja=function(a){return ix.slice(0,a.length)===a};Sh.exports=function(){return ja("Bun/")?"BUN":ja("Cloudflare-Workers")?"CLOUDFLARE":ja("Deno/")?"DENO":ja("Node.js/")?"NODE":ii.Bun&&typeof Bun.version=="string"?"BUN":ii.Deno&&typeof Deno.version=="object"?"DENO":ax(ii.process)==="process"?"NODE":ii.window&&ii.document?"BROWSER":"REST"}()});var Ga=m((WM,vh)=>{"use strict";var sx=bo();vh.exports=sx==="NODE"});var Th=m((YM,yh)=>{"use strict";var nx=Lt();yh.exports=function(a,e,t){return nx.f(a,e,t)}});var xh=m((QM,Eh)=>{"use strict";var ox=Ye(),ux=Th(),cx=te(),lx=Ae(),Ih=cx("species");Eh.exports=function(a){var e=ox(a);lx&&e&&!e[Ih]&&ux(e,Ih,{configurable:!0,get:function(){return this}})}});var Ah=m((zM,Ph)=>{"use strict";var dx=Hr(),px=TypeError;Ph.exports=function(a,e){if(dx(e,a))return a;throw new px("Incorrect invocation")}});var So=m((KM,wh)=>{"use strict";var hx=ce(),fx=W(),go=Wr(),mx=hx(Function.toString);fx(go.inspectSource)||(go.inspectSource=function(a){return mx(a)});wh.exports=go.inspectSource});var Ch=m((JM,Mh)=>{"use strict";var bx=ce(),gx=ve(),kh=W(),Sx=Zr(),vx=Ye(),yx=So(),Rh=function(){},$h=vx("Reflect","construct"),vo=/^\s*(?:class|function)\b/,Tx=bx(vo.exec),Ix=!vo.test(Rh),ai=function(e){if(!kh(e))return!1;try{return $h(Rh,[],e),!0}catch(t){return!1}},Lh=function(e){if(!kh(e))return!1;switch(Sx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ix||!!Tx(vo,yx(e))}catch(t){return!0}};Lh.sham=!0;Mh.exports=!$h||gx(function(){var a;return ai(ai.call)||!ai(Object)||!ai(function(){a=!0})||a})?Lh:ai});var Bh=m((XM,Dh)=>{"use strict";var Ex=Ch(),xx=jr(),Px=TypeError;Dh.exports=function(a){if(Ex(a))return a;throw new Px(xx(a)+" is not a constructor")}});var yo=m((ZM,Vh)=>{"use strict";var Oh=He(),Ax=Bh(),wx=rr(),kx=te(),Rx=kx("species");Vh.exports=function(a,e){var t=Oh(a).constructor,r;return t===void 0||wx(r=Oh(t)[Rx])?e:Ax(r)}});var Nh=m((eC,_h)=>{"use strict";var $x=ce();_h.exports=$x([].slice)});var qh=m((tC,Fh)=>{"use strict";var Lx=TypeError;Fh.exports=function(a,e){if(a<e)throw new Lx("Not enough arguments");return a}});var To=m((rC,Uh)=>{"use strict";var Mx=ar();Uh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Mx)});var $o=m((iC,Jh)=>{"use strict";var Te=Y(),Cx=Gn(),Dx=Jr(),Hh=W(),Bx=Ve(),Kh=ve(),jh=Xn(),Ox=Nh(),Gh=Ea(),Vx=qh(),_x=To(),Nx=Ga(),wo=Te.setImmediate,ko=Te.clearImmediate,Fx=Te.process,Io=Te.Dispatch,qx=Te.Function,Wh=Te.MessageChannel,Ux=Te.String,Eo=0,si={},Yh="onreadystatechange",ni,Ct,xo,Po;Kh(function(){ni=Te.location});var Ro=function(a){if(Bx(si,a)){var e=si[a];delete si[a],e()}},Ao=function(a){return function(){Ro(a)}},Qh=function(a){Ro(a.data)},zh=function(a){Te.postMessage(Ux(a),ni.protocol+"//"+ni.host)};(!wo||!ko)&&(wo=function(e){Vx(arguments.length,1);var t=Hh(e)?e:qx(e),r=Ox(arguments,1);return si[++Eo]=function(){Cx(t,void 0,r)},Ct(Eo),Eo},ko=function(e){delete si[e]},Nx?Ct=function(a){Fx.nextTick(Ao(a))}:Io&&Io.now?Ct=function(a){Io.now(Ao(a))}:Wh&&!_x?(xo=new Wh,Po=xo.port2,xo.port1.onmessage=Qh,Ct=Dx(Po.postMessage,Po)):Te.addEventListener&&Hh(Te.postMessage)&&!Te.importScripts&&ni&&ni.protocol!=="file:"&&!Kh(zh)?(Ct=zh,Te.addEventListener("message",Qh,!1)):Yh in Gh("script")?Ct=function(a){jh.appendChild(Gh("script"))[Yh]=function(){jh.removeChild(this),Ro(a)}}:Ct=function(a){setTimeout(Ao(a),0)});Jh.exports={set:wo,clear:ko}});var ef=m((aC,Zh)=>{"use strict";var Xh=Y(),Hx=Ae(),jx=Object.getOwnPropertyDescriptor;Zh.exports=function(a){if(!Hx)return Xh[a];var e=jx(Xh,a);return e&&e.value}});var Lo=m((sC,rf)=>{"use strict";var tf=function(){this.head=null,this.tail=null};tf.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}}};rf.exports=tf});var sf=m((nC,af)=>{"use strict";var Gx=ar();af.exports=/ipad|iphone|ipod/i.test(Gx)&&typeof Pebble!="undefined"});var of=m((oC,nf)=>{"use strict";var Wx=ar();nf.exports=/web0s(?!.*chrome)/i.test(Wx)});var ff=m((uC,hf)=>{"use strict";var dr=Y(),Yx=ef(),uf=Jr(),Mo=$o().set,Qx=Lo(),zx=To(),Kx=sf(),Jx=of(),Co=Ga(),cf=dr.MutationObserver||dr.WebKitMutationObserver,lf=dr.document,df=dr.process,Wa=dr.Promise,Oo=Yx("queueMicrotask"),lr,Do,Bo,Ya,pf;Oo||(oi=new Qx,ui=function(){var a,e;for(Co&&(a=df.domain)&&a.exit();e=oi.get();)try{e()}catch(t){throw oi.head&&lr(),t}a&&a.enter()},!zx&&!Co&&!Jx&&cf&&lf?(Do=!0,Bo=lf.createTextNode(""),new cf(ui).observe(Bo,{characterData:!0}),lr=function(){Bo.data=Do=!Do}):!Kx&&Wa&&Wa.resolve?(Ya=Wa.resolve(void 0),Ya.constructor=Wa,pf=uf(Ya.then,Ya),lr=function(){pf(ui)}):Co?lr=function(){df.nextTick(ui)}:(Mo=uf(Mo,dr),lr=function(){Mo(ui)}),Oo=function(a){oi.head||lr(),oi.add(a)});var oi,ui;hf.exports=Oo});var bf=m((cC,mf)=>{"use strict";mf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Qa=m((lC,gf)=>{"use strict";gf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Dt=m((dC,Sf)=>{"use strict";var Xx=Y();Sf.exports=Xx.Promise});var pr=m((pC,If)=>{"use strict";var Zx=Y(),ci=Dt(),eP=W(),tP=Yn(),rP=So(),iP=te(),vf=bo(),aP=Oe(),Vo=An(),yf=ci&&ci.prototype,sP=iP("species"),_o=!1,Tf=eP(Zx.PromiseRejectionEvent),nP=tP("Promise",function(){var a=rP(ci),e=a!==String(ci);if(!e&&Vo===66||aP&&!(yf.catch&&yf.finally))return!0;if(!Vo||Vo<51||!/native code/.test(a)){var t=new ci(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[sP]=r,_o=t.then(function(){})instanceof r,!_o)return!0}return!e&&(vf==="BROWSER"||vf==="DENO")&&!Tf});If.exports={CONSTRUCTOR:nP,REJECTION_EVENT:Tf,SUBCLASSING:_o}});var hr=m((hC,xf)=>{"use strict";var Ef=Qe(),oP=TypeError,uP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new oP("Bad Promise constructor");e=r,t=i}),this.resolve=Ef(e),this.reject=Ef(t)};xf.exports.f=function(a){return new uP(a)}});var Hf=m(()=>{"use strict";var cP=we(),lP=Oe(),Xa=Ga(),dt=Y(),gr=ye(),Pf=cr(),Af=co(),dP=ei(),pP=xh(),hP=Qe(),Ja=W(),fP=Pe(),mP=Ah(),bP=yo(),Lf=$o().set,Ho=ff(),gP=bf(),SP=Qa(),vP=Lo(),Mf=jn(),Za=Dt(),jo=pr(),Cf=hr(),es="Promise",Df=jo.CONSTRUCTOR,yP=jo.REJECTION_EVENT,TP=jo.SUBCLASSING,No=Mf.getterFor(es),IP=Mf.set,fr=Za&&Za.prototype,Bt=Za,za=fr,Bf=dt.TypeError,Fo=dt.document,Go=dt.process,qo=Cf.f,EP=qo,xP=!!(Fo&&Fo.createEvent&&dt.dispatchEvent),Of="unhandledrejection",PP="rejectionhandled",wf=0,Vf=1,AP=2,Wo=1,_f=2,Ka,kf,wP,Rf,Nf=function(a){var e;return fP(a)&&Ja(e=a.then)?e:!1},Ff=function(a,e){var t=e.value,r=e.state===Vf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{i?(r||(e.rejection===_f&&RP(e),e.rejection=Wo),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),l=!0)),u===a.promise?n(new Bf("Promise-chain cycle")):(c=Nf(u))?gr(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},qf=function(a,e){a.notified||(a.notified=!0,Ho(function(){for(var t=a.reactions,r;r=t.get();)Ff(r,a);a.notified=!1,e&&!a.rejection&&kP(a)}))},Uf=function(a,e,t){var r,i;xP?(r=Fo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),dt.dispatchEvent(r)):r={promise:e,reason:t},!yP&&(i=dt["on"+a])?i(r):a===Of&&gP("Unhandled promise rejection",t)},kP=function(a){gr(Lf,dt,function(){var e=a.facade,t=a.value,r=$f(a),i;if(r&&(i=SP(function(){Xa?Go.emit("unhandledRejection",t,e):Uf(Of,e,t)}),a.rejection=Xa||$f(a)?_f:Wo,i.error))throw i.value})},$f=function(a){return a.rejection!==Wo&&!a.parent},RP=function(a){gr(Lf,dt,function(){var e=a.facade;Xa?Go.emit("rejectionHandled",e):Uf(PP,e,a.value)})},mr=function(a,e,t){return function(r){a(e,r,t)}},br=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=AP,qf(a,!0))},Uo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Bf("Promise can't be resolved itself");var r=Nf(e);r?Ho(function(){var i={done:!1};try{gr(r,e,mr(Uo,i,a),mr(br,i,a))}catch(s){br(i,s,a)}}):(a.value=e,a.state=Vf,qf(a,!1))}catch(i){br({done:!1},i,a)}}};if(Df&&(Bt=function(e){mP(this,za),hP(e),gr(Ka,this);var t=No(this);try{e(mr(Uo,t),mr(br,t))}catch(r){br(t,r)}},za=Bt.prototype,Ka=function(e){IP(this,{type:es,done:!1,notified:!1,parent:!1,reactions:new vP,rejection:!1,state:wf,value:void 0})},Ka.prototype=Pf(za,"then",function(e,t){var r=No(this),i=qo(bP(this,Bt));return r.parent=!0,i.ok=Ja(e)?e:!0,i.fail=Ja(t)&&t,i.domain=Xa?Go.domain:void 0,r.state===wf?r.reactions.add(i):Ho(function(){Ff(i,r)}),i.promise}),kf=function(){var a=new Ka,e=No(a);this.promise=a,this.resolve=mr(Uo,e),this.reject=mr(br,e)},Cf.f=qo=function(a){return a===Bt||a===wP?new kf(a):EP(a)},!lP&&Ja(Za)&&fr!==Object.prototype)){Rf=fr.then,TP||Pf(fr,"then",function(e,t){var r=this;return new Bt(function(i,s){gr(Rf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete fr.constructor}catch(a){}Af&&Af(fr,za)}cP({global:!0,constructor:!0,wrap:!0,forced:Df},{Promise:Bt});dP(Bt,es,!1,!0);pP(es)});var Qf=m((bC,Yf)=>{"use strict";var $P=te(),Gf=$P("iterator"),Wf=!1;try{jf=0,Yo={next:function(){return{done:!!jf++}},return:function(){Wf=!0}},Yo[Gf]=function(){return this},Array.from(Yo,function(){throw 2})}catch(a){}var jf,Yo;Yf.exports=function(a,e){try{if(!e&&!Wf)return!1}catch(i){return!1}var t=!1;try{var r={};r[Gf]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Qo=m((gC,zf)=>{"use strict";var LP=Dt(),MP=Qf(),CP=pr().CONSTRUCTOR;zf.exports=CP||!MP(function(a){LP.all(a).then(void 0,function(){})})});var Kf=m(()=>{"use strict";var DP=we(),BP=ye(),OP=Qe(),VP=hr(),_P=Qa(),NP=Ua(),FP=Qo();DP({target:"Promise",stat:!0,forced:FP},{all:function(e){var t=this,r=VP.f(t),i=r.resolve,s=r.reject,n=_P(function(){var o=OP(t.resolve),u=[],c=0,l=1;NP(e,function(d){var p=c++,h=!1;l++,BP(o,t,d).then(function(f){h||(h=!0,u[p]=f,--l||i(u))},s)}),--l||i(u)});return n.error&&s(n.value),r.promise}})});var Xf=m(()=>{"use strict";var qP=we(),UP=Oe(),HP=pr().CONSTRUCTOR,Ko=Dt(),jP=Ye(),GP=W(),WP=cr(),Jf=Ko&&Ko.prototype;qP({target:"Promise",proto:!0,forced:HP,real:!0},{catch:function(a){return this.then(void 0,a)}});!UP&&GP(Ko)&&(zo=jP("Promise").prototype.catch,Jf.catch!==zo&&WP(Jf,"catch",zo,{unsafe:!0}));var zo});var Zf=m(()=>{"use strict";var YP=we(),QP=ye(),zP=Qe(),KP=hr(),JP=Qa(),XP=Ua(),ZP=Qo();YP({target:"Promise",stat:!0,forced:ZP},{race:function(e){var t=this,r=KP.f(t),i=r.reject,s=JP(function(){var n=zP(t.resolve);XP(e,function(o){QP(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var em=m(()=>{"use strict";var eA=we(),tA=hr(),rA=pr().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 Jo=m((AC,tm)=>{"use strict";var iA=He(),aA=Pe(),sA=hr();tm.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 am=m(()=>{"use strict";var nA=we(),oA=Ye(),rm=Oe(),uA=Dt(),im=pr().CONSTRUCTOR,cA=Jo(),lA=oA("Promise"),dA=rm&&!im;nA({target:"Promise",stat:!0,forced:rm||im},{resolve:function(e){return cA(dA&&this===lA?uA:this,e)}})});var sm=m(()=>{"use strict";Hf();Kf();Xf();Zf();em();am()});var cm=m(()=>{"use strict";var pA=we(),hA=Oe(),ts=Dt(),fA=ve(),om=Ye(),um=W(),mA=yo(),nm=Jo(),bA=cr(),Zo=ts&&ts.prototype,gA=!!ts&&fA(function(){Zo.finally.call({then:function(){}},function(){})});pA({target:"Promise",proto:!0,real:!0,forced:gA},{finally:function(a){var e=mA(this,om("Promise")),t=um(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)}});!hA&&um(ts)&&(Xo=om("Promise").prototype.finally,Zo.finally!==Xo&&bA(Zo,"finally",Xo,{unsafe:!0}));var Xo});var rs=m((CC,lm)=>{"use strict";var SA=Ye();lm.exports=SA});var pm=m((DC,dm)=>{"use strict";gh();sm();cm();var vA=rs();dm.exports=vA("Promise","finally")});var fm=m((BC,hm)=>{"use strict";var yA=pm();hm.exports=yA});var is=m((OC,mm)=>{"use strict";var TA=fm();mm.exports=TA});var Fm=m(()=>{"use strict";var KA=we(),JA=Yr(),XA=Ca(),ZA=Ma(),ew=gn();KA({target:"Array",proto:!0},{at:function(e){var t=JA(this),r=XA(t),i=ZA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});ew("at")});var Um=m((GD,qm)=>{"use strict";Fm();var tw=rs();qm.exports=tw("Array","at")});var jm=m((WD,Hm)=>{"use strict";var rw=Um();Hm.exports=rw});var hi=m((YD,Gm)=>{"use strict";var iw=jm();Gm.exports=iw});var Kb=m(()=>{"use strict"});var Jb=m(()=>{"use strict"});var Zb=m((YV,Xb)=>{"use strict";var ck=Pe(),lk=tr(),dk=te(),pk=dk("match");Xb.exports=function(a){var e;return ck(a)&&((e=a[pk])!==void 0?!!e:lk(a)==="RegExp")}});var tg=m((QV,eg)=>{"use strict";var hk=Zr(),fk=String;eg.exports=function(a){if(hk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return fk(a)}});var ig=m((zV,rg)=>{"use strict";var mk=He();rg.exports=function(){var a=mk(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 ng=m((KV,sg)=>{"use strict";var bk=ye(),gk=Ve(),Sk=Hr(),vk=ig(),ag=RegExp.prototype;sg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in ag)&&!gk(a,"flags")&&Sk(ag,a)?bk(vk,a):e}});var ug=m((JV,og)=>{"use strict";var Ru=ce(),yk=Yr(),Tk=Math.floor,wu=Ru("".charAt),Ik=Ru("".replace),ku=Ru("".slice),Ek=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,xk=/\$([$&'`]|\d{1,2})/g;og.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=xk;return i!==void 0&&(i=yk(i),u=Ek),Ik(s,u,function(c,l){var d;switch(wu(l,0)){case"$":return"$";case"&":return a;case"`":return ku(e,0,t);case"'":return ku(e,n);case"<":d=i[ku(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=Tk(p/10);return h===0?c:h<=o?r[h-1]===void 0?wu(l,1):r[h-1]+wu(l,1):c}d=r[p-1]}return d===void 0?"":d})}});var dg=m(()=>{"use strict";var Pk=we(),Ak=ye(),Lu=ce(),cg=qr(),wk=W(),kk=rr(),Rk=Zb(),wr=tg(),$k=Gr(),Lk=ng(),Mk=ug(),Ck=te(),Dk=Oe(),Bk=Ck("replace"),Ok=TypeError,$u=Lu("".indexOf),Vk=Lu("".replace),lg=Lu("".slice),_k=Math.max;Pk({target:"String",proto:!0},{replaceAll:function(e,t){var r=cg(this),i,s,n,o,u,c,l,d,p,h,f=0,b="";if(!kk(e)){if(i=Rk(e),i&&(s=wr(cg(Lk(e))),!~$u(s,"g")))throw new Ok("`.replaceAll` does not allow non-global regexes");if(n=$k(e,Bk),n)return Ak(n,e,r,t);if(Dk&&i)return Vk(wr(r),e,t)}for(o=wr(r),u=wr(e),c=wk(t),c||(t=wr(t)),l=u.length,d=_k(1,l),p=$u(o,u);p!==-1;)h=c?wr(t(u,p,o)):Mk(u,o,p,[],void 0,t),b+=lg(o,f,p)+h,f=p+l,p=p+d>o.length?-1:$u(o,u,p+d);return f<o.length&&(b+=lg(o,f)),b}})});var hg=m((e_,pg)=>{"use strict";Kb();Jb();dg();var Nk=rs();pg.exports=Nk("String","replaceAll")});var mg=m((t_,fg)=>{"use strict";var Fk=hg();fg.exports=Fk});var gg=m((r_,bg)=>{"use strict";var qk=mg();bg.exports=qk});var Dc="2.0.108-dev.f2d9491a.0";var ue=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ue||{}),lt=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(lt||{});var ya=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ya||{}),dn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(dn||{});var pn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(pn||{});import{assertNever as Fc,assertNonNullable as ov,isNonNullable as Ta,ValueSubject as hn,Subject as uv,Subscription as cv,merge as lv,observableFrom as dv,fromEvent as Oc,map as Vc,tap as _c,filterChanged as pv,isNullable as fn,ErrorCategory as Nc}from"@vkontakte/videoplayer-shared";var Bc=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Ia=class{constructor(e){this.connection$=new hn(void 0);this.castState$=new hn("NOT_AVAILABLE");this.errorEvent$=new uv;this.realCastState$=new hn("NOT_AVAILABLE");this.subscription=new cv;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=Ta((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Bc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Nc.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(){Ta(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();fn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();fn(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Oc(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 Fc(i.sessionState)}})).add(lv(Oc(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(_c(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Vc(i=>i.castState)),dv([r.getCastState()])).pipe(pv(),Vc(hv),_c(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Ta(this.connection$.getValue());if(s&&!n){let c=r.getCurrentSession();ov(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(fn(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?Ta(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:Nc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},hv=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 Fc(a)}};var mS=Ue(mo(),1);var Pm=Ue(is(),1);import{assertNever as bm}from"@vkontakte/videoplayer-shared";var ee=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:bm(t)}return a},eu=(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:bm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as IA,Subject as as,merge as gm}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new as;this.transitionEnded$=new as;this.transitionUpdated$=new as;this.forceChanged$=new as;this.stateChangeStarted$=gm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=gm(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||IA(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}};import{assertNever as EA}from"@vkontakte/videoplayer-shared";var Sm=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 EA(a)}};import{assertNever as Sr,assertNonNullable as Ot,debounce as vm,ErrorCategory as ym,fromEvent as Vt,isNonNullable as Tm,map as Im,merge as Em,observableFrom as xA,Subject as PA,Subscription as tu,timeout as AA,getHighestQuality as wA}from"@vkontakte/videoplayer-shared";var kA=5,RA=5,$A=500,xm=7e3,li=class{constructor(e){this.subscription=new tu;this.loadMediaTimeoutSubscription=new tu;this.videoState=new M("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:Sr(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:Sr(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:Sr(e)}break}default:Sr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Sm(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 tu;this.subscription.add(e),this.subscription.add(Em(this.videoState.stateChangeStarted$.pipe(Im(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Im(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 PA;e.add(i.pipe(vm($A)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Vt(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)>kA)&&i.next(o),s=o})),e.add(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Vt(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<RA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(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:Sr(n)}}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Em(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xA(["init"])).pipe(vm(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"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(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"),E(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"),E(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"&&E(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 c;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let l=t[e];Ot(l);let d=wA(Object.keys(l));Ot(d);let p=l[d];Ot(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Ot(l),r=l.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 l=t[e];Ot(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Ot(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Ot(l),r=ee(l.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:ym.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Sr(e)}let n=new chrome.cast.media.MediaInfo((c=this.params.meta.videoId)!=null?c:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Tm(o)&&(n.metadata.title=o),Tm(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(AA(xm).subscribe(()=>s(`timeout(${xm})`)))});(0,Pm.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:ym.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as wm}from"@vkontakte/videoplayer-shared";import{clearVideoElement as LA}from"@vkontakte/videoplayer-shared";var Am=a=>{try{a.pause(),a.playbackRate=0,LA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as MA,Subscription as CA}from"@vkontakte/videoplayer-shared";var ru=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)}},iu=window.WeakMap?new WeakMap:new ru,au=window.WeakMap?new WeakMap:new Map,DA=(a,e=20)=>{let t=0;return MA(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},le=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?wm(t):(t=document.createElement("video"),a.appendChild(t)),iu.set(t,r);let i=new CA;return i.add(DA(t,e)),au.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},de=a=>{let e=au.get(a);e==null||e.unsubscribe(),au.delete(a);let t=iu.get(a);iu.delete(a),t?wm(a):Am(a)};import{assertNonNullable as di,isNonNullable as Ge,isNullable as VA,fromEvent as vr,merge as km,observableFrom as Rm,filterChanged as $m,map as pi,Subject as Lm,Subscription as _A,ValueSubject as NA,ErrorCategory as FA}from"@vkontakte/videoplayer-shared";import{isNonNullable as su,isNullable as BA,Subscription as OA}from"@vkontakte/videoplayer-shared";var ss=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=BA(i),c=new OA;return i&&c.add(i.subscribe(l=>{let d=a.getState();r(l,d)&&a.setState(l)},s)),r(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(l=>{t(l.to),u&&a.setState(l.to)},s)),c},je=(a,e,t)=>ss(e,()=>a.loop,r=>{su(r)&&(a.loop=r)},{onError:t}),pe=(a,e,t,r)=>ss(e,()=>({muted:a.muted,volume:a.volume}),i=>{su(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}),ke=(a,e,t,r)=>ss(e,()=>a.playbackRate,i=>{su(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),pt=ss;var qA=a=>["__",a.language,a.label].join("|"),UA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},nu=class a{constructor(){this.available$=new Lm;this.current$=new NA(void 0);this.error$=new Lm;this.subscription=new _A;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:FA.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(pt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Ge(s)&&this.setInternal(s)},{equal:(s,n)=>Ge(s)&&Ge(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(pi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(pt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Ge(s)&&this.setExternal(s)},{equal:(s,n)=>Ge(s)&&Ge(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(pi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(pt(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(pt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){di(this.video);let{textTracks:e}=this.video;this.subscription.add(vr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(km(vr(e,"addtrack"),vr(e,"removetrack"),Rm(["init"])).pipe(pi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),$m((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(km(vr(e,"change"),Rm(["init"])).pipe(pi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),pi(r=>r&&this.htmlTextTrackToITextTrack(r).id),$m()).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(vr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var c,l,d,p,h;let u=(l=(c=o.target)==null?void 0:c.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(vr(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;Ge(t.align)&&(i.align=t.align),Ge(t.position)&&(i.position=t.position),Ge(t.size)&&(i.size=t.size),Ge(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){di(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,i=e.id?e.id:qA(e),s=this.externalTracks.has(i),n=i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(i))==null?void 0:o.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(i))==null?void 0:u.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){di(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(VA(e)||!UA(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){di(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){di(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)}},Re=nu;var Je=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 Mm=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},ou=a=>{let e=Mm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Cm=a=>{let e=Mm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as $e,map as ht,merge as Bm,filterChanged as jA,isNonNullable as Om,Subject as GA,filter as Vm,mapTo as _m,combine as WA,once as YA,ErrorCategory as QA,ValueSubject as Nm,clientChecker as zA}from"@vkontakte/videoplayer-shared";var HA=3,Dm=(a,e,t=HA)=>{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 he=a=>{let e=S=>$e(a,S).pipe(_m(void 0)),r=Bm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>$e(a,S))).pipe(ht(S=>S.type==="ended"?a.readyState<2:a.readyState<3),jA()),i=Bm($e(a,"progress"),$e(a,"timeupdate")).pipe(ht(()=>Dm(a.buffered,a.currentTime))),s=zA.isSafari?WA({play:e("play").pipe(YA()),playing:e("playing")}).pipe(_m(void 0)):e("playing"),n=$e(a,"volumechange").pipe(ht(()=>({muted:a.muted,volume:a.volume}))),o=$e(a,"ratechange").pipe(ht(()=>a.playbackRate)),u=$e(a,"error").pipe(Vm(()=>!!(a.error||a.played.length)),ht(()=>{var v;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:QA.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(v=a.error)!=null?v:void 0}})),c=$e(a,"timeupdate").pipe(ht(()=>a.currentTime)),l=new GA,d=.3,p;c.subscribe(S=>{a.loop&&Om(p)&&Om(S)&&p>=a.duration-d&&S<=d&&l.next(p),p=S});let h=e("pause").pipe(Vm(()=>!a.error&&p!==a.duration)),f=$e(a,"enterpictureinpicture"),b=$e(a,"leavepictureinpicture"),g=new Nm(Cm(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let y=new Nm(ou(a));return $e(a,"fullscreenchange").pipe(ht(()=>ou(a))).subscribe(y),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:$e(a,"durationchange").pipe(ht(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:y}};import{VideoQuality as ft}from"@vkontakte/videoplayer-shared";var mt=a=>{switch(a){case"mobile":return ft.Q_144P;case"lowest":return ft.Q_240P;case"low":return ft.Q_360P;case"sd":case"medium":return ft.Q_480P;case"hd":case"high":return ft.Q_720P;case"fullhd":case"full":return ft.Q_1080P;case"quadhd":case"quad":return ft.Q_1440P;case"ultrahd":case"ultra":return ft.Q_2160P}};var _t=Ue(hi(),1);import{isNonNullable as fe,isNullable as cu,now as Zm,isHigher as lu,isHigherOrEqual as zm,isInvariantQuality as Km,isLower as du,isLowerOrEqual as Jm,videoSizeToQuality as aw,assertNotEmptyArray as eb,assertNonNullable as sw}from"@vkontakte/videoplayer-shared";var uu=!1,Xe={},Wm=a=>{uu=a},Ym=()=>{Xe={}},Qm=a=>{a(Xe)},fi=(a,e)=>{var t;uu&&(Xe.meta=(t=Xe.meta)!=null?t:{},Xe.meta[a]=e)},re=class{constructor(e){this.name=e}next(e){var r,i;if(!uu)return;Xe.series=(r=Xe.series)!=null?r:{};let t=(i=Xe.series[this.name])!=null?i:[];t.push([Date.now(),e]),Xe.series[this.name]=t}};var nw=new re("best_bitrate"),tb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var pu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),mi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Zm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},rb='Assertion "ABR Tracks is empty array" failed',ns=(a,e,t,r)=>{var u;let i=[...e].sort(pu(1)),s=[...t].sort(pu(1)),n=s.filter(c=>fe(c.bitrate)&&fe(a.bitrate)?a.bitrate/c.bitrate>r:!0),o=(u=(0,_t.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,_t.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,_t.default)(n,-1):(0,_t.default)(s,0)},Xm=a=>"quality"in a,ib=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&Zm()-r.history[t.id]<=a.trackCooldown&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!i&&r.recordSelection(t),i&&(r!=null&&r.last)){let s=r.last;r==null||r.recordSwitch(s);let n=Xm(s)?"video":"audio",o=Xm(s)?s.quality:s.bitrate;return e({message:`
7
+ [last ${n} selected] ${o}
8
+ `}),s}return r==null||r.recordSwitch(t),t},bt=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:c,visible:l,droppedVideoMaxQualityLimit:d,abrLogger:p})=>{var N,O,w,L,q;eb(a,rb);let h=r.usePixelRatio&&(N=window.devicePixelRatio)!=null?N:1,f=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*r.containerSizeFactor,height:e.height*h*r.containerSizeFactor},b=f&&aw(f),g=r.considerPlaybackRate&&fe(o)?o:1,y=a.filter(k=>!Km(k.quality)).sort((k,x)=>lu(k.quality,x.quality)?-1:1),I=(O=(0,_t.default)(y,-1))==null?void 0:O.quality,S=(w=(0,_t.default)(y,0))==null?void 0:w.quality,v=cu(i)||fe(i.min)&&fe(i.max)&&du(i.max,i.min)||fe(i.min)&&S&&lu(i.min,S)||fe(i.max)&&I&&du(i.max,I),T=g*tb(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),R={},$=y.filter(k=>{if(!(b?du(k.quality,b):!0))return R[k.quality]="FitsContainer",!1;if(!(fe(t)&&isFinite(t)&&fe(k.bitrate)?t-s>=k.bitrate*T:!0))return R[k.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&fe(r.minBufferToSwitchUp)&&u&&!Km(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&lu(k.quality,u.quality))return R[k.quality]="Buffer",!1;if(!!d&&zm(k.quality,d))return R[k.quality]="DroppedFramesLimit",!1;let z=v||(cu(i.max)||Jm(k.quality,i.max))&&(cu(i.min)||zm(k.quality,i.min)),se=fe(l)&&!l?Jm(k.quality,r.backgroundVideoQualityLimit):!0;return!z||!se?(R[k.quality]="FitsQualityLimits",!1):!0})[0];$&&$.bitrate&&nw.next($.bitrate);let B=(L=$!=null?$:y[Math.ceil((y.length-1)/2)])!=null?L:a[0];return B.quality!==((q=c==null?void 0:c.last)==null?void 0:q.quality)&&p({message:`
9
+ [VIDEO TRACKS ABR]
10
+ [available video tracks]
8
11
  ${a.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
9
12
  `)}
10
13
 
@@ -13,28 +16,46 @@ var qS=Object.create;var kl=Object.defineProperty;var US=Object.getOwnPropertyDe
13
16
  `)}
14
17
 
15
18
  [limit params]
16
- containerQualityLimit: ${f},
19
+ containerQualityLimit: ${b},
17
20
  throughput: ${t},
18
21
  reserve: ${s},
19
22
  playbackRate: ${o},
20
- playbackRateFactor: ${b},
23
+ playbackRateFactor: ${g},
21
24
  forwardBufferHealth: ${n},
22
- bitrateFactor: ${v},
25
+ bitrateFactor: ${T},
23
26
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
24
- droppedVideoMaxQualityLimit: ${c},
25
- limitsAreInvalid: ${S},
27
+ droppedVideoMaxQualityLimit: ${d},
28
+ limitsAreInvalid: ${v},
26
29
  maxQualityLimit: ${i==null?void 0:i.max},
27
30
  minQualityLimit: ${i==null?void 0:i.min},
28
31
 
29
- [limited tracks]
30
- ${Object.entries(T).map(([k,x])=>`${k}: ${x}`).join(`
32
+ [limited video tracks]
33
+ ${Object.entries(R).map(([k,x])=>`${k}: ${x}`).join(`
31
34
  `)||"All tracks are available"}
32
35
 
33
- [best track] ${M==null?void 0:M.quality}
34
- [selected track] ${A==null?void 0:A.quality}
35
- `});let F=A&&l&&l.history[A.id]&&Wm()-l.history[A.id]<=r.trackCooldown&&(!l.last||A.id!==l.last.id);if(A!=null&&A.id&&l&&!F&&l.recordSelection(A),F&&(l!=null&&l.last)){let k=l.last;return l==null||l.recordSwitch(k),p({message:`
36
- [last selected] ${k==null?void 0:k.quality}
37
- `}),k}return l==null||l.recordSwitch(A),A},ft=KA;var X=a=>new URL(a).hostname;import{assertNever as Xm,assertNonNullable as Zm,combine as bw,debounce as gw,ErrorCategory as eb,filter as tb,filterChanged as Sw,isNonNullable as du,map as as,merge as rb,observableFrom as vw,once as yw,Subscription as Tw,ValueSubject as pu,videoQualityToHeight as Iw,videoSizeToQuality as Ew}from"@vkontakte/videoplayer-shared";var Ym=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},pe=async a=>{let e=a.muted;try{await a.play()}catch(t){if(!Ym(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(r){return Ym(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as ts,isNullable as ZA,assertNonNullable as pi}from"@vkontakte/videoplayer-shared";import{isNonNullable as Qm,assertNonNullable as es,now as JA}from"@vkontakte/videoplayer-shared";function Z(){return JA()}function ou(a){return Z()-a}function uu(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 zm(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function br(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,p,d=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;es(c);let w=ou(c),q;if(w<b){q=b-w,setTimeout(g,q);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,D()},y=w=>(s=w,L),I=w=>(p=w,L),S=()=>(h="json",L),v=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,p&&p(),t&&t()}},T=w=>(d=w,L),D=()=>{c=Z(),n=new i,n.open("get",a);let w=0,q,K=0,k=()=>(es(c),Math.max(c,Math.max(q||0,K||0)));if(s&&n.addEventListener("progress",x=>{let V=Z();s.updateChunk&&x.loaded>w&&(s.updateChunk(k(),x.loaded-w),w=x.loaded,q=V)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>v())),n.addEventListener("load",()=>{if(u)return;es(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let V=n.response.byteLength-w;V&&s.updateChunk&&s.updateChunk(k(),V)}n.responseType==="json"&&!Object.values(n.response).length?v():(p&&p(),e(n.response))}else v()}),n.addEventListener("error",()=>{v()}),d){let x=()=>{es(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=Z(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),L},L={withBitrateReporting:y,withParallel:T,withJSONResponse:S,withRetryCount:w=>(l=w,L),withRetryInterval:(w,q)=>(Qm(w)&&(b=w),Qm(q)&&(f=q),L),withTimeout:w=>(o=w,L),withFinally:I,send:D,abort:()=>{n&&(n.abort(),n=void 0),u=!0,p&&p()}};return L}var ci=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 di=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=Z(),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=Z()-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=br(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=Z()}_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=Z();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(){Object.values(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 rs=1e4,lu=3;var ew=6e4,tw=10,rw=1,iw=500,hi=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.chunkRateEstimator=new ci(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=uu(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=uu(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||ts(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=()=>{zm(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 di(lu,rs,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,p=()=>{let v=s&&(!c||c===this.rep);return v||t("Not running!"),v},d=(v,T,D)=>{u&&u.abort(),u=br(this.urlResolver.resolve(v,!1),T,D,()=>this._retryCallback()).withTimeout(rs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(lu).withFinally(()=>{u=null}).send()},h=(v,T,D)=>{pi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),T,D,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=v=>{let T=r.playbackRate;r.playbackRate!==v&&(t(`Playback rate switch: ${T}=>${v}`),r.playbackRate=v)},b=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let D=Z()-1e4,M=0;for(let F=0;F<this.bufferStates.length;F++){let R=this.bufferStates[F];v=Math.min(v,R.buf),R.ts<D&&M++}this.bufferStates.splice(0,M),t(`update playback rate; minBuffer=${v} drop=${M} jitter=${this.sourceJitter}`);let A=v-rw;this.sourceJitter>=0?A-=this.sourceJitter/2:this.sourceJitter-=1,A>3?f(1.15):A>1?f(1.1):A>.3?f(1.05):f(1)}},y=v=>{let T,D=()=>T&&T.start?T.start.length:0,M=x=>T.start[x]/1e3,A=x=>T.dur[x]/1e3,F=x=>T.fragIndex+x,R=(x,V)=>({chunkIdx:F(x),startTS:M(x),dur:A(x),discontinuity:V}),L=()=>{let x=0;if(T&&T.dur){let V=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,U=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,j=V;this.sourceJitter>1&&(j+=this.sourceJitter-1);let z=T.dur.length-1;for(;z>=0&&(j-=T.dur[z],!(j<=0));--z);x=Math.min(z,T.dur.length-1-U),x=Math.max(x,0)}return R(x,!0)},w=x=>{let V=D();if(!(V<=0)){if(ts(x)){for(let U=0;U<V;U++)if(M(U)>x)return R(U)}return L()}},q=x=>{let V=D(),U=x?x.chunkIdx+1:0,j=U-T.fragIndex;if(!(V<=0)){if(!x||j<0||j-V>tw)return t(`Resync: offset=${j} bChunks=${V} chunk=`+JSON.stringify(x)),L();if(!(j>=V))return R(U-T.fragIndex,!1)}},K=(x,V,U)=>{l&&l.abort(),l=br(this.urlResolver.resolve(x,!0,this.lowLatency),V,U,()=>this._retryCallback()).withTimeout(rs).withRetryCount(lu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(x,V)=>{K(v,U=>{if(!p())return;T=U;let j=!!T.lowLatency;j!==this.lowLatency&&b(j);let z=0;for(let _=0;_<T.dur.length;++_)z+=T.dur[_];z>0&&(pi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(z/T.dur.length)),i({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,x(w(V))},()=>this._handleNetworkError())},nextChunk:q}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),pi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:v=>{let{videoElement:T,logger:D}=this.params,M=y(e.jidxUrl),A,F,R,L,w=0,q,K,k,x=()=>{q&&(clearTimeout(q),q=void 0);let O=Math.max(iw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=w+O,me=Z(),Te=Math.min(1e4,ae-me);w=me;let at=()=>{l||p()&&M.seek(()=>{p()&&(w=Z(),V(),x())})};Te>0?q=window.setTimeout(()=>{this.paused?x():at()},Te):at()},V=()=>{let O;for(;O=M.nextChunk(L);)L=O,Gt(O);let ae=M.nextChunk(R);if(ae){if(R&&ae.discontinuity){D("Detected discontinuity; restarting playback"),this.paused?x():(I(),this._initPlayerWith(e));return}_(ae)}else x()},U=(O,ae)=>{if(!p()||!this.sourceBuffer)return;let me,Te,at,Wt=st=>{window.setTimeout(()=>{p()&&U(O,ae)},st)};if(this.sourceBuffer.updating)D("Source buffer is updating; delaying appendBuffer"),Wt(100);else{let st=Z(),vt=T.currentTime;!this.paused&&T.buffered.length>1&&K===vt&&st-k>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),K!==vt&&(K=vt,k=st);let Yt=this._getBufferSizeSec();if(Yt>30)D(`Buffered ${Yt} seconds; delaying appendBuffer`),Wt(2e3);else try{this.sourceBuffer.appendBuffer(O),this.videoPlayStarted?(this.bufferStates.push({ts:st,buf:Yt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ae&&ae()}catch(Lr){if(Lr.name==="QuotaExceededError")D("QuotaExceededError; delaying appendBuffer"),at=this.sourceBuffer.buffered.length,at!==0&&(me=this.sourceBuffer.buffered.start(0),Te=vt,Te-me>4&&this.sourceBuffer.remove(me,Te-3)),Wt(1e3);else throw Lr}}},j=()=>{F&&A&&(D([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(R)]),U(F,function(){F=null,V()}))},z=O=>e.fragUrlTemplate.replace("%%id%%",O.chunkIdx),_=O=>{p()&&h(z(O),(ae,me)=>{if(p()){if(me/=1e3,F=ae,R=O,n=O.startTS,me){let Te=Math.min(10,O.dur/me);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Te:Te}j()}},()=>this._handleNetworkError())},Gt=O=>{p()&&(pi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(z(O),!1)))},it=O=>{p()&&(e.cachedHeader=O,U(O,()=>{A=!0,j()}))};s=!0,M.seek(O=>{if(p()){if(w=Z(),!O){x();return}L=O,!ZA(v)||O.startTS>v?_(O):(R=O,V())}},v),e.cachedHeader?it(e.cachedHeader):d(e.headerUrl,it,()=>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(),ts(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,pi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return ts(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=p=>{if(!this.autoQuality)return;let d,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&p<this.bitrate&&(h=this._getBufferSizeSec(),f=p/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(p)}`);return}d=this._selectQuality(p),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${p}`)},s={updateChunk:(d,h)=>{let f=Z();if(this.chunkRateEstimator.addInterval(d,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-d,speed:g}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},n=-1/0,o,u=!0,l=()=>{let p=s.get();if(p&&o&&this.autoQuality){if(u&&p>o&&ou(n)<3e4)return;r(p)}u=this.autoQuality};return{updateChunk:(p,d)=>{let h=s.updateChunk(p,d);return h&&l(),h},notifySwitch:p=>{let d=Z();p<o&&(n=d),o=p}}}_fetchManifest(e,t,r){this.manifestRequest=br(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(rs).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;pe(e).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))},ew))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as aw,filter as Km,fromEvent as sw,interval as nw,isHigher as ow,isInvariantQuality as uw,isLower as lw,merge as cw,Subject as Jm,Subscription as dw}from"@vkontakte/videoplayer-shared";var cu=class{constructor(){this.onDroopedVideoFramesLimit$=new Jm;this.subscription=new dw;this.playing=!1;this.tracks=[];this.forceChecker$=new Jm;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&&!uw(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&&ow(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(sw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=nw(this.droppedFramesChecker.checkTime).pipe(Km(()=>this.playing),Km(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(aw(this.droppedFramesChecker.checkTime)),r=cw(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=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>lw(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}},is=cu;import{map as pw,Observable as hw}from"@vkontakte/videoplayer-shared";import{fromEvent as fw}from"@vkontakte/videoplayer-shared";var fi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var mw=(a,e)=>new hw(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||fi()))},{...r,...e});i.observe(a);let s=fw(document,"visibilitychange").pipe(pw(n=>!document.hidden||fi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),ke=mw;var xw=["paused","playing","ready"],Pw=["paused","playing","ready"],mi=class{constructor(e){this.subscription=new Tw;this.videoState=new $("stopped");this.representations$=new pu([]);this.textTracksManager=new Ae;this.droppedFramesManager=new is;this.maxSeekBackTime$=new pu(1/0);this.zeroTime$=new pu(void 0);this.liveOffset=new ze;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:eb.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=pt(u.name))!=null?r:Ew(u.video),p=u.bitrate/1e3,d={...u.video};if(!c)continue;let h={id:l,quality:c,bitrate:p,size:d};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),du(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(Pw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&xw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ee(this.params.source.url,u))}return;default:return Xm(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:eb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};rb(this.videoState.stateChangeStarted$.pipe(as(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(as(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),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(X(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.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=de(this.video);this.subscription.add(this.representations$.pipe(as(i=>i.map(({track:s})=>s)),tb(i=>!!i.length),yw()).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(Sw(),as(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(bw({zeroTime:this.zeroTime$.pipe(tb(du)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(Ue(this.video,this.params.desiredState.isLooped,t)).add(ce(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Pe(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&Iw(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 Xm(i.to)}},t)).add(rb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,vw(["init"])).pipe(gw(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),le(this.video)}createLiveDashPlayer(){let e=new hi({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,p,d,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(d=(p=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:p.to)!=null?d:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&du(t)?t:ft(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput: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 b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;Zm(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;Zm(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ee(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var ib=mi;var Je=(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)};import{assertNever as zk,assertNonNullable as Kk,debounce as Jk,ErrorCategory as Uu,filter as kg,filterChanged as Hu,fromEvent as Xk,isLowerOrEqual as Rg,isNonNullable as Zk,isInvariantQuality as eR,map as Lg,merge as Rs,observableFrom as tR,observeElementSize as rR,once as $g,Subscription as iR,ValueSubject as aR}from"@vkontakte/videoplayer-shared";var ss=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}},gr=class extends ss{constructor(){super(),this.listeners||ss.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)}},bi=class{constructor(){Object.defineProperty(this,"signal",{value:new gr,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&&(bi.prototype[Symbol.toStringTag]="AbortController",gr.prototype[Symbol.toStringTag]="AbortSignal");function ns(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 hu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!ns({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 p;c&&c.signal&&(p=c.signal,delete c.signal);let d=new t(l,c);return p&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:p}),d},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 p;try{p=new DOMException("Aborted","AbortError")}catch(h){p=new Error("Aborted"),p.name="AbortError"}if(c.aborted)return Promise.reject(p);let d=new Promise((h,f)=>{c.addEventListener("abort",()=>f(p),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(u,l)])}return n(u,l)},Request:s}}var gi=ns({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ab=gi?hu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Xe=gi?ab.fetch:window.fetch,sO=gi?ab.Request:window.Request,Ze=gi?bi:window.AbortController,nO=gi?gr:window.AbortSignal;var gb=Fe(ui(),1);var et=()=>window.ManagedMediaSource||window.MediaSource,os=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},sb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},nb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as bs,clientChecker as ms}from"@vkontakte/videoplayer-shared";var Re=document.createElement("video"),kw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Rw='video/mp4; codecs="hev1.1.6.L93.B0"',Sb='video/webm; codecs="vp09.00.10.08"',vb='video/webm; codecs="av01.0.00M.08"',Lw='audio/mp4; codecs="mp4a.40.2"',$w='audio/webm; codecs="opus"',ob,ub,Ct={mms:os(),mse:sb(),hls:!!((ob=Re.canPlayType)!=null&&ob.call(Re,"application/x-mpegurl")||(ub=Re.canPlayType)!=null&&ub.call(Re,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},lb,cb,he={mp4:!!((lb=Re.canPlayType)!=null&&lb.call(Re,"video/mp4")),webm:!!((cb=Re.canPlayType)!=null&&cb.call(Re,"video/webm")),cmaf:!0},ls,db,cs,pb,ds,hb,ps,fb,hs,mb,fs,bb,fe={h264:!!((db=(ls=et())==null?void 0:ls.isTypeSupported)!=null&&db.call(ls,kw)),h265:!!((pb=(cs=et())==null?void 0:cs.isTypeSupported)!=null&&pb.call(cs,Rw)),vp9:!!((hb=(ds=et())==null?void 0:ds.isTypeSupported)!=null&&hb.call(ds,Sb)),av1:!!((fb=(ps=et())==null?void 0:ps.isTypeSupported)!=null&&fb.call(ps,vb)),aac:!!((mb=(hs=et())==null?void 0:hs.isTypeSupported)!=null&&mb.call(hs,Lw)),opus:!!((bb=(fs=et())==null?void 0:fs.isTypeSupported)!=null&&bb.call(fs,$w))},Sr=(fe.h264||fe.h265)&&fe.aac,Dt,Mw=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:vb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Sb}})]);Dt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{Mw()}catch(a){console.error(a)}var vr=Ct.hls&&he.mp4,yb=()=>Object.keys(fe).filter(a=>fe[a]),Tb=(a,e=!1,t=!1)=>{let r=Ct.mse||Ct.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&he.mp4&&Sr;case"DASH_WEBM":return r&&he.webm&&fe.vp9&&fe.opus;case"DASH_WEBM_AV1":return r&&he.webm&&fe.av1&&fe.opus;case"DASH_STREAMS":return r&&(he.mp4&&Sr||he.webm&&(fe.vp9||fe.av1)&&(fe.opus||fe.aac));case"DASH_LIVE":return Ct.mse&&he.mp4&&Sr;case"DASH_LIVE_CMAF":return r&&he.mp4&&Sr&&he.cmaf;case"DASH_ONDEMAND":return r&&he.mp4&&Sr;case"HLS":case"HLS_ONDEMAND":return vr||e&&Ct.mse&&he.mp4&&Sr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return vr;case"MPEG":return he.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Ct.webrtc&&Ct.ws&&fe.h264&&(he.mp4||he.webm);default:return bs(i)}})},us=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 Dt?Dt[t].smooth?[t,e]:Dt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Dt?Dt[t].powerEfficient?[t,e]:Dt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:bs(a)}return[e,t]},Ib=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...us(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ms.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",...us(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...us(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...us(a),...i,"HLS","HLS_ONDEMAND"];default:bs(e)}return vr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Eb=({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=ms.isMac&&ms.isSafari;if(ms.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:bs(a)}else vr&&!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"]},fu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],xb=a=>{if(a.size!==0){if(a.size===1)return a.values().next().value.split(".").at(0);for(let e of a){let t=(0,gb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as Si}from"@vkontakte/videoplayer-shared";var Pb=a=>{if(!a)return{id:"EmptyResponse",category:Si.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Si.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Si.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Si.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Si.PARSER,message:"Response is valid XML, but parser failed"}};var vi=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};import{abortable as Nu,assertNonNullable as Ht,combine as Es,ErrorCategory as bt,filter as xs,filterChanged as Tg,fromEvent as Ar,interval as Fu,isNonNullable as Ig,map as qu,merge as wr,Subject as Eg,Subscription as xg,tap as Uk,throttle as Hk,clientChecker as jk,ValueSubject as ie}from"@vkontakte/videoplayer-shared";var Pr=Fe(ui(),1);var Cw=(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)},Dw=a=>window.clearTimeout(a),Ab=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",mu=Ab?Cw:window.requestIdleCallback,yO=Ab?Dw:window.cancelIdleCallback;var fg=Fe(Ka(),1);import{assertNever as Ow,ErrorCategory as wb,clientChecker as bu,Subject as kb}from"@vkontakte/videoplayer-shared";var Bw=16,Rb=!1;try{Rb=bu.isSafari&&!!bu.macVersion&&bu.macVersion<=Bw}catch(a){console.error(a)}var gu=class{constructor(e){this.bufferFull$=new kb;this.error$=new kb;this.queue=[];this.currentTask=null;this.destroyed=!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:wb.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;Rb&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);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)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:wb.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:Ow(t)}}},Lb=gu;var Su=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as xr,assertNonNullable as je,cloneDeepWith as Ck,ErrorCategory as Ft,fromEvent as Mu,getExponentialDelay as Cu,isNonNullable as Du,isNullable as Le,once as Dk,Subject as Ok,Subscription as Bk,ValueSubject as Ui}from"@vkontakte/videoplayer-shared";var N=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 yr=class extends N{};var yi=class extends N{};var Ti=class extends N{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 Ii=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ei=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var xi=class extends N{constructor(e,t){super(e,t),this.data=this.content}};var Y=class extends N{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ot=class extends Y{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 Pi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ai=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wi=class extends Y{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 ki=class extends Y{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Ri=class extends Y{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Li=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends Y{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 Mi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ci=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends Y{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Oi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends Y{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 Vi=class extends Y{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 _i=class extends Y{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 _w={ftyp:Ti,moov:Ii,moof:Ei,mdat:xi,sidx:Ot,trak:Pi,mdia:Li,mfhd:Di,tkhd:$i,traf:Oi,tfhd:Bi,tfdt:Vi,trun:_i,minf:Mi,sv3d:Ai,st3d:wi,prhd:ki,proj:Ci,equi:Ri,uuid:yi,unknown:yr},Bt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=_w[e];return r?new r(t,new a):new yr(t,new a)}};var Tr=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 Fw=new TextDecoder("ascii"),qw=a=>Fw.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Uw=a=>{let e=new Ot(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})},Hw=(a,e)=>{let r=new Bt().parse(a),i=new Tr(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,p=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,p)},jw=(a,e)=>{let r=new Bt().parse(a),s=new Tr(r).findAll("traf"),n=s[s.length-1].children.find(p=>p.type==="tfhd"),o=s[s.length-1].children.find(p=>p.type==="tfdt"),u=s[s.length-1].children.find(p=>p.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((p,d)=>p+d,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Gw=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 Tr(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},$b={validateData:qw,parseInit:Gw,getIndexRange:()=>{},parseSegments:Uw,parseFeedableSegmentChunk:Hw,getSegmentEndTime:jw};import{assertNonNullable as yu,isNonNullable as Ob,isNullable as Yw}from"@vkontakte/videoplayer-shared";import{assertNever as Ww}from"@vkontakte/videoplayer-shared";var Mb={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"}},Cb=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=Ni(a,t),i=r in Mb,s=i?Mb[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=Ni(u),p=l*2**((o-1)*8)+c,d=t+o,h;return d+p>a.byteLength?h=new DataView(a.buffer,a.byteOffset+d):h=new DataView(a.buffer,a.byteOffset+d,p),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+p,value:h,valueSize:p}},Ni=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ve=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ni(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:Ww(e)}},Vt=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Cb(r);if(!e(i))return;i.type==="master"&&Vt(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Db=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Cb(a);return Vt(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ve(o,n):s===17026?t=Ve(o,n):s===17029&&(r=Ve(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Bb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Qw=[231,22612,22743,167,171,163,160,175],zw=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,p=0;return Vt(a,({tag:d,type:h,value:f,valueSize:b})=>{if(d===21419){let g=Ve(f,h);l=Ni(g)}else d!==21420&&(l=void 0);return d===408125543?(e=f.byteOffset,t=f.byteOffset+b):d===357149030?s=!0:d===290298740?n=!0:d===2807729?r=Ve(f,h):d===17545?i=Ve(f,h):d===21420&&l===475249515?u=Ve(f,h):d===374648427?Vt(f,({tag:g,type:y,value:I})=>g===30321?(c=Ve(I,y)===1,!1):!0):s&&n&&Bb.includes(d)&&(o=!0),!o}),yu(e,"Failed to parse webm Segment start"),yu(t,"Failed to parse webm Segment end"),yu(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:p,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Kw=a=>{if(Yw(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Jw=(a,e)=>{let t=!1,r=!1,i=o=>Ob(o.time)&&Ob(o.position),s=[],n;return Vt(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=Ve(l,u));break;case 183:break;case 241:n&&(n.position=Ve(l,u));break;default:t&&Bb.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,p=s[u+1];return{status:"none",time:{from:l,to:p?p.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:p?e.segmentStart+p.position-1:e.segmentEnd-1}}})},Xw=a=>{let e=0,t=!1;try{Vt(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):Qw.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Vb={validateData:Db,parseInit:zw,getIndexRange:Kw,parseSegments:Jw,parseFeedableSegmentChunk:Xw};var Ir=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Vb;case"mp4":return $b}}throw new ReferenceError(`Unsupported mime type ${a}`)};var wu=Fe(sg(),1);var Au=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["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as og,isNullable as ug}from"@vkontakte/videoplayer-shared";var ng=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var lg=a=>{if(!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},_t=(a,e)=>{let t=a;t=(0,wu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,wu.default)(t,n,(o,u)=>ug(s)?o:ug(u)?s:s.padStart(parseInt(u,10),"0"))}return t},cg=(a,e)=>{var v,T,D,M,A,F,R,L,w,q,K,k,x,V,U,j,z,_,Gt,it,O,ae,me,Te,at,Wt,st,vt,Yt,Lr,al,sl,nl,ol,ul,ll,cl,dl,pl,hl,fl,ml,bl,gl,Sl,vl,yl,Tl,Il,El;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(D=(T=(v=s.querySelector("BaseURL"))==null?void 0:v.textContent)==null?void 0:T.trim())!=null?D:"",u=n.children,l=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),p=c?new Date(c).getTime():void 0,d,h=s.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],g=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)d=lg(h);else if(f){let se=lg(f);og(se)&&(d=se)}else g&&(d=parseInt(g,10));let y=0,I=(A=(M=s.getAttribute("profiles"))==null?void 0:M.split(","))!=null?A:[];for(let se of u){let yS=(F=se.getAttribute("id"))!=null?F:"id"+(y++).toString(10),$r=(R=se.getAttribute("mimeType"))!=null?R:"",Gs=(L=se.getAttribute("codecs"))!=null?L:"",Ws=(w=se.getAttribute("contentType"))!=null?w:$r==null?void 0:$r.split("/")[0],TS=(K=(q=se.getAttribute("profiles"))==null?void 0:q.split(","))!=null?K:[],IS=(k=se.getAttribute("lang"))!=null?k:void 0,ES=(U=(V=(x=se.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:V.trim())!=null?U:void 0,xS=se.querySelectorAll("Representation"),PS=se.querySelector("SegmentTemplate"),AS=(z=(j=se.querySelector("Role"))==null?void 0:j.getAttribute("value"))!=null?z:void 0,Mr=Ws,J={id:yS,language:IS,isDefault:AS==="main",label:ES,codecs:Gs,hdr:Mr==="video"&&Au(Gs),mime:$r,representations:[]};for(let Q of xS){let wS=(_=Q.getAttribute("lang"))!=null?_:void 0,kS=(Gt=Q.getAttribute("label"))!=null?Gt:void 0,RS=(ae=(O=(it=Q.querySelector("BaseURL"))==null?void 0:it.textContent)==null?void 0:O.trim())!=null?ae:"",Ys=new URL(RS||o,e).toString(),Qt=(me=Q.getAttribute("mimeType"))!=null?me:$r,ua=(at=(Te=Q.getAttribute("codecs"))!=null?Te:Gs)!=null?at:"",Qs;if(Ws==="text"){let yt=Q.getAttribute("id")||"",zs=yt.includes("_auto");Qs={id:yt,isAuto:zs,kind:"text",url:Ys}}else{let yt=(st=(Wt=Q.getAttribute("contentType"))!=null?Wt:Qt==null?void 0:Qt.split("/")[0])!=null?st:Ws,zs=(Yt=(vt=se.getAttribute("profiles"))==null?void 0:vt.split(","))!=null?Yt:[],LS=parseInt((Lr=Q.getAttribute("width"))!=null?Lr:"",10),xl=parseInt((al=Q.getAttribute("height"))!=null?al:"",10),Pl=parseInt((sl=Q.getAttribute("bandwidth"))!=null?sl:"",10)/1e3,Al=(nl=Q.getAttribute("frameRate"))!=null?nl:"",$S=(ol=Q.getAttribute("quality"))!=null?ol:void 0,MS=Al?ng(Al):void 0,CS=(ul=Q.getAttribute("id"))!=null?ul:"id"+(y++).toString(10),DS=yt==="video"?`${xl}p`:yt==="audio"?`${Pl}Kbps`:ua,OS=`${CS}@${DS}`,BS=[...I,...TS,...zs],Ks,VS=Q.querySelector("SegmentBase"),Tt=(ll=Q.querySelector("SegmentTemplate"))!=null?ll:PS;if(VS){let It=(dl=(cl=Q.querySelector("SegmentBase Initialization"))==null?void 0:cl.getAttribute("range"))!=null?dl:"",[Et,Xs]=It.split("-").map(zt=>parseInt(zt,10)),nt={from:Et,to:Xs},Cr=(pl=Q.querySelector("SegmentBase"))==null?void 0:pl.getAttribute("indexRange"),[Zs,la]=Cr?Cr.split("-").map(zt=>parseInt(zt,10)):[],Dr=Cr?{from:Zs,to:la}:void 0;Ks={type:"byteRange",url:Ys,initRange:nt,indexRange:Dr}}else if(Tt){let It={representationId:(hl=Q.getAttribute("id"))!=null?hl:void 0,bandwidth:(fl=Q.getAttribute("bandwidth"))!=null?fl:void 0},Et=parseInt((ml=Tt.getAttribute("timescale"))!=null?ml:"",10),Xs=(bl=Tt.getAttribute("initialization"))!=null?bl:"",nt=Tt.getAttribute("media"),Cr=(Sl=parseInt((gl=Tt.getAttribute("startNumber"))!=null?gl:"",10))!=null?Sl:1,Zs=_t(Xs,It);if(!nt)throw new ReferenceError("No media attribute in SegmentTemplate");let la=(vl=Tt.querySelectorAll("SegmentTimeline S"))!=null?vl:[],Dr=[],zt=0,en="",tn=0;if(la.length){let ca=Cr,Me=0;for(let Kt of la){let Ne=parseInt((yl=Kt.getAttribute("d"))!=null?yl:"",10),xt=parseInt((Tl=Kt.getAttribute("r"))!=null?Tl:"",10)||0,da=parseInt((Il=Kt.getAttribute("t"))!=null?Il:"",10);Me=Number.isFinite(da)?da:Me;let rn=Ne/Et*1e3,an=Me/Et*1e3;for(let pa=0;pa<xt+1;pa++){let NS=_t(nt,{...It,segmentNumber:ca.toString(10),segmentTime:(Me+pa*Ne).toString(10)}),wl=(an!=null?an:0)+pa*rn,FS=wl+rn;ca++,Dr.push({time:{from:wl,to:FS},url:NS})}Me+=(xt+1)*Ne,zt+=(xt+1)*rn}tn=Me/Et*1e3,en=_t(nt,{...It,segmentNumber:ca.toString(10),segmentTime:Me.toString(10)})}else if(og(d)){let Me=parseInt((El=Tt.getAttribute("duration"))!=null?El:"",10)/Et*1e3,Kt=Math.ceil(d/Me),Ne=0;for(let xt=1;xt<Kt;xt++){let da=_t(nt,{...It,segmentNumber:xt.toString(10),segmentTime:Ne.toString(10)});Dr.push({time:{from:Ne,to:Ne+Me},url:da}),Ne+=Me}tn=Ne,en=_t(nt,{...It,segmentNumber:Kt.toString(10),segmentTime:Ne.toString(10)})}let _S={time:{from:tn,to:1/0},url:en};Ks={type:"template",baseUrl:Ys,segmentTemplateUrl:nt,initUrl:Zs,totalSegmentsDurationMs:zt,segments:Dr,nextSegmentBeyondManifest:_S,timescale:Et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!yt||!Qt)continue;let Js={video:"video",audio:"audio",text:"text"}[yt];if(!Js)continue;Mr||(Mr=Js),Qs={id:OS,kind:Js,segmentReference:Ks,profiles:BS,duration:d,bitrate:Pl,mime:Qt,codecs:ua,width:LS,height:xl,fps:MS,quality:$S}}J.language||(J.language=wS),J.label||(J.label=kS),J.mime||(J.mime=Qt),J.codecs||(J.codecs=ua),J.hdr||(J.hdr=Mr==="video"&&Au(ua)),J.representations.push(Qs)}Mr&&i[Mr].push(J)}return{dynamic:l,liveAvailabilityStartTime:p,duration:d,streams:i}};var Fi=Fe(ui(),1);import{videoSizeToQuality as Mk}from"@vkontakte/videoplayer-shared";var dg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?pt(s):void 0)!=null?o:Mk({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},pg=({id:a,bitrate:e})=>({id:a,bitrate:e}),gs=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Fi.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Fi.default)(t,-1)},hg=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Lu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Fi.default)(r.split("."),0),isDefault:i}),$u=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Fi.default)(i.split("."),0)}),Ss=a=>"url"in a,Nt=a=>a.type==="template",qi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Hi=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new Ui(0);this.onLastSegment$=new Ui(!1);this.fullyBuffered$=new Ui(!1);this.playingRepresentation$=new Ui(void 0);this.playingRepresentationInit$=new Ui(void 0);this.error$=new Ok;this.gaps=[];this.subscription=new Bk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ze;this.destroyAbortController=new Ze;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=xr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Lb(this.sourceBuffer),this.subscription.add(Mu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ft.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ft.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Mu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ft.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,Su(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=Je(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,l<c)}else this.pruneBufferOld(o,n)})),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);je(r,"No init buffer for starting representation"),je(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=xr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);je(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Le(s)||Le(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),je(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(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();Du(n)&&(this.isLive||(i.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=xr(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let p=t.find(f=>f.id===c);p&&this.representations.set(c,p);let d=this.representations.get(c);if(!d||!Nt(d.segmentReference))return;let h=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);je(i);let s=this.segments.get(r);je(s,"No segments for starting representation");let n=this.initData.get(r);if(je(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,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));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.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ze,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(Le(e)||Le(this.downloadingRepresentationId)||Le(this.playingRepresentationId)||Le(this.sourceBuffer)||!Le(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(je(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(p=>e>=p.time.from&&e<p.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=Je(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&Su(this.sourceBuffer.buffered)>=this.bufferLimit){let p=Je(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<d);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))p="high";else{let d=(0,Pr.default)(o,0);d&&d.time.from-i.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(o,t,p)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&Je(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Pr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}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;Du(t.duration)&&t.duration-r>0&&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=e==null?void 0:e.streams[this.kind].flatMap(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=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!Nt(o.segmentReference))return;let u=o.segmentReference.segments.map(d=>({...d,status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Pr.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(d=>Math.floor(c)>=Math.floor(d.time.from)&&Math.floor(c)<=Math.floor(d.time.to));if(p===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,d)}else{let d=u.slice(p+1);this.segments.set(o.id,[...l,...d])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;je(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Nt(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=_t(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}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&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.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:p,time:{from:d,to:h}},f)=>{let b=d<=r&&h>=r,g=d>r||b||f===0&&r===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&d<=r+y||h<=r+y;return(p==="none"||p==="partially_ejected"&&g&&I&&this.sourceBuffer&&!vi(this.sourceBuffer.buffered,r))&&g&&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 p=i;p<s.length&&(n<=l||o<=c);p++){let d=s[p];if(n+=d.byte.to+1-d.byte.from,o+=d.time.to+1-d.time.from,d.status==="none"||d.status==="partially_ejected")u.push(d);else break}return u}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await xr(o,async function*(){let c=Cu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(p=>setTimeout(p,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let p=new DataView(c);if(!isFinite(i.segment.time.to)){let d=t.segmentReference.timescale,h=Ir(t.mime);i.segment.time.to=h.getSegmentEndTime(p,d)}u&&i.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(p,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),qi(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await xr(n,async function*(){let u=Cu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Mu(window,"online").pipe(Dk()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.kind==="video"&&console.log("-----------"),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),qi(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Nt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Pr.default)(e,0).byte.from,to:(0,Pr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{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:Ft.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Nt(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{let p=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(p)}catch(p){this.error$.next({id:"SegmentFeeding",category:Ft.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:p})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Ir(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,l=e.byteLength;for(let c of this.activeSegments){let{segment:p}=c,d=u==="byteRange",h=d?p.byte.to-p.byte.from+1:l;if(c.representationId!==t||!(!d||p.byte.from>=r&&p.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=d?p.byte.from-r:0,g=d?p.byte.to-r:e.byteLength,y=b<i,I=g<=i;if(p.status==="downloading"&&y&&I){p.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+b,h),v=this.getCurrentPosition();Du(v)&&(this.bufferAccumulation.accumulatedBufferSizeMs=p.time.to-v,this.bufferAccumulation.accumulated.push({segmentView:S,segmentProgress:c}),this.activeSegments.delete(c));let T=({segmentView:D,segmentProgress:M})=>this.sourceBufferTaskQueue.append(D,s).then(A=>A&&!s.aborted?this.onSegmentFullyAppended(M,t):n());this.kind==="video"&&console.log({currentPosition:v,bufferAccumulation:Ck(this.bufferAccumulation)}),this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.kind==="video"&&console.log("append buffer"),this.bufferAccumulation.accumulated.forEach(T),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||Le(v))&&(this.kind==="video"&&console.log("regular append segment"),T({segmentView:S,segmentProgress:c}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&!I&&(c.loadedBytes=Math.min(h,i-b),c.loadedBytes>c.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),v=c.loadedBytes===h?S:Ir(o.mime).parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(p.status="partially_fed",c.feedingBytes+=v.byteLength,this.sourceBufferTaskQueue.append(v,s).then(T=>{if(s.aborted)n();else if(T)c.fedBytes+=v.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let c=l.byte.from-r,p=l.byte.to-r,d=p-c+1,h=c<i,f=p<=i;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,d);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,i-c),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===d?b:Ir(o.mime).parseFeedableSegmentChunk(b);g!=null&&g.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):n())}}}}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ss(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"&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);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=mu(()=>(0,fg.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?xr(this.destroyAbortController.signal,async function*(){let o=Cu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ir(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,p);let d=c;this.isLive&&Nt(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ft.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Le(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,p)=>c.from-p.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:p,to:d}=u[c],h=l[l.length-1];h.to>=p?h.to=Math.max(h.to,d):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(u.time),i=n(i);let l=Ss(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,p=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||p)&&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,p=0;for(let d of this.segments.values())for(let h of d)h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&p++;if(p===this.segments.size){let d={time:{from:l,to:c},url:"",status:"none"};o(d)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Le(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=l=>{var p;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=Ss(l)?(p=l.size)!=null?p:0:l.byte.to-l.byte.from;i+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){i=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let c of l){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let c=this.sourceBuffer.buffered.start(l)*1e3,p=this.sourceBuffer.buffered.end(l)*1e3;for(let d of this.segments.values())for(let h of d)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(p)){s=c,n=p;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){i=0,s=1/0,n=-1/0;let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let p of c)p.time.from>e+l&&p.status==="fed"&&u(p)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(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){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=mu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ft.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Le(this.sourceBuffer)||Le(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=1;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-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);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 ji=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var mg=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}};import{abortable as Gi,assertNever as bg,fromEvent as gg,merge as Vk,now as Ou,Subscription as _k,ValueSubject as Bu}from"@vkontakte/videoplayer-shared";var vs=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new Bu(void 0);this.lastConnectionReused$=new Bu(void 0);this.lastRequestFirstBytes$=new Bu(void 0);this.abortAllController=new Ze;this.subscription=new _k;this.fetchManifest=Gi(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=ji(t));let r=yield Xe(t,{signal:this.abortAllController.signal}).catch(Wi);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=Gi(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var A,F;let l=e,c=new Headers;if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let R=new URL(l,location.href);R.searchParams.append("bytes",`${r.from}-${r.to}`),l=R.toString();break}default:bg(t)}this.requestQuic&&(l=ji(l));let p=this.abortAllController.signal,d;if(n){let R=new Ze;if(d=Vk(gg(this.abortAllController.signal,"abort"),gg(n,"abort")).subscribe(()=>{try{R.abort()}catch(L){Wi(L)}}),this.abortAllController.signal.aborted||n.aborted)try{R.abort()}catch(L){Wi(L)}p=R.signal}let h=Ou(),f=yield Xe(l,{priority:s,headers:c,signal:p}).catch(Wi),b=Ou();if(!f)return d==null||d.unsubscribe(),null;if((A=this.throughputEstimator)==null||A.addRawRtt(b-h),!f.ok||!f.body)return d==null||d.unsubscribe(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));if(this.onHeadersReceived(f.headers),!i&&!o)return d==null||d.unsubscribe(),f.arrayBuffer();let[g,y]=f.body.tee(),I=g.getReader();o&&((F=this.throughputEstimator)==null||F.trackStream(y,u));let S=0,v=new Uint8Array(0),T=!1,D=R=>{d==null||d.unsubscribe(),T=!0,Wi(R)},M=Gi(p,async function*({done:R,value:L}){if(S===0&&this.lastRequestFirstBytes$.next(Ou()-h),p.aborted){d==null||d.unsubscribe();return}if(!R&&L){let w=new Uint8Array(v.length+L.length);w.set(v),w.set(L,v.length),v=w,S+=L.byteLength,i==null||i(new DataView(v.buffer),S),yield I==null?void 0:I.read().then(M,D)}}.bind(this));return yield I==null?void 0:I.read().then(M,D),d==null||d.unsubscribe(),T?null:v.buffer}.bind(this));this.fetchByteRangeRepresentation=Gi(this.abortAllController.signal,async function*(e,t,r){var y;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 p=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!p)return null;let d=new DataView(p,i-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=(y=e.indexRange)!=null?y:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(p,f.from-n,f.to-f.from+1);else{let I=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!I)return null;b=new DataView(I)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(p),segments:g}}.bind(this));this.fetchTemplateRepresentation=Gi(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){let{type:t,reused:r}=mg(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:bg(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Wi=a=>{if(!qi(a))throw a};var qt=(a,e,t)=>t*e+(1-t)*a,Vu=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Sg=(a,e,t,r)=>{let i=0,s=t,n=Vu(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};import{isNullable as Nk,ValueSubject as vg}from"@vkontakte/videoplayer-shared";var mt=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 vg(e.initial),this.debounced$=new vg(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new re(`raw_${t}`),this.smoothedSeries$=new re(`smoothed_${t}`),this.reportedSeries$=new re(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(Nk(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 ys=class extends mt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=qt(this.slow,e,this.params.emaAlphaSlow),this.fast=qt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ts=class extends mt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Vu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=qt(this.emaSmoothed,e,this.params.emaAlpha);let r=Sg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Is=class extends mt{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?qt(this.smoothed,t,this.params.emaAlpha):t}};var Ut=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ys({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Ts({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Is({initial:e,label:"liveEdgeDelay",...t})}};var _u=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var Pg=["timeupdate","progress","play","seeked","stalled","waiting"];var Ps=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new xg;this.representationSubscription=new xg;this.state$=new $("none");this.currentVideoRepresentation$=new ie(void 0);this.currentVideoRepresentationInit$=new ie(void 0);this.currentAudioRepresentation$=new ie(void 0);this.currentVideoSegmentLength$=new ie(0);this.currentAudioSegmentLength$=new ie(0);this.error$=new Eg;this.lastConnectionType$=new ie(void 0);this.lastConnectionReused$=new ie(void 0);this.lastRequestFirstBytes$=new ie(void 0);this.isLive$=new ie(!1);this.liveDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(void 0);this.bufferLength$=new ie(0);this.liveLoadBufferLength$=new ie(0);this.livePositionFromPlayer$=new ie(0);this.timeInWaiting=0;this.isActiveLowLatency$=new ie(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Eg;this.gapWatchdogActive=!1;this.destroyController=new Ze;this.initManifest=Nu(this.destroyController.signal,async function*(e,t,r){var i;this.element=e,this.manifestUrlString=ee(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:bt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Nu(this.destroyController.signal,async function*(){var s,n;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:bt.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t;try{t=cg(e!=null?e:"",this.manifestUrlString)}catch(o){let u=(s=Pb(e))!=null?s:{id:"ManifestParsing",category:bt.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(u)}if(!t)return null;let r=(o,u,l)=>{var c,p,d,h;return!!((p=(c=this.element)==null?void 0:c.canPlayType)!=null&&p.call(c,u)&&((h=(d=et())==null?void 0:d.isTypeSupported)!=null&&h.call(d,`${u}; codecs="${l}"`))||o==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((n=t.duration)!=null?n:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let o of["video","audio"]){let l=t.streams[o].filter(({mime:d,codecs:h})=>r(o,d,h)),c=new Set(l.map(({codecs:d})=>d)),p=xb(c);if(p&&(i[o]=l.filter(({codecs:d})=>d.startsWith(p))),o==="video"){let d=this.tuning.preferHDR,h=i.video.some(b=>b.hdr),f=i.video.some(b=>!b.hdr);jk.isHDR&&d&&h?i.video=i.video.filter(b=>b.hdr):f&&(i.video=i.video.filter(b=>!b.hdr))}}return{...t,streams:i}}.bind(this));this.initRepresentations=Nu(this.destroyController.signal,async function*(e,t,r){var p;Ht(this.manifest),Ht(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=d=>{this.representationSubscription.add(Ar(d,"error").pipe(xs(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:bt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?nb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&os())if(r){let d=document.createElement("source");i(d),d.type="application/x-mpegurl",d.src=r.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);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((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new Hi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Ig(t)){let d=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Hi("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}if(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(Fu(1e3).subscribe(d=>{var h;if((h=this.element)!=null&&h.paused){let f=Qo(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(wr(...Pg.filter(d=>d!=="waiting").map(d=>Ar(this.element,d))).pipe(qu(d=>this.element?Je(this.element.buffered,this.element.currentTime*1e3):0),Tg(),xs(d=>!!d),Uk(d=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Tg()).subscribe(h=>_u(this.element,1))),this.representationSubscription.add(Es({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(xs(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(Es({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b,S=1;Math.abs(I)>g&&(S=1+Math.sign(I)*y),_u(this.element,S)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let y=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(S=>{var v,T;return(T=(v=S.getLiveSegmentsToLoadState(this.manifest))==null?void 0:v.to)!=null?T:y}))-y}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add(Es({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Hk(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(Ht(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=Qo(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,T=isFinite(h)?h:f,D=this.isActiveLowLatency$.getValue(),M=y<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(D&&M);let A="none";if(D?A="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&M?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),A="active_low_latency"):g!==0&&T<I?A="live_forward_buffering":T<I+v&&(A="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),A==="live_forward_buffering"||A==="live_with_target_offset"){let F=d-(I+S),R=this.normolizeLiveOffset(Math.trunc(g+F/b)),L=Math.abs(R-g),w;!h||L<=this.tuning.dashCmafLive.offsetCalculationError?w=g:R>0&&L>this.tuning.dashCmafLive.offsetCalculationError?w=R:w=0,this.manifestUrlString=ee(this.manifestUrlString,w,2)}A!=="none"&&A!=="active_low_latency"&&(d=0,this.updateLive())}))}let u=wr(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(qu(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),l=wr(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(qu(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue())));this.representationSubscription.add(wr(this.forceEnded$,Es({allBuffersFull:u,someBufferEnded:l}).pipe(xs(({allBuffersFull:d,someBufferEnded:h})=>d&&h))).subscribe(()=>{var d;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(d=this.source)==null||d.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:bt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(wr(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(d=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",d)}));let c=[(p=this.manifest.duration)!=null?p:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(d=>d.representations).flatMap(d=>{var h;return(h=d.duration)!=null?h:0})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&Ig(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Fu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:bt.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new vs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Ut.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var r,i,s,n;Ht(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ee(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video)),await((n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio)))}initBuffer(){Ht(this.element),this.state$.setState("running"),this.subscription.add(wr(...Pg.map(e=>Ar(this.element,e)),Ar(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:bt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ar(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ar(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&vi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var s,n;if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset);else{let o=this.element.currentTime*1e3;(s=this.videoBufferManager)==null||s.maintain(o),(n=this.audioBufferManager)==null||n.maintain(o)}}};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=Fu(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:bt.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u,l;Ht(this.element),Ht(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),vi(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(l=this.audioBufferManager)==null||l.maintain(r),this.element.currentTime=r/1e3}stop(){var e,t,r;(e=this.element)==null||e.querySelectorAll("source").forEach(i=>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}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],i=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-i<=t&&n.to+i>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var As=class{constructor(e,t){this.fov=e,this.orientation=t}};var ws=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Ag=`attribute vec2 a_vertex;
36
+ [best video track] ${$==null?void 0:$.quality}
37
+ [selected video track] ${B==null?void 0:B.quality}
38
+ `}),ib(r,p,B,c)},ab=(a,e,t,{throughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var f;eb(t,rb);let c=i.considerPlaybackRate&&fe(s)?s:1,l=[...t].sort(pu(-1)),d=a.bitrate;sw(d);let p=c*tb(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),h;return fe(r)&&isFinite(r)&&(h=l.find(b=>fe(b.bitrate)?r-d>=b.bitrate*p:!0)),h||(h=ns(a,e,t,i.minVideoAudioRatio)),(h==null?void 0:h.bitrate)!==((f=o==null?void 0:o.last)==null?void 0:f.bitrate)&&u({message:`
39
+ [AUDIO TRACKS ABR]
40
+ [available audio tracks]
41
+ ${t.map(b=>`{ id: ${b.id}, bitrate: ${b.bitrate} }`).join(`
42
+ `)}
43
+
44
+ [tuning]
45
+ ${Object.entries(i!=null?i:{}).map(([b,g])=>`${b}: ${g}`).join(`
46
+ `)}
47
+
48
+ [limit params]
49
+ throughput: ${r},
50
+ reserve: ${d},
51
+ playbackRate: ${s},
52
+ playbackRateFactor: ${c},
53
+ forwardBufferHealth: ${n},
54
+ bitrateFactor: ${p},
55
+ minBufferToSwitchUp: ${i.minBufferToSwitchUp},
56
+
57
+ [selected audio track] ${h==null?void 0:h.id}
58
+ `}),h&&ib(i,u,h,o)};var X=a=>new URL(a).hostname;import{assertNever as lb,assertNonNullable as db,combine as Aw,debounce as ww,ErrorCategory as pb,filter as hb,filterChanged as kw,isNonNullable as gu,map as ds,merge as fb,observableFrom as Rw,once as $w,Subscription as Lw,ValueSubject as Su,videoQualityToHeight as Mw,videoSizeToQuality as Cw}from"@vkontakte/videoplayer-shared";var sb=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},me=async a=>{let e=a.muted;try{await a.play()}catch(t){if(!sb(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(r){return sb(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as us,isNullable as cw,assertNonNullable as Si}from"@vkontakte/videoplayer-shared";import{isNonNullable as nb,assertNonNullable as os,now as ow}from"@vkontakte/videoplayer-shared";function Z(){return ow()}function hu(a){return Z()-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 c=n.indexOf("?")>-1?"&":"?";return u&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ob(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function yr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,c=0,l,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;os(l);let w=hu(l),L;if(w<b){L=b-w,setTimeout(g,L);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,R()},y=w=>(s=w,O),I=w=>(d=w,O),S=()=>(h="json",O),v=()=>{if(!u){if(--c>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},T=w=>(p=w,O),R=()=>{l=Z(),n=new i,n.open("get",a);let w=0,L,q=0,k=()=>(os(l),Math.max(l,Math.max(L||0,q||0)));if(s&&n.addEventListener("progress",x=>{let V=Z();s.updateChunk&&x.loaded>w&&(s.updateChunk(k(),x.loaded-w),w=x.loaded,L=V)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>v())),n.addEventListener("load",()=>{if(u)return;os(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let V=n.response.byteLength-w;V&&s.updateChunk&&s.updateChunk(k(),V)}n.responseType==="json"&&!Object.values(n.response).length?v():(d&&d(),e(n.response))}else v()}),n.addEventListener("error",()=>{v()}),p){let x=()=>{os(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(q=Z(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),O},O={withBitrateReporting:y,withParallel:T,withJSONResponse:S,withRetryCount:w=>(c=w,O),withRetryInterval:(w,L)=>(nb(w)&&(b=w),nb(L)&&(f=L),O),withTimeout:w=>(o=w,O),withFinally:I,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return O}var bi=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 gi=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=Z(),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=Z()-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=yr(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=Z()}_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=Z();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(){Object.values(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 cs=1e4,mu=3;var lw=6e4,dw=10,pw=1,hw=500,vi=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.chunkRateEstimator=new bi(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||us(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=()=>{ob(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 gi(mu,cs,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,c=null,l=!1,d=()=>{let v=s&&(!l||l===this.rep);return v||t("Not running!"),v},p=(v,T,R)=>{u&&u.abort(),u=yr(this.urlResolver.resolve(v,!1),T,R,()=>this._retryCallback()).withTimeout(cs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(mu).withFinally(()=>{u=null}).send()},h=(v,T,R)=>{Si(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),T,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=v=>{let T=r.playbackRate;r.playbackRate!==v&&(t(`Playback rate switch: ${T}=>${v}`),r.playbackRate=v)},b=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=Z()-1e4,U=0;for(let B=0;B<this.bufferStates.length;B++){let N=this.bufferStates[B];v=Math.min(v,N.buf),N.ts<R&&U++}this.bufferStates.splice(0,U),t(`update playback rate; minBuffer=${v} drop=${U} jitter=${this.sourceJitter}`);let $=v-pw;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?f(1.15):$>1?f(1.1):$>.3?f(1.05):f(1)}},y=v=>{let T,R=()=>T&&T.start?T.start.length:0,U=x=>T.start[x]/1e3,$=x=>T.dur[x]/1e3,B=x=>T.fragIndex+x,N=(x,V)=>({chunkIdx:B(x),startTS:U(x),dur:$(x),discontinuity:V}),O=()=>{let x=0;if(T&&T.dur){let V=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,G=V;this.sourceJitter>1&&(G+=this.sourceJitter-1);let z=T.dur.length-1;for(;z>=0&&(G-=T.dur[z],!(G<=0));--z);x=Math.min(z,T.dur.length-1-H),x=Math.max(x,0)}return N(x,!0)},w=x=>{let V=R();if(!(V<=0)){if(us(x)){for(let H=0;H<V;H++)if(U(H)>x)return N(H)}return O()}},L=x=>{let V=R(),H=x?x.chunkIdx+1:0,G=H-T.fragIndex;if(!(V<=0)){if(!x||G<0||G-V>dw)return t(`Resync: offset=${G} bChunks=${V} chunk=`+JSON.stringify(x)),O();if(!(G>=V))return N(H-T.fragIndex,!1)}},q=(x,V,H)=>{c&&c.abort(),c=yr(this.urlResolver.resolve(x,!0,this.lowLatency),V,H,()=>this._retryCallback()).withTimeout(cs).withRetryCount(mu).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(x,V)=>{q(v,H=>{if(!d())return;T=H;let G=!!T.lowLatency;G!==this.lowLatency&&b(G);let z=0;for(let se=0;se<T.dur.length;++se)z+=T.dur[se];z>0&&(Si(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(z/T.dur.length)),i({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,x(w(V))},()=>this._handleNetworkError())},nextChunk:L}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),Si(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:v=>{let{videoElement:T,logger:R}=this.params,U=y(e.jidxUrl),$,B,N,O,w=0,L,q,k,x=()=>{L&&(clearTimeout(L),L=void 0);let A=Math.max(hw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=w+A,Se=Z(),xe=Math.min(1e4,ne-Se);w=Se;let ot=()=>{c||d()&&U.seek(()=>{d()&&(w=Z(),V(),x())})};xe>0?L=window.setTimeout(()=>{this.paused?x():ot()},xe):ot()},V=()=>{let A;for(;A=U.nextChunk(O);)O=A,Et(A);let ne=U.nextChunk(N);if(ne){if(N&&ne.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?x():(I(),this._initPlayerWith(e));return}se(ne)}else x()},H=(A,ne)=>{if(!d()||!this.sourceBuffer)return;let Se,xe,ot,Kt=ut=>{window.setTimeout(()=>{d()&&H(A,ne)},ut)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),Kt(100);else{let ut=Z(),xt=T.currentTime;!this.paused&&T.buffered.length>1&&q===xt&&ut-k>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),q!==xt&&(q=xt,k=ut);let Jt=this._getBufferSizeSec();if(Jt>30)R(`Buffered ${Jt} seconds; delaying appendBuffer`),Kt(2e3);else try{this.sourceBuffer.appendBuffer(A),this.videoPlayStarted?(this.bufferStates.push({ts:ut,buf:Jt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(Br){if(Br.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),ot=this.sourceBuffer.buffered.length,ot!==0&&(Se=this.sourceBuffer.buffered.start(0),xe=xt,xe-Se>4&&this.sourceBuffer.remove(Se,xe-3)),Kt(1e3);else throw Br}}},G=()=>{B&&$&&(R([`Appending chunk, sz=${B.byteLength}:`,JSON.stringify(N)]),H(B,function(){B=null,V()}))},z=A=>e.fragUrlTemplate.replace("%%id%%",A.chunkIdx),se=A=>{d()&&h(z(A),(ne,Se)=>{if(d()){if(Se/=1e3,B=ne,N=A,n=A.startTS,Se){let xe=Math.min(10,A.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}G()}},()=>this._handleNetworkError())},Et=A=>{d()&&(Si(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(z(A),!1)))},nt=A=>{d()&&(e.cachedHeader=A,H(A,()=>{$=!0,G()}))};s=!0,U.seek(A=>{if(d()){if(w=Z(),!A){x();return}O=A,!cw(v)||A.startTS>v?se(A):(N=A,V())}},v),e.cachedHeader?nt(e.cachedHeader):p(e.headerUrl,nt,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},l}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),us(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,Si(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return us(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=Z();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,c=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&hu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&c(),h},notifySwitch:d=>{let p=Z();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=yr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(cs).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;me(e).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,c)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.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))},lw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as fw,filter as ub,fromEvent as mw,interval as bw,isHigher as gw,isInvariantQuality as Sw,isLower as vw,merge as yw,Subject as cb,Subscription as Tw}from"@vkontakte/videoplayer-shared";var bu=class{constructor(){this.onDroopedVideoFramesLimit$=new cb;this.subscription=new Tw;this.playing=!1;this.tracks=[];this.forceChecker$=new cb;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&&!Sw(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&&gw(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(mw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=bw(this.droppedFramesChecker.checkTime).pipe(ub(()=>this.playing),ub(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(fw(this.droppedFramesChecker.checkTime)),r=yw(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=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>vw(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}},ls=bu;import{map as Iw,Observable as Ew}from"@vkontakte/videoplayer-shared";import{fromEvent as xw}from"@vkontakte/videoplayer-shared";var yi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Pw=(a,e)=>new Ew(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||yi()))},{...r,...e});i.observe(a);let s=xw(document,"visibilitychange").pipe(Iw(n=>!document.hidden||yi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Le=Pw;var Dw=["paused","playing","ready"],Bw=["paused","playing","ready"],Ti=class{constructor(e){this.subscription=new Lw;this.videoState=new M("stopped");this.representations$=new Su([]);this.textTracksManager=new Re;this.droppedFramesManager=new ls;this.maxSeekBackTime$=new Su(1/0);this.zeroTime$=new Su(void 0);this.liveOffset=new Je;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:pb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let c=(t=u.name)!=null?t:u.index.toString(10),l=(r=mt(u.name))!=null?r:Cw(u.video),d=u.bitrate/1e3,p={...u.video};if(!l)continue;let h={id:c,quality:l,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),gu(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(Bw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Dw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ee(this.params.source.url,u))}return;default:return lb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:pb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};fb(this.videoState.stateChangeStarted$.pipe(ds(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ds(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=le(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),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(X(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.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=he(this.video);this.subscription.add(this.representations$.pipe(ds(i=>i.map(({track:s})=>s)),hb(i=>!!i.length),$w()).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(kw(),ds(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Aw({zeroTime:this.zeroTime$.pipe(hb(gu)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(je(this.video,this.params.desiredState.isLooped,t)).add(pe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(ke(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(Le(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&Mw(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 lb(i.to)}},t)).add(fb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Rw(["init"])).pipe(ww(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),de(this.video)}createLiveDashPlayer(){let e=new vi({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 c,l,d,p,h,f;let e=this.representations$.getValue(),t=(l=(c=this.params.desiredState.videoTrack.getTransition())==null?void 0:c.to)!=null?l: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&&gu(t)?t:bt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput: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 b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;db(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;db(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ee(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var mb=Ti;var Ze=(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)};import{assertNever as sR,assertNonNullable as nR,debounce as oR,ErrorCategory as Wu,filter as qg,filterChanged as Yu,fromEvent as uR,isNonNullable as cR,map as Ug,merge as Os,observableFrom as lR,observeElementSize as dR,once as Hg,Subscription as pR,ValueSubject as hR}from"@vkontakte/videoplayer-shared";var ps=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}},Tr=class extends ps{constructor(){super(),this.listeners||ps.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)}},Ii=class{constructor(){Object.defineProperty(this,"signal",{value:new Tr,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&&(Ii.prototype[Symbol.toStringTag]="AbortController",Tr.prototype[Symbol.toStringTag]="AbortSignal");function hs(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 vu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!hs({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(c,l){let d;l&&l.signal&&(d=l.signal,delete l.signal);let p=new t(c,l);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,c)=>{let l=s&&s.prototype.isPrototypeOf(u)?u.signal:c?c.signal:void 0;if(l){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(l.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{l.addEventListener("abort",()=>f(d),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([p,n(u,c)])}return n(u,c)},Request:s}}var Ei=hs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),bb=Ei?vu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,et=Ei?bb.fetch:window.fetch,mB=Ei?bb.Request:window.Request,tt=Ei?Ii:window.AbortController,bB=Ei?Tr:window.AbortSignal;var Rb=Ue(hi(),1);var rt=()=>window.ManagedMediaSource||window.MediaSource,fs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},gb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Sb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Es,clientChecker as Is}from"@vkontakte/videoplayer-shared";var Me=document.createElement("video"),_w='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Nw='video/mp4; codecs="hev1.1.6.L93.B0"',$b='video/webm; codecs="vp09.00.10.08"',Lb='video/webm; codecs="av01.0.00M.08"',Fw='audio/mp4; codecs="mp4a.40.2"',qw='audio/webm; codecs="opus"',vb,yb,Nt={mms:fs(),mse:gb(),hls:!!((vb=Me.canPlayType)!=null&&vb.call(Me,"application/x-mpegurl")||(yb=Me.canPlayType)!=null&&yb.call(Me,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Tb,Ib,be={mp4:!!((Tb=Me.canPlayType)!=null&&Tb.call(Me,"video/mp4")),webm:!!((Ib=Me.canPlayType)!=null&&Ib.call(Me,"video/webm")),cmaf:!0},bs,Eb,gs,xb,Ss,Pb,vs,Ab,ys,wb,Ts,kb,ge={h264:!!((Eb=(bs=rt())==null?void 0:bs.isTypeSupported)!=null&&Eb.call(bs,_w)),h265:!!((xb=(gs=rt())==null?void 0:gs.isTypeSupported)!=null&&xb.call(gs,Nw)),vp9:!!((Pb=(Ss=rt())==null?void 0:Ss.isTypeSupported)!=null&&Pb.call(Ss,$b)),av1:!!((Ab=(vs=rt())==null?void 0:vs.isTypeSupported)!=null&&Ab.call(vs,Lb)),aac:!!((wb=(ys=rt())==null?void 0:ys.isTypeSupported)!=null&&wb.call(ys,Fw)),opus:!!((kb=(Ts=rt())==null?void 0:Ts.isTypeSupported)!=null&&kb.call(Ts,qw))},Ir=(ge.h264||ge.h265)&&ge.aac,Ft,Uw=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Lb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:$b}})]);Ft={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{Uw()}catch(a){console.error(a)}var Er=Nt.hls&&be.mp4,Mb=()=>Object.keys(ge).filter(a=>ge[a]),Cb=(a,e=!1,t=!1)=>{let r=Nt.mse||Nt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&be.mp4&&Ir;case"DASH_WEBM":return r&&be.webm&&ge.vp9&&ge.opus;case"DASH_WEBM_AV1":return r&&be.webm&&ge.av1&&ge.opus;case"DASH_STREAMS":return r&&(be.mp4&&Ir||be.webm&&(ge.vp9||ge.av1)&&(ge.opus||ge.aac));case"DASH_LIVE":return Nt.mse&&be.mp4&&Ir;case"DASH_LIVE_CMAF":return r&&be.mp4&&Ir&&be.cmaf;case"DASH_ONDEMAND":return r&&be.mp4&&Ir;case"HLS":case"HLS_ONDEMAND":return Er||e&&Nt.mse&&be.mp4&&Ir;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Er;case"MPEG":return be.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Nt.webrtc&&Nt.ws&&ge.h264&&(be.mp4||be.webm);default:return Es(i)}})},ms=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 Ft?Ft[t].smooth?[t,e]:Ft[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Ft?Ft[t].powerEfficient?[t,e]:Ft[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Es(a)}return[e,t]},Db=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ms(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Is.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",...ms(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ms(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ms(a),...i,"HLS","HLS_ONDEMAND"];default:Es(e)}return Er?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Bb=({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=Is.isMac&&Is.isSafari;if(Is.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:Es(a)}else Er&&!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"]},yu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ob=a=>{if(a.size!==0){if(a.size===1)return a.values().next().value.split(".").at(0);for(let e of a){let t=(0,Rb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as xi}from"@vkontakte/videoplayer-shared";var Vb=a=>{if(!a)return{id:"EmptyResponse",category:xi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:xi.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:xi.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:xi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:xi.PARSER,message:"Response is valid XML, but parser failed"}};var Pi=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};import{abortable as Hu,assertNonNullable as Qt,combine as $s,ErrorCategory as St,filter as Ls,filterChanged as Dg,fromEvent as Lr,interval as ju,isNonNullable as Bg,map as Gu,merge as Mr,Subject as Og,Subscription as Vg,tap as Jk,throttle as Xk,clientChecker as Zk,ValueSubject as ie,flattenObject as ea,getTraceSubscriptionMethod as eR}from"@vkontakte/videoplayer-shared";var Rr=Ue(hi(),1);var Hw=(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)},jw=a=>window.clearTimeout(a),_b=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Tu=_b?Hw:window.requestIdleCallback,$B=_b?jw:window.cancelIdleCallback;var wg=Ue(is(),1);import{assertNever as Gw,ErrorCategory as Nb,clientChecker as Iu,Subject as Fb}from"@vkontakte/videoplayer-shared";var Ww=16,qb=!1;try{qb=Iu.isSafari&&!!Iu.macVersion&&Iu.macVersion<=Ww}catch(a){console.error(a)}var Eu=class{constructor(e){this.bufferFull$=new Fb;this.error$=new Fb;this.queue=[];this.currentTask=null;this.destroyed=!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:Nb.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;qb&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);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)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:Nb.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:Gw(t)}}},Ub=Eu;var xu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as kr,assertNonNullable as We,ErrorCategory as Gt,fromEvent as Vu,getExponentialDelay as _u,isNonNullable as Nu,isNullable as Ce,once as Hk,Subject as jk,Subscription as Gk,ValueSubject as Qi}from"@vkontakte/videoplayer-shared";var F=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 xr=class extends F{};var Ai=class extends F{};var wi=class extends F{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 ki=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends F{constructor(e,t){super(e,t),this.data=this.content}};var Q=class extends F{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var qt=class extends Q{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,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}};var Li=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ci=class extends Q{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 Di=class extends Q{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Bi=class extends Q{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Oi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vi=class extends Q{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 _i=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ni=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Fi=class extends Q{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var qi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends Q{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 Hi=class extends Q{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 ji=class extends Q{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 Qw={ftyp:wi,moov:ki,moof:Ri,mdat:$i,sidx:qt,trak:Li,mdia:Oi,mfhd:Fi,tkhd:Vi,traf:qi,tfhd:Ui,tfdt:Hi,trun:ji,minf:_i,sv3d:Mi,st3d:Ci,prhd:Di,proj:Ni,equi:Bi,uuid:Ai,unknown:xr},Ut=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=Qw[e];return r?new r(t,new a):new xr(t,new a)}};var Pr=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 Kw=new TextDecoder("ascii"),Jw=a=>Kw.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Xw=a=>{let e=new qt(a,new Ut),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})},Zw=(a,e)=>{let r=new Ut().parse(a),i=new Pr(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],c=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,d)},ek=(a,e)=>{let r=new Ut().parse(a),s=new Pr(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"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((d,p)=>d+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},tk=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 Ut().parse(a),i=new Pr(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},Hb={validateData:Jw,parseInit:tk,getIndexRange:()=>{},parseSegments:Xw,parseFeedableSegmentChunk:Zw,getSegmentEndTime:ek};import{assertNonNullable as Au,isNonNullable as Yb,isNullable as ik}from"@vkontakte/videoplayer-shared";import{assertNever as rk}from"@vkontakte/videoplayer-shared";var jb={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"}},Gb=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=Gi(a,t),i=r in jb,s=i?jb[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),c=n&255>>o,l=Gi(u),d=c*2**((o-1)*8)+l,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}},Gi=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ne=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Gi(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:rk(e)}},Ht=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Gb(r);if(!e(i))return;i.type==="master"&&Ht(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Wb=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Gb(a);return Ht(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ne(o,n):s===17026?t=Ne(o,n):s===17029&&(r=Ne(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Qb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],ak=[231,22612,22743,167,171,163,160,175],sk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,c,l=!1,d=0;return Ht(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Ne(f,h);c=Gi(g)}else p!==21420&&(c=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ne(f,h):p===17545?i=Ne(f,h):p===21420&&c===475249515?u=Ne(f,h):p===374648427?Ht(f,({tag:g,type:y,value:I})=>g===30321?(l=Ne(I,y)===1,!1):!0):s&&n&&Qb.includes(p)&&(o=!0),!o}),Au(e,"Failed to parse webm Segment start"),Au(t,"Failed to parse webm Segment end"),Au(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:l,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},nk=a=>{if(ik(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ok=(a,e)=>{let t=!1,r=!1,i=o=>Yb(o.time)&&Yb(o.position),s=[],n;return Ht(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ne(c,u));break;case 183:break;case 241:n&&(n.position=Ne(c,u));break;default:t&&Qb.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:l}=o,d=s[u+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},uk=a=>{let e=0,t=!1;try{Ht(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):ak.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},zb={validateData:Wb,parseInit:sk,getIndexRange:nk,parseSegments:ok,parseFeedableSegmentChunk:uk};var Ar=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return zb;case"mp4":return Hb}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Cu=Ue(gg(),1);var Mu=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["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as vg,isNullable as yg}from"@vkontakte/videoplayer-shared";var Sg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Tg=a=>{if(!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},jt=(a,e)=>{let t=a;t=(0,Cu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Cu.default)(t,n,(o,u)=>yg(s)?o:yg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Eg=(a,e)=>{var v,T,R,U,$,B,N,O,w,L,q,k,x,V,H,G,z,se,Et,nt,A,ne,Se,xe,ot,Kt,ut,xt,Jt,Br,cc,lc,dc,pc,hc,fc,mc,bc,gc,Sc,vc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(R=(T=(v=s.querySelector("BaseURL"))==null?void 0:v.textContent)==null?void 0:T.trim())!=null?R:"",u=n.children,c=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=l?new Date(l).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],g=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Tg(h);else if(f){let oe=Tg(f);vg(oe)&&(p=oe)}else g&&(p=parseInt(g,10));let y=0,I=($=(U=s.getAttribute("profiles"))==null?void 0:U.split(","))!=null?$:[];for(let oe of u){let DS=(B=oe.getAttribute("id"))!=null?B:"id"+(y++).toString(10),Or=(N=oe.getAttribute("mimeType"))!=null?N:"",Js=(O=oe.getAttribute("codecs"))!=null?O:"",Xs=(w=oe.getAttribute("contentType"))!=null?w:Or==null?void 0:Or.split("/")[0],BS=(q=(L=oe.getAttribute("profiles"))==null?void 0:L.split(","))!=null?q:[],OS=(k=oe.getAttribute("lang"))!=null?k:void 0,VS=(H=(V=(x=oe.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:V.trim())!=null?H:void 0,_S=oe.querySelectorAll("Representation"),NS=oe.querySelector("SegmentTemplate"),FS=(z=(G=oe.querySelector("Role"))==null?void 0:G.getAttribute("value"))!=null?z:void 0,Vr=Xs,J={id:DS,language:OS,isDefault:FS==="main",label:VS,codecs:Js,hdr:Vr==="video"&&Mu(Js),mime:Or,representations:[]};for(let K of _S){let qS=(se=K.getAttribute("lang"))!=null?se:void 0,US=(Et=K.getAttribute("label"))!=null?Et:void 0,HS=(ne=(A=(nt=K.querySelector("BaseURL"))==null?void 0:nt.textContent)==null?void 0:A.trim())!=null?ne:"",Zs=new URL(HS||o,e).toString(),Xt=(Se=K.getAttribute("mimeType"))!=null?Se:Or,ma=(ot=(xe=K.getAttribute("codecs"))!=null?xe:Js)!=null?ot:"",en;if(Xs==="text"){let Pt=K.getAttribute("id")||"",tn=Pt.includes("_auto");en={id:Pt,isAuto:tn,kind:"text",url:Zs}}else{let Pt=(ut=(Kt=K.getAttribute("contentType"))!=null?Kt:Xt==null?void 0:Xt.split("/")[0])!=null?ut:Xs,tn=(Jt=(xt=oe.getAttribute("profiles"))==null?void 0:xt.split(","))!=null?Jt:[],jS=parseInt((Br=K.getAttribute("width"))!=null?Br:"",10),Rc=parseInt((cc=K.getAttribute("height"))!=null?cc:"",10),$c=parseInt((lc=K.getAttribute("bandwidth"))!=null?lc:"",10)/1e3,Lc=(dc=K.getAttribute("frameRate"))!=null?dc:"",GS=(pc=K.getAttribute("quality"))!=null?pc:void 0,WS=Lc?Sg(Lc):void 0,YS=(hc=K.getAttribute("id"))!=null?hc:"id"+(y++).toString(10),QS=Pt==="video"?`${Rc}p`:Pt==="audio"?`${$c}Kbps`:ma,zS=`${YS}@${QS}`,KS=[...I,...BS,...tn],rn,JS=K.querySelector("SegmentBase"),At=(fc=K.querySelector("SegmentTemplate"))!=null?fc:NS;if(JS){let wt=(bc=(mc=K.querySelector("SegmentBase Initialization"))==null?void 0:mc.getAttribute("range"))!=null?bc:"",[kt,sn]=wt.split("-").map(Zt=>parseInt(Zt,10)),ct={from:kt,to:sn},_r=(gc=K.querySelector("SegmentBase"))==null?void 0:gc.getAttribute("indexRange"),[nn,ba]=_r?_r.split("-").map(Zt=>parseInt(Zt,10)):[],Nr=_r?{from:nn,to:ba}:void 0;rn={type:"byteRange",url:Zs,initRange:ct,indexRange:Nr}}else if(At){let wt={representationId:(Sc=K.getAttribute("id"))!=null?Sc:void 0,bandwidth:(vc=K.getAttribute("bandwidth"))!=null?vc:void 0},kt=parseInt((yc=At.getAttribute("timescale"))!=null?yc:"",10),sn=(Tc=At.getAttribute("initialization"))!=null?Tc:"",ct=At.getAttribute("media"),_r=(Ec=parseInt((Ic=At.getAttribute("startNumber"))!=null?Ic:"",10))!=null?Ec:1,nn=jt(sn,wt);if(!ct)throw new ReferenceError("No media attribute in SegmentTemplate");let ba=(xc=At.querySelectorAll("SegmentTimeline S"))!=null?xc:[],Nr=[],Zt=0,on="",un=0;if(ba.length){let ga=_r,De=0;for(let er of ba){let qe=parseInt((Pc=er.getAttribute("d"))!=null?Pc:"",10),Rt=parseInt((Ac=er.getAttribute("r"))!=null?Ac:"",10)||0,Sa=parseInt((wc=er.getAttribute("t"))!=null?wc:"",10);De=Number.isFinite(Sa)?Sa:De;let cn=qe/kt*1e3,ln=De/kt*1e3;for(let va=0;va<Rt+1;va++){let ZS=jt(ct,{...wt,segmentNumber:ga.toString(10),segmentTime:(De+va*qe).toString(10)}),Mc=(ln!=null?ln:0)+va*cn,ev=Mc+cn;ga++,Nr.push({time:{from:Mc,to:ev},url:ZS})}De+=(Rt+1)*qe,Zt+=(Rt+1)*cn}un=De/kt*1e3,on=jt(ct,{...wt,segmentNumber:ga.toString(10),segmentTime:De.toString(10)})}else if(vg(p)){let De=parseInt((kc=At.getAttribute("duration"))!=null?kc:"",10)/kt*1e3,er=Math.ceil(p/De),qe=0;for(let Rt=1;Rt<er;Rt++){let Sa=jt(ct,{...wt,segmentNumber:Rt.toString(10),segmentTime:qe.toString(10)});Nr.push({time:{from:qe,to:qe+De},url:Sa}),qe+=De}un=qe,on=jt(ct,{...wt,segmentNumber:er.toString(10),segmentTime:qe.toString(10)})}let XS={time:{from:un,to:1/0},url:on};rn={type:"template",baseUrl:Zs,segmentTemplateUrl:ct,initUrl:nn,totalSegmentsDurationMs:Zt,segments:Nr,nextSegmentBeyondManifest:XS,timescale:kt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pt||!Xt)continue;let an={video:"video",audio:"audio",text:"text"}[Pt];if(!an)continue;Vr||(Vr=an),en={id:zS,kind:an,segmentReference:rn,profiles:KS,duration:p,bitrate:$c,mime:Xt,codecs:ma,width:jS,height:Rc,fps:WS,quality:GS}}J.language||(J.language=qS),J.label||(J.label=US),J.mime||(J.mime=Xt),J.codecs||(J.codecs=ma),J.hdr||(J.hdr=Vr==="video"&&Mu(ma)),J.representations.push(en)}Vr&&i[Vr].push(J)}return{dynamic:c,liveAvailabilityStartTime:d,duration:p,streams:i}};var Wi=Ue(hi(),1);import{videoSizeToQuality as Uk}from"@vkontakte/videoplayer-shared";var xg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?mt(s):void 0)!=null?o:Uk({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},Pg=({id:a,bitrate:e})=>({id:a,bitrate:e}),xs=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Wi.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Wi.default)(t,-1)},Ag=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Bu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Wi.default)(r.split("."),0),isDefault:i}),Ou=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Wi.default)(i.split("."),0)}),Ps=a=>"url"in a,it=a=>a.type==="template",Yi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var zi=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new Qi(0);this.onLastSegment$=new Qi(!1);this.fullyBuffered$=new Qi(!1);this.playingRepresentation$=new Qi(void 0);this.playingRepresentationInit$=new Qi(void 0);this.error$=new jk;this.gaps=[];this.subscription=new Gk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new tt;this.destroyAbortController=new tt;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=kr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);We(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Ub(this.sourceBuffer),this.subscription.add(Vu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Vu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Gt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,xu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=Ze(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,c<l)}else this.pruneBufferOld(o,n)})),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);We(r,"No init buffer for starting representation"),We(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=kr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);We(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Ce(s)||Ce(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),We(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(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();Nu(n)&&(this.isLive||(i.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=kr(this.destroyAbortController.signal,async function*(e){var u,c;let t=(u=e==null?void 0:e.flatMap(l=>l.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let d=t.find(f=>f.id===l);d&&this.representations.set(l,d);let p=this.representations.get(l);if(!p||!it(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(c=this.switchingToRepresentationId)!=null?c:this.downloadingRepresentationId,i=this.representations.get(r);We(i);let s=this.segments.get(r);We(s,"No segments for starting representation");let n=this.initData.get(r);if(We(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,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));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.dynamic),this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new tt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;if(Ce(e)||Ce(this.downloadingRepresentationId)||Ce(this.playingRepresentationId)||Ce(this.sourceBuffer)||!Ce(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(We(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((c=i==null?void 0:i.time.to)!=null?c:0)-((l=i==null?void 0:i.time.from)!=null?l:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=Ze(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&xu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Ze(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let p=(0,Rr.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&Ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Rr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}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;Nu(t.duration)&&t.duration-r>0&&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=e==null?void 0:e.streams[this.kind].flatMap(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=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!it(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),c=(i=this.segments.get(o.id))!=null?i:[],l=(n=(s=(0,Rr.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(l)>=Math.floor(p.time.from)&&Math.floor(l)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(d+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;We(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!it(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),c=jt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}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&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&p<=r+y||h<=r+y;return(d==="none"||d==="partially_ejected"&&g&&I&&this.sourceBuffer&&!Pi(this.sourceBuffer.buffered,r))&&g&&I});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=c||o<=l);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await kr(o,async function*(){let l=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!l)return;let d=new DataView(l);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=Ar(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Yi(l)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await kr(n,async function*(){let u=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),Vu(window,"online").pipe(Hk()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Yi(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(it(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Rr.default)(e,0).byte.from,to:(0,Rr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!it(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?(c,l)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Gt.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)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=Ar(n.mime).parseFeedableSegmentChunk(c,this.isLive);l!=null&&l.byteLength&&(u.status="partially_fed",o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,c=e.byteLength;for(let l of this.activeSegments){let{segment:d}=l,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:c;if(l.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,g=p?d.byte.to-r:e.byteLength,y=b<i,I=g<=i;if(d.status==="downloading"&&y&&I){d.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+b,h),v=this.getCurrentPosition();Nu(v)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-v,this.bufferAccumulation.accumulated.push({segmentView:S,segmentProgress:l}),this.activeSegments.delete(l));let T=({segmentView:R,segmentProgress:U})=>this.sourceBufferTaskQueue.append(R,s).then($=>$&&!s.aborted?this.onSegmentFullyAppended(U,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(T),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||Ce(v))&&(T({segmentView:S,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&!I&&(l.loadedBytes=Math.min(h,i-b),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+b+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===h?S:Ar(o.mime).parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(d.status="partially_fed",l.feedingBytes+=v.byteLength,this.sourceBufferTaskQueue.append(v,s).then(T=>{if(s.aborted)n();else if(T)l.fedBytes+=v.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let l=c.byte.from-r,d=c.byte.to-r,p=d-l+1,h=l<i,f=d<=i;if(h){if(c.status==="downloading"&&f){c.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+l,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-l),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+l+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?b:Ar(o.mime).parseFeedableSegmentChunk(b);g!=null&&g.byteLength&&(c.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ps(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"&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);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=Tu(()=>(0,wg.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?kr(this.destroyAbortController.signal,async function*(){let o=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ar(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:c,segments:l}=o,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d);let p=l;this.isLive&&it(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:Gt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ce(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((l,d)=>l.from-d.from);let c=[u[0]];for(let l=1;l<u.length;l++){let{from:d,to:p}=u[l],h=c[c.length-1];h.to>=d?h.to=Math.max(h.to,p):c.push(u[l])}return c},o=u=>{var l;if(s>=t)return i;i.push(u.time),i=n(i);let c=Ps(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let l=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let p={time:{from:c,to:l},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>=e+u&&l.status==="fed"&&o(l)}return i.length?(await Promise.all(i.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ce(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=c=>{var d;s=Math.min(s,c.time.from),n=Math.max(n,c.time.to);let l=Ps(c)?(d=c.size)!=null?d:0:c.byte.to-c.byte.from;i+=l};for(let c of this.segments.values())for(let l of c){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;l.status==="fed"&&u(l)}if(o=isFinite(s)&&isFinite(n),!o){i=0,s=1/0,n=-1/0;for(let c of this.segments.values())for(let l of c){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;l.status==="fed"&&u(l)}}if(o=isFinite(s)&&isFinite(n),!o)for(let c=0;c<this.sourceBuffer.buffered.length;c++){let l=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)){s=l,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){i=0,s=1/0,n=-1/0;let c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>e+c&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(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){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Tu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Gt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Ce(this.sourceBuffer)||Ce(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=1;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(l=>l.from-t<=n&&l.to+t>=o),c=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(c.length===1?i.status="partially_ejected":this.gaps.some(l=>l.from===i.time.from||l.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var Ki=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var kg=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}};import{abortable as Ji,assertNever as Rg,fromEvent as $g,merge as Wk,now as Xi,Subscription as Yk,ValueSubject as Fu,flattenObject as $r}from"@vkontakte/videoplayer-shared";var As=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new Fu(void 0);this.lastConnectionReused$=new Fu(void 0);this.lastRequestFirstBytes$=new Fu(void 0);this.abortAllController=new tt;this.subscription=new Yk;this.fetchManifest=Ji(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ki(r));let i=yield et(r,{signal:this.abortAllController.signal}).catch(Zi);return i?(t.log("success",$r({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",$r({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ji(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var O,w;let c=e,l=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{l.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(c,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),c=L.toString();break}default:Rg(t)}this.requestQuic&&(c=Ki(c));let p=this.abortAllController.signal,h;if(n){let L=new tt;if(h=Wk($g(this.abortAllController.signal,"abort"),$g(n,"abort")).subscribe(()=>{try{L.abort()}catch(q){Zi(q)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(q){Zi(q)}p=L.signal}let f=Xi();d.log("startRequest",$r({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield et(c,{priority:s,headers:l,signal:p}).catch(Zi),g=Xi();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(g-f),!b.ok||!b.body){h==null||h.unsubscribe();let L=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:L}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){h==null||h.unsubscribe();let L=Xi(),q={requestStartedAt:f,requestEndedAt:L,duration:L-f};return d.log("endRequest",$r(q)),d.end(),b.arrayBuffer()}let[y,I]=b.body.tee(),S=y.getReader();o&&((w=this.throughputEstimator)==null||w.trackStream(I,u));let v=0,T=new Uint8Array(0),R=!1,U=L=>{h==null||h.unsubscribe(),R=!0,Zi(L)},$=Ji(p,async function*({done:L,value:q}){if(v===0&&this.lastRequestFirstBytes$.next(Xi()-f),p.aborted){h==null||h.unsubscribe();return}if(!L&&q){let k=new Uint8Array(T.length+q.length);k.set(T),k.set(q,T.length),T=k,v+=q.byteLength,i==null||i(new DataView(T.buffer),v),yield S==null?void 0:S.read().then($,U)}}.bind(this));yield S==null?void 0:S.read().then($,U),h==null||h.unsubscribe();let B=Xi(),N={failed:R,requestStartedAt:f,requestEndedAt:B,duration:B-f};return R?(d.error("endRequest",$r(N)),d.end(),null):(d.log("endRequest",$r(N)),d.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ji(this.abortAllController.signal,async function*(e,t,r){var y;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,i),o=Math.max(l,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(y=e.indexRange)!=null?y:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let I=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!I)return null;b=new DataView(I)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ji(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=kg(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Rg(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Zi=a=>{if(!Yi(a))throw a};var Wt=(a,e,t)=>t*e+(1-t)*a,qu=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Lg=(a,e,t,r)=>{let i=0,s=t,n=qu(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};import{isNullable as Qk,ValueSubject as Mg}from"@vkontakte/videoplayer-shared";var gt=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 Mg(e.initial),this.debounced$=new Mg(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new re(`raw_${t}`),this.smoothedSeries$=new re(`smoothed_${t}`),this.reportedSeries$=new re(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(Qk(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 ws=class extends gt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Wt(this.slow,e,this.params.emaAlphaSlow),this.fast=Wt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ks=class extends gt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=qu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Wt(this.emaSmoothed,e,this.params.emaAlpha);let r=Lg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Rs=class extends gt{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?Wt(this.smoothed,t,this.params.emaAlpha):t}};var Yt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ws({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ks({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Rs({initial:e,label:"liveEdgeDelay",...t})}};var Uu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var _g=["timeupdate","progress","play","seeked","stalled","waiting"];var Ms=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Vg;this.representationSubscription=new Vg;this.state$=new M("none");this.currentVideoRepresentation$=new ie(void 0);this.currentVideoRepresentationInit$=new ie(void 0);this.currentAudioRepresentation$=new ie(void 0);this.currentVideoSegmentLength$=new ie(0);this.currentAudioSegmentLength$=new ie(0);this.error$=new Og;this.lastConnectionType$=new ie(void 0);this.lastConnectionReused$=new ie(void 0);this.lastRequestFirstBytes$=new ie(void 0);this.isLive$=new ie(!1);this.liveDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(void 0);this.bufferLength$=new ie(0);this.liveLoadBufferLength$=new ie(0);this.livePositionFromPlayer$=new ie(0);this.timeInWaiting=0;this.isActiveLowLatency$=new ie(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Og;this.gapWatchdogActive=!1;this.destroyController=new tt;this.initManifest=Hu(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:St.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Hu(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:St.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t;try{t=Eg(e!=null?e:"",this.manifestUrlString)}catch(u){let c=(n=Vb(e))!=null?n:{id:"ManifestParsing",category:St.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(c)}if(!t)return null;let r=(u,c,l)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,c)&&((f=(h=rt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${c}; codecs="${l}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let l=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(l.map(({codecs:h})=>h)),p=Ob(d);if(p&&(i[u]=l.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);Zk.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",ea(s)),s}.bind(this));this.initRepresentations=Hu(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",ea({initialVideo:e,initialAudio:t,sourceHls:r})),Qt(this.manifest),Qt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Lr(p,"error").pipe(Ls(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:St.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Sb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&fs())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.tuning.dashCmafLive.lowLatency.isActive);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 zi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Bg(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new zi("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(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(ju(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=eu(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Mr(..._g.filter(p=>p!=="waiting").map(p=>Lr(this.element,p))).pipe(Gu(p=>this.element?Ze(this.element.buffered,this.element.currentTime*1e3):0),Dg(),Ls(p=>!!p),Jk(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Dg()).subscribe(h=>Uu(this.element,1))),this.representationSubscription.add($s({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Ls(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add($s({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b,S=1;Math.abs(I)>g&&(S=1+Math.sign(I)*y),Uu(this.element,S)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let y=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(S=>{var v,T;return(T=(v=S.getLiveSegmentsToLoadState(this.manifest))==null?void 0:v.to)!=null?T:y}))-y}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add($s({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Xk(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(Qt(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=eu(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,T=isFinite(h)?h:f,R=this.isActiveLowLatency$.getValue(),U=y<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(R&&U);let $="none";if(R?$="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&U?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),$="active_low_latency"):g!==0&&T<I?$="live_forward_buffering":T<I+v&&($="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),$==="live_forward_buffering"||$==="live_with_target_offset"){let B=p-(I+S),N=this.normolizeLiveOffset(Math.trunc(g+B/b)),O=Math.abs(N-g),w;!h||O<=this.tuning.dashCmafLive.offsetCalculationError?w=g:N>0&&O>this.tuning.dashCmafLive.offsetCalculationError?w=N:w=0,this.manifestUrlString=ee(this.manifestUrlString,w,2)}$!=="none"&&$!=="active_low_latency"&&(p=0,this.updateLive())}))}let u=Mr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Gu(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Mr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Gu(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Mr(this.forceEnded$,$s({allBuffersFull:u,someBufferEnded:c}).pipe(Ls(({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()}catch(h){this.error$.next({id:"EndOfStream",category:St.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Mr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let l=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),it(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/1e3,this.audioBufferManager&&Bg(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;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ju(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:St.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new As({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=Yt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s,n;Qt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ee(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video)),await((n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio)))}initBuffer(){Qt(this.element),this.state$.setState("running"),this.subscription.add(Mr(..._g.map(e=>Lr(this.element,e)),Lr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:St.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Lr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Lr(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Pi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var n,o;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s={...s,liveLastSeekOffset:this.liveLastSeekOffset};else{let u=this.element.currentTime*1e3;(n=this.videoBufferManager)==null||n.maintain(u),(o=this.audioBufferManager)==null||o.maintain(u),s={...s,position:u}}this.tracer.log("stallIntervalCallback",ea(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=ju(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:St.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u,c;Qt(this.element),Qt(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),Pi(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(c=this.audioBufferManager)==null||c.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",ea({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>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=eR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>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={...t,gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ea(t)))}}};var Cs=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ds=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Ng=`attribute vec2 a_vertex;
38
59
  attribute vec2 a_texel;
39
60
 
40
61
  varying vec2 v_texel;
@@ -45,7 +66,7 @@ void main(void) {
45
66
  // save texel vector to pass to fragment shader
46
67
  v_texel = a_texel;
47
68
  }
48
- `;var wg=`#ifdef GL_ES
69
+ `;var Fg=`#ifdef GL_ES
49
70
  precision highp float;
50
71
  precision highp int;
51
72
  #else
@@ -88,5 +109,5 @@ void main(void) {
88
109
  // sample using new coordinates
89
110
  gl_FragColor = texture2D(u_texture, tc);
90
111
  }
91
- `;var ks=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 As(this.params.fov,this.params.orientation),this.cameraRotationManager=new ws(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(Ag,this.gl.VERTEX_SHADER),r=this.createShader(wg,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,p=e-r,d=t+i;return[s,n,o,u,l,c,p,d]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var jt=class{constructor(e){this.subscription=new iR;this.videoState=new $("stopped");this.elementSize$=new aR(void 0);this.textTracksManager=new Ae;this.droppedFramesManager=new is;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Za;this.textTracks=[];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.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"),E(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"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&E(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"&&E(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"&&E(this.params.desiredState.playbackState,"paused");return;default:return zk(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new ks(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.elementSize$.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=ue(e.container,e.tuning),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(X(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ps({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=de(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Uu.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(kg(l=>!!l.length),$g()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:l})})),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(kg(Zk),$g()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Lg(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Ue(this.video,t.isLooped,i)),this.subscription.add(ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pe(this.video,t.playbackRate,r.playbackRateState$,i)),s(rR(this.video),this.elementSize$),s(ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(Kk(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let d=[];for(let h of c.audio){d.push(Lu(h));let f=[];for(let b of h.representations){let g=pg(b);f.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(d)}let p=[];for(let d of c.video){p.push($u(d));let h=[];for(let f of d.representations){let b=dg(f);b&&(h.push(b),this.videoTracksMap.set(b,{stream:d,representation:f}))}this.videoStreamsMap.set(d,h)}this.params.output.availableVideoStreams$.next(p);for(let d of c.text)for(let h of d.representations){let f=hg(d,h);this.textTracksMap.set(f,{stream:d,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=l=>e.error$.next({id:"RepresentationSwitch",category:Uu.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(Rs(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.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Xk(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[d,h]=p,f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")this.player.initRepresentations(d.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",d.id).catch(n),h){let b=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,b).catch(n)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Hu()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:d}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next($u(d))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Hu()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:d}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Lu(d))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,p;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}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 o=t.playbackState.stateChangeStarted$.pipe(Lg(({to:l})=>l==="ready"),Hu());this.subscription.add(Rs(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Rs(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Rs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,tR(["init"])).pipe(Jk(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var M,A,F,R,L,w,q,K,k,x,V,U,j,z;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(M=e.videoTrack.getState())==null?void 0:M.id,n=[...this.videoTracksMap.keys()].find(({id:_})=>_===i),o=t.currentVideoTrack$.getValue(),u=((R=(F=e.videoStream.getState())!=null?F:n&&((A=this.videoTracksMap.get(n))==null?void 0:A.stream))!=null?R:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:_})=>_===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let p=Je(this.video.buffered,this.video.currentTime*1e3),d=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(p/Math.min(d,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(L=e.audioStream.getState())!=null?L:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(w=[...this.audioStreamsMap.keys()].find(({id:_})=>_===(f==null?void 0:f.id)))!=null?w:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let _=gs(n,c,(q=this.audioStreamsMap.get(b))!=null?q:[]);g=Math.max(g,(K=_==null?void 0:_.bitrate)!=null?K:-1/0)}if(o){let _=gs(o,c,(k=this.audioStreamsMap.get(b))!=null?k:[]);g=Math.max(g,(x=_==null?void 0:_.bitrate)!=null?x:-1/0)}}let y=ft(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:I}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(y=(V=c.filter(_=>!eR(_.quality)).sort((_,Gt)=>{var it,O;return((it=Gt.bitrate)!=null?it:0)-((O=_.bitrate)!=null?O:0)}).filter(_=>Rg(_.quality,y.quality)&&Rg(_.quality,I))[0])!=null?V:y);let S=r?y!=null?y:n:n!=null?n:y,v=b&&gs(S,c,(U=this.audioStreamsMap.get(b))!=null?U:[]),T=(j=this.videoTracksMap.get(S))==null?void 0:j.representation,D=v&&((z=this.audioTracksMap.get(v))==null?void 0:z.representation);if(T&&D)return[T,D];if(T&&!D&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){pe(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Uu.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),le(this.video)}};var Qi=class extends jt{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)}};import{combine as Mg,interval as sR,map as nR}from"@vkontakte/videoplayer-shared";var zi=class extends jt{constructor(e){super(e),this.liveOffset=new ze}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Mg({interval:sR(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:i})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(i-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(Mg({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(nR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$))}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 Dg=Fe(Ka(),1);import{assertNever as Ki,assertNonNullable as Cg,debounce as oR,ErrorCategory as Ls,filter as uR,isNonNullable as lR,isNullable as cR,map as $s,merge as dR,Observable as pR,observableFrom as hR,Subscription as fR,videoSizeToQuality as mR}from"@vkontakte/videoplayer-shared";var _e={};var kr=(a,e)=>new pR(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ji=class{constructor(e){this.subscription=new fR;this.videoState=new $("initializing");this.textTracksManager=new Ae;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:Ki(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ki(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ki(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ki(e)}break;default:Ki(t)}};this.video=ue(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(X(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),le(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Ls.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Dg.default)(import("hls.js").then(i=>{e||(_e.Hls=i.default,_e.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Cg(_e.Hls,"hls.js not loaded"),this.hls=new _e.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Cg(_e.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Ls.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=de(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(Ue(this.video,e.isLooped,r)),this.subscription.add(ce(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Pe(this.video,e.playbackRate,i.playbackRateState$,r)),s(ke(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe($s(l=>l.to)),this.params.output.playbackState$),this.subscription.add(kr(this.hls,_e.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Ls.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"),E(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(kr(this.hls,_e.Events.MANIFEST_PARSED).pipe($s(({levels:l})=>l.reduce((c,p)=>{var I,S;let d=p.name||p.height.toString(10),{width:h,height:f}=p,b=(S=pt((I=p.attrs.QUALITY)!=null?I:""))!=null?S:mR({width:h,height:f});if(!b)return c;let g=p.attrs["FRAME-RATE"]?parseFloat(p.attrs["FRAME-RATE"]):void 0,y={id:d.toString(),quality:b,bitrate:p.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(d,{track:y,level:p}),c.push(y),c},[]))),t.availableVideoTracks$),s(kr(this.hls,_e.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let p of l.subtitleTracks){let d=p.name,h=p.attrs.URI||"",f=p.lang;c.push({id:d,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(kr(this.hls,_e.Events.LEVEL_LOADING).pipe($s(({url:l})=>X(l))),t.hostname$),s(kr(this.hls,_e.Events.FRAG_CHANGED),l=>{var d,h,f,b;let{video:c,audio:p}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((d=c==null?void 0:c.endPTS)!=null?d:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=p==null?void 0:p.endPTS)!=null?f:0)-((b=p==null?void 0:p.startPTS)!=null?b:0))*1e3)}),this.subscription.add(lt(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:p})=>p===l))==null?void 0:c.track},o=kr(this.hls,_e.Events.LEVEL_SWITCHED).pipe($s(({level:l})=>n(this.hls.levels[l])));o.pipe(uR(lR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(lt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(cR(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let p=this.hls.levels.indexOf(c),d=this.hls.currentLevel,h=this.hls.levels[d];!h||c.bitrate>h.bitrate?this.hls.nextLevel=p:(this.hls.loadLevel=p,this.hls.loadLevel=p)},{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=dR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,hR(["init"])).pipe(oR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await pe(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ls.DOM,thrown:t}))||(this.videoState.setState("paused"),E(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"),E(this.params.desiredState.playbackState,"stopped",!0)}};var Og="X-Playback-Duration",ju=async a=>{var i;let e=await Xe(a),t=await e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Og)?parseInt(e.headers.get(Og),10):void 0};import{assertNever as TR,combine as IR,debounce as ER,ErrorCategory as Cs,filter as xR,filterChanged as PR,isNonNullable as Vg,isNullable as Ds,map as _g,merge as AR,observableFrom as wR,Subscription as kR,ValueSubject as Yu,VideoQuality as RR}from"@vkontakte/videoplayer-shared";var Wu=Fe(uo(),1);import{videoSizeToQuality as bR,getExponentialDelay as gR}from"@vkontakte/videoplayer-shared";var SR=a=>{let e=null;if(a.QUALITY&&(e=pt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=bR({width:t,height:r})}return e!=null?e:null},vR=(a,e)=>{var s,n;let t=a.split(`
92
- `),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 p=(0,Wu.default)(l[1].split(",").map(I=>I.split("="))),d=(s=p.QUALITY)!=null?s:`stream-${p.BANDWIDTH}`,h=SR(p),f;p.BANDWIDTH&&(f=parseInt(p.BANDWIDTH,10)/1e3||void 0),!f&&p["AVERAGE-BANDWIDTH"]&&(f=parseInt(p["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=p["FRAME-RATE"]?parseFloat(p["FRAME-RATE"]):void 0,g;if(p.RESOLUTION){let[I,S]=p.RESOLUTION.split("x").map(v=>parseInt(v,10));I&&S&&(g={width:I,height:S})}let y=new URL(t[++o],e).toString();h&&r.push({id:d,quality:h,url:y,bandwidth:f,size:g,fps:b})}if(c){let p=(0,Wu.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),d=(n=p.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=p.LANGUAGE,f=p.NAME;d&&h&&i.push({type:"internal",id:h,label:f,language:h,url:d,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},yR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Gu=0,Bg=async(a,e=a,t)=>{let i=await(await Xe(a)).text();Gu+=1;try{let{qualityManifests:s,textTracks:n}=vR(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(Gu<=t.manifestRetryMaxCount)return await yR(gR(Gu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Bg(a,e,t)}return{qualityManifests:[],textTracks:[]}},Ms=Bg;var Xi=class{constructor(e){this.subscription=new kR;this.videoState=new $("stopped");this.textTracksManager=new Ae;this.manifests$=new Yu([]);this.liveOffset=new ze;this.manifestStartTime$=new Yu(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"),E(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-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(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"&&E(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"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return TR(t)}};var t;this.params=e,this.video=ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:RR.INVARIANT,url:this.params.source.url},Ms(ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Cs.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Cs.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(X(this.params.source.url)),this.maxSeekBackTime$=new Yu((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,p;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(p=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?p:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(d=>d.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Cs.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=de(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pe(this.video,t.playbackRate,i.playbackRateState$,r)),s(ke(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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.subscription.add(this.maxSeekBackTime$.pipe(PR(),_g(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&&Vg(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===p);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(X(d.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(IR({startTime:this.manifestStartTime$.pipe(xR(Vg)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(_g(o=>o.map(({id:u,quality:l,size:c,bandwidth:p,fps:d})=>({id:u,quality:l,size:c,fps:d,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,r));let n=AR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,wR(["init"])).pipe(ER(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),le(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Ds(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:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,d]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(p||""));d&&p&&i.searchParams.set(d,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ee(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ju(n).then(l=>{var c;if(!Ds(l))this.maxSeekBackTime$.next(l);else{let p=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Ds(p)||!isFinite(p))try{Xe(n).then(d=>d.text()).then(d=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(d))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();ju(b).then(g=>{Ds(g)||this.maxSeekBackTime$.next(g)})}})}catch(d){}}})}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Cs.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()}};import{assertNever as LR,debounce as $R,ErrorCategory as Qu,fromEvent as zu,isNonNullable as MR,isNullable as CR,map as Ng,merge as Fg,observableFrom as qg,Subscription as DR,ValueSubject as OR,VideoQuality as BR,clientChecker as VR}from"@vkontakte/videoplayer-shared";var Zi=class{constructor(e){this.subscription=new DR;this.videoState=new $("stopped");this.textTracksManager=new Ae;this.manifests$=new OR([]);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"),E(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:p}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:p*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return LR(t)}};this.params=e,this.video=ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:BR.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(X(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ms(ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Qu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,p;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(p=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?p:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(d=>d.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Qu.WTF,message:"HlsProvider internal logic error",thrown:o})},i=de(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(Ng(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ue(this.video,t.isLooped,r)),this.subscription.add(ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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 p;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&&MR(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(f=>f.id===d);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(X(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}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(Ng(o=>o.map(({id:u,quality:l,size:c,bandwidth:p,fps:d})=>({id:u,quality:l,size:c,fps:d,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,r)),!VR.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Fg(zu(o,"addtrack"),zu(o,"removetrack"),zu(o,"change"),qg(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Fg(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,qg(["init"])).pipe($R(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),le(this.video)}prepare(){var s,n;let e=this.selectManifest();if(CR(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 p=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,p)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Qu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as _R,assertNonNullable as Ug,debounce as NR,ErrorCategory as Hg,isHigher as FR,isHigherOrEqual as qR,isInvariantQuality as jg,isLowerOrEqual as UR,isNonNullable as HR,merge as jR,observableFrom as GR,Subscription as WR,map as YR}from"@vkontakte/videoplayer-shared";var ea=class{constructor(e){this.subscription=new WR;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new Ae;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"),E(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:p}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:p*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"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return _R(e)}};this.params=e,this.video=ue(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(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(Object.values(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:Hg.WTF,message:"MpegProvider internal logic error",thrown:o})},i=de(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(YR(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ue(this.video,t.isLooped,r)),this.subscription.add(ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pe(this.video,t.playbackRate,i.playbackRateState$,r)),s(ke(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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&&HR(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(),p=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==p){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(c),d.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=jR(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,GR(["init"])).pipe(NR(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),le(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Ug(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Ug(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ji(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(X(t))}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Hg.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=Object.values(this.trackUrls).find(p=>!jg(p.track.quality)&&UR(p.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&&qR(c.quality,u.quality)&&(t=u),!t){let p=Object.values(this.trackUrls).filter(h=>!jg(h.track.quality)&&FR(h.track.quality,e)),d=p.length;d&&(t=p[d-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=ft(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput: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})}};import{assertNever as Wg,debounce as JR,merge as Yg,observableFrom as XR,Subscription as ZR,map as Qg,ValueSubject as eL,ErrorCategory as Ju,VideoQuality as tL}from"@vkontakte/videoplayer-shared";import{ErrorCategory as QR}from"@vkontakte/videoplayer-shared";var Gg=["stun:videostun.mycdn.me:80"],zR=1e3,KR=3,Ku=()=>null,Os=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=Ku;this.externalStopCallback=Ku;this.externalErrorCallback=Ku;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Gg}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:QR.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),zR)}normalizeOptions(e={}){let t={stunServerList:Gg,maxRetryNumber:KR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ta=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new eL(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"),E(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"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return Wg(e)}};this.subscription=new ZR,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ue(e.container,e.tuning),this.liveStreamClient=new Os(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.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),le(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ju.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Yg(this.videoState.stateChangeStarted$.pipe(Qg(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Qg(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=de(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(ke(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ce(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return Wg(n.to)}},r)).add(Yg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,XR(["init"])).pipe(JR(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(X(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:tL.INVARIANT}),this.video.srcObject=e,E(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:Ju.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ju.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ra=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}};import{assertNever as sa,assertNonNullable as gt,ErrorCategory as Vs,filter as uL,isNonNullable as eS,isNullable as lL,map as cL,merge as dL,once as pL,Subject as ve,Subscription as tS,ValueSubject as C}from"@vkontakte/videoplayer-shared";import{Observable as rL,map as zg,Subscription as iL,Subject as aL}from"@vkontakte/videoplayer-shared";var Kg=a=>new rL(e=>{let t=new iL,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(zg(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(zg(({type:l})=>l!==void 0)),n=new aL,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()}});import{ErrorCategory as Jg,Subscription as sL,combine as nL,filter as Xg,once as Zg}from"@vkontakte/videoplayer-shared";var ia=null,Bs=null;function Xu(){return ia||(ia=new(window.AudioContext||window.webkitAudioContext)),Bs||(Bs=new GainNode(ia,{gain:1}),Bs.connect(ia.destination)),{audioCtx:ia,gainNode:Bs}}import{clientChecker as oL}from"@vkontakte/videoplayer-shared";var Rr=class Rr{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new sL;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe(Xg(n=>!!n.type),Zg()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){oL.isSafari&&e!=="MPEG"||this.subscriptions.add(nL({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Xg(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),Zg()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:i}=Xu(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Rr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Rr.errorId,category:Jg.VIDEO_PIPELINE,message:(n=o==null?void 0:o.message)!=null?n:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(n=>{var o;this.volumeMultiplierError$.next({id:Rr.errorId,category:Jg.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Xu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Rr.errorId="VolumeMultiplierManager";var aa=Rr;var hL={chunkDuration:5e3,maxParallelRequests:5},na=class{constructor(e){this.current$=new C({type:void 0});this.providerError$=new ve;this.noAvailableProvidersError$=new ve;this.volumeMultiplierError$=new ve;this.providerOutput={position$:new C(0),duration$:new C(1/0),volume$:new C({muted:!1,volume:1}),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableVideoTracks$:new C([]),currentVideoTrack$:new C(void 0),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0),isAudioAvailable$:new C(!0),autoVideoTrackLimitingAvailable$:new C(!1),autoVideoTrackLimits$:new C(void 0),currentBuffer$:new C(void 0),isBuffering$:new C(!0),error$:new ve,warning$:new ve,willSeekEvent$:new ve,seekedEvent$:new ve,loopedEvent$:new ve,endedEvent$:new ve,firstBytesEvent$:new ve,loadedMetadataEvent$:new ve,firstFrameEvent$:new ve,canplay$:new ve,isLive$:new C(void 0),isLowLatency$:new C(!1),canChangePlaybackSpeed$:new C(!0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),inPiP$:new C(!1),inFullscreen$:new C(!1),element$:new C(void 0),elementVisible$:new C(!0),availableSources$:new C(void 0),is3DVideo$:new C(!1),playbackState$:new C("")};this.subscription=new tS;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Tb([...Eb(this.params.tuning),...Ib(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>eS(e.sources[u])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(u=>!i.includes(u)),...t.filter(u=>i.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new ra(s);let n=[...fu(!0),...fu(!1)];this.chromecastFormatsIterator=new ra(n.filter(u=>eS(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new aa(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(lL(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Vs.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.destroyProvider(),this.initProvider()}switchToNextProvider(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"});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}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return sa(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 gt(o),new Qi({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return gt(o),new zi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return gt(o),vr||!this.params.tuning.useHlsJs?new Zi({...n,source:o}):new Ji({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return gt(o),new Xi({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return gt(o),new ea({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return gt(o),new ib({...n,source:o,config:{...hL,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return gt(o),new ta({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 sa(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 gt(o),new si({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 sa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return sa(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 sa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,rS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new tS,t=!1,r=0;return e.add(dL(this.providerOutput.error$,Kg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(cL(i=>({id:`ProviderHangup:${i}`,category:Vs.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(uL(({to:s})=>s==="playing"),pL()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=i.category===Vs.NETWORK,o=i.category===Vs.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}})),e}};import{fromEvent as _s,once as fL,combine as mL,Subscription as iS,ValueSubject as Zu,map as bL,filter as gL,isNonNullable as Ns,now as ye,safeStorage as el}from"@vkontakte/videoplayer-shared";var SL=5e3,aS="one_video_throughput",sS="one_video_rtt",tt=window.navigator.connection,nS=()=>{let a=tt==null?void 0:tt.downlink;if(Ns(a)&&a!==10)return a*1e3},oS=()=>{let a=tt==null?void 0:tt.rtt;if(Ns(a)&&a!==3e3)return a},uS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},tl=class a{constructor(e){this.subscription=new iS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(aS)||(e.useBrowserEstimation?nS():void 0)||SL,r=(s=(i=a.load(sS))!=null?i:e.useBrowserEstimation?oS():void 0)!=null?s:0;if(this.throughput$=new Zu(t),this.rtt$=new Zu(r),this.rttAdjustedThroughput$=new Zu(uS(t,r,e.rttPenaltyRequestSize)),this.throughput=Ut.getSmoothedValue(t,-1,e),this.rtt=Ut.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=nS();u&&this.throughput.next(u);let l=oS();Ns(l)&&this.rtt.next(l)};tt&&"onchange"in tt&&this.subscription.add(_s(tt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{el.set(aS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{el.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(mL({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(bL(({throughput:n,rtt:o})=>uS(n,o,e.rttPenaltyRequestSize)),gL(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=ye(),i=new iS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(_s(e,"progress").pipe(fL()).subscribe(s=>{t=s.loaded,r=ye()}));break;case 1:case 0:i.add(_s(e,"loadstart").subscribe(()=>{t=0,r=ye()}));break}i.add(_s(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=ye(),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=ye(),n=0,o=ye(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:p})=>{if(c)!t&&this.addRawSpeed(i,ye()-s,1),this.concurrentDownloads.delete(e);else if(p){if(t){let d=ye();if(d-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=p.byteLength,s=ye()}else n+=p.byteLength;o=ye()}else i+=p.byteLength,n+=p.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ye()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ye()-o,this.concurrentDownloads.size),n=0,o=ye());await(r==null?void 0:r.read().then(l,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=el.get(e);if(Ns(t))return(r=parseInt(t,10))!=null?r:void 0}},lS=tl;import{fillWithDefault as vL,VideoQuality as cS}from"@vkontakte/videoplayer-shared";var dS={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:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:cS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:cS.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,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{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:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",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,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!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},pS=a=>{var e;return{...vL(a,dS),configName:[...(e=a.configName)!=null?e:[],...dS.configName]}};import{assertNonNullable as Fs,combine as qs,ErrorCategory as Us,filter as oa,filterChanged as $e,fromEvent as il,isNonNullable as AL,isNullable as wL,Logger as kL,map as B,mapTo as bS,merge as St,now as Hs,once as rt,Subject as H,Subscription as gS,tap as SS,ValueSubject as P,isHigher as RL,isInvariantQuality as vS}from"@vkontakte/videoplayer-shared";import{merge as yL,map as TL,filter as hS,isNonNullable as IL}from"@vkontakte/videoplayer-shared";var rl=({seekState:a,position$:e})=>yL(a.stateChangeEnded$.pipe(TL(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),hS(IL)),e.pipe(hS(()=>a.getState().state==="none")));import{assertNonNullable as EL}from"@vkontakte/videoplayer-shared";var fS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return EL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as xL,once as PL}from"@vkontakte/videoplayer-shared";var mS=(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(xL(i=>i.length>0),PL()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var js=class{constructor(e={configName:[]}){this.subscription=new gS;this.logger=new kL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new $("stopped"),seekState:new $({state:"none"}),volume:new $({volume:1,muted:!1}),videoTrack:new $(void 0),videoStream:new $(void 0),audioStream:new $(void 0),autoVideoTrackSwitching:new $(!0),autoVideoTrackLimits:new $({}),isLooped:new $(!1),playbackRate:new $(1),externalTextTracks:new $([]),internalTextTracks:new $([]),currentTextTrack:new $(void 0),textTrackCuesSettings:new $({}),cameraOrientation:new $({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,firstBytes$:new H,loadedMetadata$:new H,firstFrame$:new H,canplay$:new H,log$:new H};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Hm};if(this.initLogs(),this.tuning=pS(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ma({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new lS(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,i)=>{let s=Reflect.get(t,r,i);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let u=n.map(p=>JSON.stringify(p,(d,h)=>{let f=typeof h;return["number","string","boolean"].includes(f)?h:h===null?null:`<${f}>`})),l=`Player.${String(r)}`,c=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:Us.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,i;return this.config=e,this.domContainer=fS(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new na({sources:e.sources,meta:(r=e.meta)!=null?r:{},failoverHosts:(i=e.failoverHosts)!=null?i:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;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()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!fi()?il(document,"visibilitychange").pipe(rt()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue();return e>=r&&!i&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return 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.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){Fs(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(oa(r=>r.length>0),rt()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Fs(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return mS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(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(wL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return AL(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(St(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(B(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(oa(({from:e})=>e==="stopped"),rt()).subscribe(()=>{this.initedAt=Hs(),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();n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Us.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(B(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(B(n=>n.destination),$e()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(B(n=>n.map(({quality:o})=>o).sort((o,u)=>vS(o)?1:vS(u)?-1:RL(u,o)?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$.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$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe($e()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe($e()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe($e()).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(B(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(qs({hasLiveOffsetByPaused:St(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(B(n=>n.to),$e(),B(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(qs({atLiveEdge:qs({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:rl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(B(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),$e(),SS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(B(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(qs({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(B(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),$e(),SS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(B(n=>n.muted),$e()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(B(n=>n.volume),$e()).subscribe(this.info.volume$)).add(rl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(St(e.providerOutput.endedEvent$.pipe(bS(!0)),e.providerOutput.seekedEvent$.pipe(bS(!1))).pipe($e()).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(B(n=>({id:n?`No${n}`:"NoProviders",category:Us.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.firstBytesEvent$.pipe(rt(),B(n=>n!=null?n:Hs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(rt(),B(()=>Hs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(rt(),B(()=>Hs()-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 P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(oa(({to:n})=>n==="playing"),rt()).subscribe(()=>r.next(!1)));let i=0,s=St(e.providerOutput.isBuffering$,t,r).pipe(B(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),$e());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(St(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(St(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(),p;c==="CONNECTED"?p="second_screen":u?l?n?p="pip":o?p="fullscreen":p="inline":p="invisible":p="none",this.info.surface$.getValue()!==p&&this.info.surface$.next(p)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(B(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 gS;this.subscription.add(t),this.subscription.add(e.current$.pipe($e((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(oa(r=>r.length>0),rt()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t,r=(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=ft(e,{container:this.domContainer.getBoundingClientRect(),throughput: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(St(this.desiredState.videoTrack.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(B(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;Fs(this.providerContainer),Fs(e),Um(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>qm(r)),this.providerContainer.current$.subscribe(({type:r})=>li("provider",r)),e.duration$.subscribe(r=>li("duration",r)),e.availableVideoTracks$.pipe(oa(r=>!!r.length),rt()).subscribe(r=>li("tracks",r)),this.events.fatalError$.subscribe(new re("fatalError")),this.events.managedError$.subscribe(new re("managedError")),e.position$.subscribe(new re("position")),e.currentVideoTrack$.pipe(B(r=>r==null?void 0:r.quality)).subscribe(new re("quality")),this.info.currentBuffer$.subscribe(new re("buffer")),e.isBuffering$.subscribe(new re("isBuffering"))].forEach(r=>this.subscription.add(r)),li("codecs",yb())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Us.DOM,message:String(i)})})};this.subscription.add(St(il(document,"visibilitychange"),il(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);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as sG,Observable as nG,Subject as oG,ValueSubject as uG,VideoQuality as lG}from"@vkontakte/videoplayer-shared";var cG=`@vkontakte/videoplayer-core@${Rl}`;export{ha as ChromecastState,sn as HttpConnectionType,nG as Observable,ne as PlaybackState,js as Player,cG as SDK_VERSION,oG as Subject,sG as Subscription,nn as Surface,Rl as VERSION,uG as ValueSubject,ot as VideoFormat,lG as VideoQuality};
112
+ `;var Bs=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 Cs(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ds(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(Ng,this.gl.VERTEX_SHADER),r=this.createShader(Fg,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,c=e+r,l=t+i,d=e-r,p=t+i;return[s,n,o,u,c,l,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 zt=class{constructor(e){this.subscription=new pR;this.videoState=new M("stopped");this.elementSize$=new hR(void 0);this.textTracksManager=new Re;this.droppedFramesManager=new ls;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new mi;this.audioTrackSwitchHistory=new mi;this.textTracks=[];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 c=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-c,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),E(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"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&E(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"&&E(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"&&E(this.params.desiredState.playbackState,"paused");return;default:return sR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Bs(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.elementSize$.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=le(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(X(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ms({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=he(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Wu.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(qg(c=>!!c.length),Hg()).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})})),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(qg(cR),Hg()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Ug(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(je(this.video,t.isLooped,i)),this.subscription.add(pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ke(this.video,t.playbackRate,r.playbackRateState$,i)),s(dR(this.video),this.elementSize$),s(Le(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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 l=this.player.getStreams();if(nR(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of l.audio){p.push(Bu(h));let f=[];for(let b of h.representations){let g=Pg(b);f.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of l.video){d.push(Ou(p));let h=[];for(let f of p.representations){let b=xg(f);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of l.text)for(let h of p.representations){let f=Ag(p,h);this.textTracksMap.set(f,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=c=>e.error$.next({id:"RepresentationSwitch",category:Wu.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(Os(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.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,uR(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),l=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||l)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),c==="manifest_ready")this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let b=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,b).catch(n)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Yu()).subscribe(c=>{let l=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===c);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=l,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Ou(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Yu()).subscribe(c=>{let l=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===c);if(!l){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=l,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Bu(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var l,d;if(c!=null&&c.is3dVideo&&((l=this.params.tuning.spherical)!=null&&l.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Ug(({to:c})=>c==="ready"),Yu());this.subscription.add(Os(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Os(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Os(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,lR(["init"])).pipe(oR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var R,U,$,B,N,O,w,L,q,k,x,V,H,G,z,se,Et,nt;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(R=e.videoTrack.getState())==null?void 0:R.id,n=[...this.videoTracksMap.keys()].find(({id:A})=>A===i),o=t.currentVideoTrack$.getValue(),u=((B=($=e.videoStream.getState())!=null?$:n&&((U=this.videoTracksMap.get(n))==null?void 0:U.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let c=[...this.videoStreamsMap.keys()].find(({id:A})=>A===u.id),l=c&&this.videoStreamsMap.get(c);if(!l)return;let d=Ze(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),f=(N=e.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(O=[...this.audioStreamsMap.keys()].find(({id:A})=>A===(f==null?void 0:f.id)))!=null?O:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let A=ns(n,l,(w=this.audioStreamsMap.get(b))!=null?w:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(L=A==null?void 0:A.bitrate)!=null?L:-1/0)}else{let A=xs(n,l,(q=this.audioStreamsMap.get(b))!=null?q:[]);g=Math.max(g,(k=A==null?void 0:A.bitrate)!=null?k:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let A=ns(o,l,(x=this.audioStreamsMap.get(b))!=null?x:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(V=A==null?void 0:A.bitrate)!=null?V:-1/0)}else{let A=xs(o,l,(H=this.audioStreamsMap.get(b))!=null?H:[]);g=Math.max(g,(G=A==null?void 0:A.bitrate)!=null?G:-1/0)}}let y=bt(l,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),I=r?y!=null?y:n:n!=null?n:y,S;this.params.tuning.useSeparateAudioVideoABR?S=b&&ab(I,l,(z=this.audioStreamsMap.get(b))!=null?z:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):S=b&&xs(I,l,(se=this.audioStreamsMap.get(b))!=null?se:[]);let v=(Et=this.videoTracksMap.get(I))==null?void 0:Et.representation,T=S&&((nt=this.audioTracksMap.get(S))==null?void 0:nt.representation);if(v&&T)return[v,T];if(v&&!T&&this.audioTracksMap.size===0)return[v,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){me(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Wu.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),de(this.video),this.tracer.end()}};var ra=class extends zt{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)}};import{combine as jg,interval as fR,map as mR}from"@vkontakte/videoplayer-shared";var ia=class extends zt{constructor(e){super(e),this.liveOffset=new Je}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(jg({interval:fR(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:i})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(i-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(jg({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(mR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$))}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 Wg=Ue(is(),1);import{assertNever as aa,assertNonNullable as Gg,debounce as bR,ErrorCategory as Vs,filter as gR,isNonNullable as SR,isNullable as vR,map as _s,merge as yR,Observable as TR,observableFrom as IR,Subscription as ER,videoSizeToQuality as xR}from"@vkontakte/videoplayer-shared";var Fe={};var Cr=(a,e)=>new TR(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),sa=class{constructor(e){this.subscription=new ER;this.videoState=new M("initializing");this.textTracksManager=new Re;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:aa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:aa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:aa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:aa(e)}break;default:aa(t)}};this.video=le(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(X(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),de(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Vs.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Wg.default)(import("hls.js").then(i=>{e||(Fe.Hls=i.default,Fe.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Gg(Fe.Hls,"hls.js not loaded"),this.hls=new Fe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Gg(Fe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=c=>{t.error$.next({id:"HlsJsProvider",category:Vs.WTF,message:"HlsJsProvider internal logic error",thrown:c})},i=he(this.video),s=(c,l)=>this.subscription.add(c.subscribe(l,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(je(this.video,e.isLooped,r)),this.subscription.add(pe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ke(this.video,e.playbackRate,i.playbackRateState$,r)),s(Le(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(_s(c=>c.to)),this.params.output.playbackState$),this.subscription.add(Cr(this.hls,Fe.Events.ERROR).subscribe(c=>{var l;c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:Vs.WTF,message:`HlsJs fatal ${c.type} ${c.details}, ${(l=c.err)==null?void 0:l.message} ${c.reason}`,thrown:c.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var c;((c=this.videoState.getTransition())==null?void 0:c.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Cr(this.hls,Fe.Events.MANIFEST_PARSED).pipe(_s(({levels:c})=>c.reduce((l,d)=>{var I,S;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(S=mt((I=d.attrs.QUALITY)!=null?I:""))!=null?S:xR({width:h,height:f});if(!b)return l;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,y={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:y,level:d}),l.push(y),l},[]))),t.availableVideoTracks$),s(Cr(this.hls,Fe.Events.MANIFEST_PARSED),c=>{if(c.subtitleTracks.length>0){let l=[];for(let d of c.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;l.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(l)}}),s(Cr(this.hls,Fe.Events.LEVEL_LOADING).pipe(_s(({url:c})=>X(c))),t.hostname$),s(Cr(this.hls,Fe.Events.FRAG_CHANGED),c=>{var p,h,f,b;let{video:l,audio:d}=c.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=l==null?void 0:l.endPTS)!=null?p:0)-((h=l==null?void 0:l.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(pt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,c=>{this.hls.nextLevel=c?-1:this.hls.currentLevel,this.hls.loadLevel=c?-1:this.hls.loadLevel},{onError:r}));let n=c=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:d})=>d===c))==null?void 0:l.track},o=Cr(this.hls,Fe.Events.LEVEL_SWITCHED).pipe(_s(({level:c})=>n(this.hls.levels[c])));o.pipe(gR(SR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(pt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),c=>{var f;if(vR(c))return;let l=(f=this.trackLevels.get(c.id))==null?void 0:f.level;if(!l)return;let d=this.hls.levels.indexOf(l),p=this.hls.currentLevel,h=this.hls.levels[p];!h||l.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=yR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,IR(["init"])).pipe(bR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await me(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Vs.DOM,thrown:t}))||(this.videoState.setState("paused"),E(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"),E(this.params.desiredState.playbackState,"stopped",!0)}};var Yg="X-Playback-Duration",Qu=async a=>{var i;let e=await et(a),t=await e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Yg)?parseInt(e.headers.get(Yg),10):void 0};import{assertNever as $R,combine as LR,debounce as MR,ErrorCategory as Fs,filter as CR,filterChanged as DR,isNonNullable as zg,isNullable as qs,map as Kg,merge as BR,observableFrom as OR,Subscription as VR,ValueSubject as Ju,VideoQuality as _R}from"@vkontakte/videoplayer-shared";var Ku=Ue(mo(),1);import{videoSizeToQuality as PR,getExponentialDelay as AR}from"@vkontakte/videoplayer-shared";var wR=a=>{let e=null;if(a.QUALITY&&(e=mt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=PR({width:t,height:r})}return e!=null?e:null},kR=(a,e)=>{var s,n;let t=a.split(`
113
+ `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],c=u.match(/^#EXT-X-STREAM-INF:(.+)/),l=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!l)){if(c){let d=(0,Ku.default)(c[1].split(",").map(I=>I.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=wR(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[I,S]=d.RESOLUTION.split("x").map(v=>parseInt(v,10));I&&S&&(g={width:I,height:S})}let y=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:y,bandwidth:f,size:g,fps:b})}if(l){let d=(0,Ku.default)(l[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},RR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),zu=0,Qg=async(a,e=a,t)=>{let i=await(await et(a)).text();zu+=1;try{let{qualityManifests:s,textTracks:n}=kR(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(zu<=t.manifestRetryMaxCount)return await RR(AR(zu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Qg(a,e,t)}return{qualityManifests:[],textTracks:[]}},Ns=Qg;var na=class{constructor(e){this.subscription=new VR;this.videoState=new M("stopped");this.textTracksManager=new Re;this.manifests$=new Ju([]);this.liveOffset=new Je;this.manifestStartTime$=new Ju(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"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(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"&&E(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 l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return $R(t)}};var t;this.params=e,this.video=le(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:_R.INVARIANT,url:this.params.source.url},Ns(ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Fs.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Fs.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(X(this.params.source.url)),this.maxSeekBackTime$=new Ju((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,c,l,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(l=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?l:(c=t.getState())==null?void 0:c.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=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:Fs.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=he(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(pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ke(this.video,t.playbackRate,i.playbackRateState$,r)),s(Le(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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.subscription.add(this.maxSeekBackTime$.pipe(DR(),Kg(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(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&zg(c.to)){let d=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(X(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,c,l;let o=(l=(c=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:c.call(u))==null?void 0:l.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(LR({startTime:this.manifestStartTime$.pipe(CR(zg)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Kg(o=>o.map(({id:u,quality:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=BR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,OR(["init"])).pipe(MR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),de(this.video)}prepare(){var o,u;let e=this.selectManifest();if(qs(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:l}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[c,"mq"],[l,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ee(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Qu(n).then(c=>{var l;if(!qs(c))this.maxSeekBackTime$.next(c);else{let d=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();if(qs(d)||!isFinite(d))try{et(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();Qu(b).then(g=>{qs(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){me(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Fs.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()}};import{assertNever as NR,debounce as FR,ErrorCategory as Xu,fromEvent as Zu,isNonNullable as qR,isNullable as UR,map as Jg,merge as Xg,observableFrom as Zg,Subscription as HR,ValueSubject as jR,VideoQuality as GR,clientChecker as WR}from"@vkontakte/videoplayer-shared";var oa=class{constructor(e){this.subscription=new HR;this.videoState=new M("stopped");this.textTracksManager=new Re;this.manifests$=new jR([]);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"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return NR(t)}};this.params=e,this.video=le(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:GR.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(X(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ns(ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Xu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,c,l,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(l=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?l:(c=t.getState())==null?void 0:c.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=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:Xu.WTF,message:"HlsProvider internal logic error",thrown:o})},i=he(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(Jg(o=>o.to)),this.params.output.playbackState$),this.subscription.add(je(this.video,t.isLooped,r)),this.subscription.add(pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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 d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&qR(c.to)){let p=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let h=this.manifests$.getValue().find(f=>f.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(X(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Jg(o=>o.map(({id:u,quality:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!WR.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Xg(Zu(o,"addtrack"),Zu(o,"removetrack"),Zu(o,"change"),Zg(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Xg(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Zg(["init"])).pipe(FR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),de(this.video)}prepare(){var s,n;let e=this.selectManifest();if(UR(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[c,l]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(c||""));l&&c&&i.searchParams.set(l,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){me(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Xu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as YR,assertNonNullable as eS,debounce as QR,ErrorCategory as tS,isHigher as zR,isHigherOrEqual as KR,isInvariantQuality as rS,isLowerOrEqual as JR,isNonNullable as XR,merge as ZR,observableFrom as e$,Subscription as t$,map as r$}from"@vkontakte/videoplayer-shared";var ua=class{constructor(e){this.subscription=new t$;this.videoState=new M("stopped");this.trackUrls={};this.textTracksManager=new Re;this.syncPlayback=()=>{var u,c,l;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"),E(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)!==((l=(c=this.trackUrls[n.to.id])==null?void 0:c.track)==null?void 0:l.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"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return YR(e)}};this.params=e,this.video=le(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(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(Object.values(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:tS.WTF,message:"MpegProvider internal logic error",thrown:o})},i=he(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(r$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(je(this.video,t.isLooped,r)),this.subscription.add(pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ke(this.video,t.playbackRate,i.playbackRateState$,r)),s(Le(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,c;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&XR(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),d=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(l!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(l),p.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=ZR(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,e$(["init"])).pipe(QR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),de(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;eS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];eS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ki(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(X(t))}playIfAllowed(){me(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tS.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=Object.values(this.trackUrls).find(d=>!rS(d.track.quality)&&JR(d.track.quality,e)))==null?void 0:s.track,c=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,l=(o=this.trackUrls[c!=null?c:"0"])==null?void 0:o.track;if(u&&l&&KR(l.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!rS(h.track.quality)&&zR(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(c=>c.track);t=bt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput: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})}};import{assertNever as aS,debounce as n$,merge as sS,observableFrom as o$,Subscription as u$,map as nS,ValueSubject as c$,ErrorCategory as tc,VideoQuality as l$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as i$}from"@vkontakte/videoplayer-shared";var iS=["stun:videostun.mycdn.me:80"],a$=1e3,s$=3,ec=()=>null,Us=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=ec;this.externalStopCallback=ec;this.externalErrorCallback=ec;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:iS}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:i$.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),a$)}normalizeOptions(e={}){let t={stunServerList:iS,maxRetryNumber:s$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ca=class{constructor(e){this.videoState=new M("stopped");this.maxSeekBackTime$=new c$(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"),E(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"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return aS(e)}};this.subscription=new u$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=le(e.container,e.tuning),this.liveStreamClient=new Us(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.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),de(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:tc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};sS(this.videoState.stateChangeStarted$.pipe(nS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(nS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=he(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(Le(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(pe(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 aS(n.to)}},r)).add(sS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,o$(["init"])).pipe(n$(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(X(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:l$.INVARIANT}),this.video.srcObject=e,E(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:tc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){me(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var la=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}};import{assertNever as ha,assertNonNullable as vt,ErrorCategory as js,filter as g$,isNonNullable as pS,isNullable as S$,map as v$,merge as y$,once as T$,Subject as Ie,Subscription as hS,ValueSubject as C,flattenObject as fS}from"@vkontakte/videoplayer-shared";import{Observable as d$,map as oS,Subscription as p$,Subject as h$}from"@vkontakte/videoplayer-shared";var uS=a=>new d$(e=>{let t=new p$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(oS(({from:c,to:l})=>`${c}-${l}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(oS(({type:c})=>c!==void 0)),n=new h$,o=0,u="unknown";return t.add(r.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(c=>{o&&(window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as cS,Subscription as f$,combine as m$,filter as lS,once as dS}from"@vkontakte/videoplayer-shared";var da=null,Hs=null;function rc(){return da||(da=new(window.AudioContext||window.webkitAudioContext)),Hs||(Hs=new GainNode(da,{gain:1}),Hs.connect(da.destination)),{audioCtx:da,gainNode:Hs}}import{clientChecker as b$}from"@vkontakte/videoplayer-shared";var Dr=class Dr{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new f$;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe(lS(n=>!!n.type),dS()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){b$.isSafari&&e!=="MPEG"||this.subscriptions.add(m$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(lS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),dS()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:i}=rc(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Dr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Dr.errorId,category:cS.VIDEO_PIPELINE,message:(n=o==null?void 0:o.message)!=null?n:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(n=>{var o;this.volumeMultiplierError$.next({id:Dr.errorId,category:cS.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=rc();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Dr.errorId="VolumeMultiplierManager";var pa=Dr;var I$={chunkDuration:5e3,maxParallelRequests:5},fa=class{constructor(e){this.current$=new C({type:void 0});this.providerError$=new Ie;this.noAvailableProvidersError$=new Ie;this.volumeMultiplierError$=new Ie;this.providerOutput={position$:new C(0),duration$:new C(1/0),volume$:new C({muted:!1,volume:1}),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableVideoTracks$:new C([]),currentVideoTrack$:new C(void 0),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0),isAudioAvailable$:new C(!0),autoVideoTrackLimitingAvailable$:new C(!1),autoVideoTrackLimits$:new C(void 0),currentBuffer$:new C(void 0),isBuffering$:new C(!0),error$:new Ie,warning$:new Ie,willSeekEvent$:new Ie,seekedEvent$:new Ie,loopedEvent$:new Ie,endedEvent$:new Ie,firstBytesEvent$:new Ie,loadedMetadataEvent$:new Ie,firstFrameEvent$:new Ie,canplay$:new Ie,isLive$:new C(void 0),isLowLatency$:new C(!1),canChangePlaybackSpeed$:new C(!0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),inPiP$:new C(!1),inFullscreen$:new C(!1),element$:new C(void 0),elementVisible$:new C(!0),availableSources$:new C(void 0),is3DVideo$:new C(!1),playbackState$:new C("")};this.subscription=new hS;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Cb([...Bb(this.params.tuning),...Db(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>pS(e.sources[u])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(u=>!i.includes(u)),...t.filter(u=>i.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",fS(s)),this.screenFormatsIterator=new la(s);let n=[...yu(!0),...yu(!1)];this.chromecastFormatsIterator=new la(n.filter(u=>pS(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new pa(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy(),this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(S$(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:js.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 ha(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 vt(o),new ra({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return vt(o),new ia({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return vt(o),Er||!this.params.tuning.useHlsJs?new oa({...n,source:o}):new sa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return vt(o),new na({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return vt(o),new ua({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return vt(o),new mb({...n,source:o,config:{...I$,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return vt(o),new ca({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 ha(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 vt(o),new li({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 ha(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ha(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 ha(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,mS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new hS,t=!1,r=0;return e.add(y$(this.providerOutput.error$,uS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(v$(i=>({id:`ProviderHangup:${i}`,category:js.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(g$(({to:s})=>s==="playing"),T$()).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===js.NETWORK,u=i.category===js.FATAL,c=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!u,d=c&&!u&&(o&&t||!l);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:c,tryFailover:d,canReinitProvider:l},d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",fS(n))})),e}};import{fromEvent as Gs,once as E$,combine as x$,Subscription as bS,ValueSubject as ic,map as P$,filter as A$,isNonNullable as Ws,now as Ee,safeStorage as ac}from"@vkontakte/videoplayer-shared";var w$=5e3,gS="one_video_throughput",SS="one_video_rtt",at=window.navigator.connection,vS=()=>{let a=at==null?void 0:at.downlink;if(Ws(a)&&a!==10)return a*1e3},yS=()=>{let a=at==null?void 0:at.rtt;if(Ws(a)&&a!==3e3)return a},TS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},sc=class a{constructor(e){this.subscription=new bS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(gS)||(e.useBrowserEstimation?vS():void 0)||w$,r=(s=(i=a.load(SS))!=null?i:e.useBrowserEstimation?yS():void 0)!=null?s:0;if(this.throughput$=new ic(t),this.rtt$=new ic(r),this.rttAdjustedThroughput$=new ic(TS(t,r,e.rttPenaltyRequestSize)),this.throughput=Yt.getSmoothedValue(t,-1,e),this.rtt=Yt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=vS();u&&this.throughput.next(u);let c=yS();Ws(c)&&this.rtt.next(c)};at&&"onchange"in at&&this.subscription.add(Gs(at,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{ac.set(gS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{ac.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(x$({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(P$(({throughput:n,rtt:o})=>TS(n,o,e.rttPenaltyRequestSize)),A$(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=Ee(),i=new bS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Gs(e,"progress").pipe(E$()).subscribe(s=>{t=s.loaded,r=Ee()}));break;case 1:case 0:i.add(Gs(e,"loadstart").subscribe(()=>{t=0,r=Ee()}));break}i.add(Gs(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ee(),u=n-t,c=o-r;this.addRawSpeed(u,c,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=Ee(),n=0,o=Ee(),u=l=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},c=async({done:l,value:d})=>{if(l)!t&&this.addRawSpeed(i,Ee()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Ee();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=Ee()}else n+=d.byteLength;o=Ee()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ee()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ee()-o,this.concurrentDownloads.size),n=0,o=Ee());await(r==null?void 0:r.read().then(c,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(c,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=ac.get(e);if(Ws(t))return(r=parseInt(t,10))!=null?r:void 0}},IS=sc;import{fillWithDefault as k$,VideoQuality as ES}from"@vkontakte/videoplayer-shared";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:1.8,bitrateAudioFactorAtEmptyBuffer:7,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:5,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:ES.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ES.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,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{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:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",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,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!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},PS=a=>{var e;return{...k$(a,xS),configName:[...(e=a.configName)!=null?e:[],...xS.configName]}};import{assertNonNullable as Ys,combine as yt,ErrorCategory as Qs,filter as ae,filterChanged as _,fromEvent as oc,isNonNullable as B$,isNullable as O$,Logger as V$,map as D,mapTo as RS,merge as Tt,now as zs,once as st,Subject as j,Subscription as $S,tap as LS,ValueSubject as P,isHigher as _$,isInvariantQuality as MS,flattenObject as It,throttle as uc,getTraceSubscriptionMethod as CS,Tracer as N$}from"@vkontakte/videoplayer-shared";import{merge as R$,map as $$,filter as AS,isNonNullable as L$}from"@vkontakte/videoplayer-shared";var nc=({seekState:a,position$:e})=>R$(a.stateChangeEnded$.pipe($$(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),AS(L$)),e.pipe(AS(()=>a.getState().state==="none")));import{assertNonNullable as M$}from"@vkontakte/videoplayer-shared";var wS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return M$(e,`Wrong container or containerId {${a.container}}`),e};import{filter as C$,once as D$}from"@vkontakte/videoplayer-shared";var 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(C$(i=>i.length>0),D$()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Ks=class{constructor(e={configName:[]},t=N$.createRootTracer(!1)){this.subscription=new $S;this.logger=new V$;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new M("stopped"),seekState:new M({state:"none"}),volume:new M({volume:1,muted:!1}),videoTrack:new M(void 0),videoStream:new M(void 0),audioStream:new M(void 0),autoVideoTrackSwitching:new M(!0),autoVideoTrackLimits:new M({}),isLooped:new M(!1),playbackRate:new M(1),externalTextTracks:new M([]),internalTextTracks:new M([]),currentTextTrack:new M(void 0),textTrackCuesSettings:new M({}),cameraOrientation:new M({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,firstBytes$:new j,loadedMetadata$:new j,firstFrame$:new j,canplay$:new j,log$:new j};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Qm};if(this.initLogs(),this.tuning=PS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ia({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new IS(this.tuning.throughputEstimator),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 c=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),l=`Player.${String(i)}`,d=`Exception calling ${l} (${c.join(", ")})`;throw this.events.fatalError$.next({id:l,category:Qs.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var t,r,i;return this.config=e,this.tracer.log("initVideo",It(e)),this.domContainer=wS(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new fa({sources:e.sources,meta:(r=e.meta)!=null?r:{},failoverHosts:(i=e.failoverHosts)!=null?i:[],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.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;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()}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&&!yi()?(this.tracer.log("request play from hidden tab"),oc(document,"visibilitychange").pipe(st()).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){Ys(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.providerContainer.providerOutput.availableVideoTracks$.pipe(ae(r=>r.length>0),st()).subscribe(r=>{this.setVideoTrackIdByQuality(r,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",It(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Ys(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",It(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({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",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}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(O$(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return B$(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(Tt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ae(({from:e})=>e==="stopped"),st()).subscribe(()=>{this.initedAt=zs(),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",It(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Qs.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",It(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(D(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(D(n=>n.destination),_()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(D(n=>n.map(({quality:o})=>o).sort((o,u)=>MS(o)?1:MS(u)?-1:_$(u,o)?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(_()).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(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(_()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(_()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(_()).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(D(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(yt({hasLiveOffsetByPaused:Tt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(n=>n.to),_(),D(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(yt({atLiveEdge:yt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:nc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(D(({isLive:n,position:o,isLowLatency:u})=>{let c=this.getActiveLiveDelay(u);return n&&Math.abs(o)<c/1e3}),_(),LS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(D(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(yt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(D(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),_(),LS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(D(n=>n.muted),_()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(D(n=>n.volume),_()).subscribe(this.info.volume$)).add(nc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Tt(e.providerOutput.endedEvent$.pipe(RS(!0)),e.providerOutput.seekedEvent$.pipe(RS(!1))).pipe(_()).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(D(n=>({id:n?`No${n}`:"NoProviders",category:Qs.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.firstBytesEvent$.pipe(st(),D(n=>n!=null?n:zs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(st(),D(()=>zs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(st(),D(()=>zs()-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 P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ae(({to:n})=>n==="playing"),st()).subscribe(()=>r.next(!1)));let i=0,s=Tt(e.providerOutput.isBuffering$,t,r).pipe(D(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),_());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(Tt(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,c;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(c=n==null?void 0:n.size)==null?void 0:c.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(Tt(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(),c=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),d;l==="CONNECTED"?d="second_screen":u?c?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(D(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 $S;this.subscription.add(t),this.subscription.add(e.current$.pipe(_((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ae(r=>r.length>0),st()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t,r=(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=bt(e,{container:this.domContainer.getBoundingClientRect(),throughput: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(Tt(this.desiredState.videoTrack.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(D(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;Ys(this.providerContainer),Ys(e),Ym(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Wm(r)),this.providerContainer.current$.subscribe(({type:r})=>fi("provider",r)),e.duration$.subscribe(r=>fi("duration",r)),e.availableVideoTracks$.pipe(ae(r=>!!r.length),st()).subscribe(r=>fi("tracks",r)),this.events.fatalError$.subscribe(new re("fatalError")),this.events.managedError$.subscribe(new re("managedError")),e.position$.subscribe(new re("position")),e.currentVideoTrack$.pipe(D(r=>r==null?void 0:r.quality)).subscribe(new re("quality")),this.info.currentBuffer$.subscribe(new re("buffer")),e.isBuffering$.subscribe(new re("isBuffering"))].forEach(r=>this.subscription.add(r)),fi("codecs",Mb())}initTracerSubscription(){let e=CS(this.tracer.log.bind(this.tracer)),t=CS(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(_()).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(yt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ae(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),_((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ae(r=>r>0),_()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ae(r=>r>0),_()).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(yt({currentBuffer:this.info.currentBuffer$.pipe(ae(r=>r.end>0),_((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(_())}).pipe(uc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(_()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(_()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(_()).subscribe(e("canChangePlaybackSpeed"))).add(yt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ae(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),uc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(_(),ae(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(_(),ae(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(_()).subscribe(e("muted"))).add(this.info.volume$.pipe(_()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(_(),ae(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(yt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ae(({throughputEstimation:r,rtt:i})=>!!r&&!!i),uc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(_(),ae(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Qs.DOM,message:String(i)})})};this.subscription.add(Tt(oc(document,"visibilitychange"),oc(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",It({quality:t,availableTracks:It(e),track:It(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}};import{Subscription as IG,Observable as EG,Subject as xG,ValueSubject as PG,VideoQuality as AG}from"@vkontakte/videoplayer-shared";var wG=`@vkontakte/videoplayer-core@${Dc}`;export{ya as ChromecastState,dn as HttpConnectionType,EG as Observable,ue as PlaybackState,Ks as Player,wG as SDK_VERSION,xG as Subject,IG as Subscription,pn as Surface,Dc as VERSION,PG as ValueSubject,lt as VideoFormat,AG as VideoQuality};