@vkontakte/videoplayer-core 2.0.108-dev.3b4522e2.0 → 2.0.108-dev.3ff897f5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.esm.js CHANGED
@@ -1,40 +1,61 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.108-dev.3b4522e2.0
3
- * Tue, 03 Sep 2024 10:04:28 GMT
2
+ * @vkontakte/videoplayer-core v2.0.108-dev.3ff897f5.0
3
+ * Wed, 04 Sep 2024 18:33:52 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-108/doc/
5
5
  */
6
- var zg=Object.create;var cn=Object.defineProperty,Kg=Object.defineProperties,Jg=Object.getOwnPropertyDescriptor,Xg=Object.getOwnPropertyDescriptors,Zg=Object.getOwnPropertyNames,Cl=Object.getOwnPropertySymbols,ev=Object.getPrototypeOf,Ol=Object.prototype.hasOwnProperty,tv=Object.prototype.propertyIsEnumerable;var rv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var je=Math.pow,Dl=(a,e,t)=>e in a?cn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,R=(a,e)=>{for(var t in e||(e={}))Ol.call(e,t)&&Dl(a,t,e[t]);if(Cl)for(var t of Cl(e))tv.call(e,t)&&Dl(a,t,e[t]);return a},q=(a,e)=>Kg(a,Xg(e));var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var iv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Zg(e))!Ol.call(a,i)&&i!==t&&cn(a,i,{get:()=>e[i],enumerable:!(r=Jg(e,i))||r.enumerable});return a};var Ge=(a,e,t)=>(t=a!=null?zg(ev(a)):{},iv(e||!a||!a.__esModule?cn(t,"default",{value:a,enumerable:!0}):t,a));var w=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),av=function(a,e){this[0]=a,this[1]=e},te=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof av,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[rv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var ye=m((t$,Hl)=>{"use strict";Hl.exports=function(a){try{return!!a()}catch(e){return!0}}});var Fr=m((r$,jl)=>{"use strict";var pv=ye();jl.exports=!pv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var de=m((i$,Wl)=>{"use strict";var Gl=Fr(),Yl=Function.prototype,mn=Yl.call,hv=Gl&&Yl.bind.bind(mn,mn);Wl.exports=Gl?hv:function(a){return function(){return mn.apply(a,arguments)}}});var rr=m((a$,zl)=>{"use strict";var Ql=de(),fv=Ql({}.toString),mv=Ql("".slice);zl.exports=function(a){return mv(fv(a),8,-1)}});var Jl=m((s$,Kl)=>{"use strict";var bv=de(),Sv=ye(),gv=rr(),bn=Object,vv=bv("".split);Kl.exports=Sv(function(){return!bn("z").propertyIsEnumerable(0)})?function(a){return gv(a)==="String"?vv(a,""):bn(a)}:bn});var ir=m((n$,Xl)=>{"use strict";Xl.exports=function(a){return a==null}});var qr=m((o$,Zl)=>{"use strict";var yv=ir(),Tv=TypeError;Zl.exports=function(a){if(yv(a))throw new Tv("Can't call method on "+a);return a}});var ar=m((u$,ec)=>{"use strict";var Iv=Jl(),Ev=qr();ec.exports=function(a){return Iv(Ev(a))}});var Sn=m((l$,tc)=>{"use strict";tc.exports=function(){}});var Lt=m((c$,rc)=>{"use strict";rc.exports={}});var K=m((gn,ic)=>{"use strict";var Ur=function(a){return a&&a.Math===Math&&a};ic.exports=Ur(typeof globalThis=="object"&&globalThis)||Ur(typeof window=="object"&&window)||Ur(typeof self=="object"&&self)||Ur(typeof global=="object"&&global)||Ur(typeof gn=="object"&&gn)||function(){return this}()||Function("return this")()});var z=m((d$,ac)=>{"use strict";var vn=typeof document=="object"&&document.all;ac.exports=typeof vn=="undefined"&&vn!==void 0?function(a){return typeof a=="function"||a===vn}:function(a){return typeof a=="function"}});var oc=m((p$,nc)=>{"use strict";var xv=K(),Pv=z(),sc=xv.WeakMap;nc.exports=Pv(sc)&&/native code/.test(String(sc))});var Ae=m((h$,uc)=>{"use strict";var Av=z();uc.exports=function(a){return typeof a=="object"?a!==null:Av(a)}});var we=m((f$,lc)=>{"use strict";var wv=ye();lc.exports=!wv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ta=m((m$,dc)=>{"use strict";var kv=K(),cc=Ae(),yn=kv.document,Rv=cc(yn)&&cc(yn.createElement);dc.exports=function(a){return Rv?yn.createElement(a):{}}});var Tn=m((b$,pc)=>{"use strict";var Lv=we(),$v=ye(),Mv=Ta();pc.exports=!Lv&&!$v(function(){return Object.defineProperty(Mv("div"),"a",{get:function(){return 7}}).a!==7})});var In=m((S$,hc)=>{"use strict";var Cv=we(),Dv=ye();hc.exports=Cv&&Dv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ye=m((g$,fc)=>{"use strict";var Ov=Ae(),Bv=String,Vv=TypeError;fc.exports=function(a){if(Ov(a))return a;throw new Vv(Bv(a)+" is not an object")}});var Te=m((v$,mc)=>{"use strict";var _v=Fr(),Ia=Function.prototype.call;mc.exports=_v?Ia.bind(Ia):function(){return Ia.apply(Ia,arguments)}});var Ea=m((y$,bc)=>{"use strict";bc.exports={}});var Ke=m((T$,gc)=>{"use strict";var En=Ea(),xn=K(),Nv=z(),Sc=function(a){return Nv(a)?a:void 0};gc.exports=function(a,e){return arguments.length<2?Sc(En[a])||Sc(xn[a]):En[a]&&En[a][e]||xn[a]&&xn[a][e]}});var Hr=m((I$,vc)=>{"use strict";var Fv=de();vc.exports=Fv({}.isPrototypeOf)});var sr=m((E$,Ic)=>{"use strict";var qv=K(),yc=qv.navigator,Tc=yc&&yc.userAgent;Ic.exports=Tc?String(Tc):""});var An=m((x$,kc)=>{"use strict";var wc=K(),Pn=sr(),Ec=wc.process,xc=wc.Deno,Pc=Ec&&Ec.versions||xc&&xc.version,Ac=Pc&&Pc.v8,Ve,xa;Ac&&(Ve=Ac.split("."),xa=Ve[0]>0&&Ve[0]<4?1:+(Ve[0]+Ve[1]));!xa&&Pn&&(Ve=Pn.match(/Edge\/(\d+)/),(!Ve||Ve[1]>=74)&&(Ve=Pn.match(/Chrome\/(\d+)/),Ve&&(xa=+Ve[1])));kc.exports=xa});var wn=m((P$,Lc)=>{"use strict";var Rc=An(),Uv=ye(),Hv=K(),jv=Hv.String;Lc.exports=!!Object.getOwnPropertySymbols&&!Uv(function(){var a=Symbol("symbol detection");return!jv(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Rc&&Rc<41})});var kn=m((A$,$c)=>{"use strict";var Gv=wn();$c.exports=Gv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Rn=m((w$,Mc)=>{"use strict";var Yv=Ke(),Wv=z(),Qv=Hr(),zv=kn(),Kv=Object;Mc.exports=zv?function(a){return typeof a=="symbol"}:function(a){var e=Yv("Symbol");return Wv(e)&&Qv(e.prototype,Kv(a))}});var jr=m((k$,Cc)=>{"use strict";var Jv=String;Cc.exports=function(a){try{return Jv(a)}catch(e){return"Object"}}});var Je=m((R$,Dc)=>{"use strict";var Xv=z(),Zv=jr(),ey=TypeError;Dc.exports=function(a){if(Xv(a))return a;throw new ey(Zv(a)+" is not a function")}});var Gr=m((L$,Oc)=>{"use strict";var ty=Je(),ry=ir();Oc.exports=function(a,e){var t=a[e];return ry(t)?void 0:ty(t)}});var Vc=m(($$,Bc)=>{"use strict";var Ln=Te(),$n=z(),Mn=Ae(),iy=TypeError;Bc.exports=function(a,e){var t,r;if(e==="string"&&$n(t=a.toString)&&!Mn(r=Ln(t,a))||$n(t=a.valueOf)&&!Mn(r=Ln(t,a))||e!=="string"&&$n(t=a.toString)&&!Mn(r=Ln(t,a)))return r;throw new iy("Can't convert object to primitive value")}});var _e=m((M$,_c)=>{"use strict";_c.exports=!0});var qc=m((C$,Fc)=>{"use strict";var Nc=K(),ay=Object.defineProperty;Fc.exports=function(a,e){try{ay(Nc,a,{value:e,configurable:!0,writable:!0})}catch(t){Nc[a]=e}return e}});var Yr=m((D$,jc)=>{"use strict";var sy=_e(),ny=K(),oy=qc(),Uc="__core-js_shared__",Hc=jc.exports=ny[Uc]||oy(Uc,{});(Hc.versions||(Hc.versions=[])).push({version:"3.38.0",mode:sy?"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((O$,Yc)=>{"use strict";var Gc=Yr();Yc.exports=function(a,e){return Gc[a]||(Gc[a]=e||{})}});var Wr=m((B$,Wc)=>{"use strict";var uy=qr(),ly=Object;Wc.exports=function(a){return ly(uy(a))}});var Ne=m((V$,Qc)=>{"use strict";var cy=de(),dy=Wr(),py=cy({}.hasOwnProperty);Qc.exports=Object.hasOwn||function(e,t){return py(dy(e),t)}});var Dn=m((_$,zc)=>{"use strict";var hy=de(),fy=0,my=Math.random(),by=hy(1 .toString);zc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+by(++fy+my,36)}});var se=m((N$,Jc)=>{"use strict";var Sy=K(),gy=Cn(),Kc=Ne(),vy=Dn(),yy=wn(),Ty=kn(),nr=Sy.Symbol,On=gy("wks"),Iy=Ty?nr.for||nr:nr&&nr.withoutSetter||vy;Jc.exports=function(a){return Kc(On,a)||(On[a]=yy&&Kc(nr,a)?nr[a]:Iy("Symbol."+a)),On[a]}});var td=m((F$,ed)=>{"use strict";var Ey=Te(),Xc=Ae(),Zc=Rn(),xy=Gr(),Py=Vc(),Ay=se(),wy=TypeError,ky=Ay("toPrimitive");ed.exports=function(a,e){if(!Xc(a)||Zc(a))return a;var t=xy(a,ky),r;if(t){if(e===void 0&&(e="default"),r=Ey(t,a,e),!Xc(r)||Zc(r))return r;throw new wy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Py(a,e)}});var Bn=m((q$,rd)=>{"use strict";var Ry=td(),Ly=Rn();rd.exports=function(a){var e=Ry(a,"string");return Ly(e)?e:e+""}});var $t=m(ad=>{"use strict";var $y=we(),My=Tn(),Cy=In(),Pa=Ye(),id=Bn(),Dy=TypeError,Vn=Object.defineProperty,Oy=Object.getOwnPropertyDescriptor,_n="enumerable",Nn="configurable",Fn="writable";ad.f=$y?Cy?function(e,t,r){if(Pa(e),t=id(t),Pa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Fn in r&&!r[Fn]){var i=Oy(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(Pa(e),t=id(t),Pa(r),My)try{return Vn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Dy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Qr=m((H$,sd)=>{"use strict";sd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var or=m((j$,nd)=>{"use strict";var By=we(),Vy=$t(),_y=Qr();nd.exports=By?function(a,e,t){return Vy.f(a,e,_y(1,t))}:function(a,e,t){return a[e]=t,a}});var Aa=m((G$,ud)=>{"use strict";var Ny=Cn(),Fy=Dn(),od=Ny("keys");ud.exports=function(a){return od[a]||(od[a]=Fy(a))}});var wa=m((Y$,ld)=>{"use strict";ld.exports={}});var jn=m((W$,pd)=>{"use strict";var qy=oc(),dd=K(),Uy=Ae(),Hy=or(),qn=Ne(),Un=Yr(),jy=Aa(),Gy=wa(),cd="Object already initialized",Hn=dd.TypeError,Yy=dd.WeakMap,ka,zr,Ra,Wy=function(a){return Ra(a)?zr(a):ka(a,{})},Qy=function(a){return function(e){var t;if(!Uy(e)||(t=zr(e)).type!==a)throw new Hn("Incompatible receiver, "+a+" required");return t}};qy||Un.state?(Fe=Un.state||(Un.state=new Yy),Fe.get=Fe.get,Fe.has=Fe.has,Fe.set=Fe.set,ka=function(a,e){if(Fe.has(a))throw new Hn(cd);return e.facade=a,Fe.set(a,e),e},zr=function(a){return Fe.get(a)||{}},Ra=function(a){return Fe.has(a)}):(Mt=jy("state"),Gy[Mt]=!0,ka=function(a,e){if(qn(a,Mt))throw new Hn(cd);return e.facade=a,Hy(a,Mt,e),e},zr=function(a){return qn(a,Mt)?a[Mt]:{}},Ra=function(a){return qn(a,Mt)});var Fe,Mt;pd.exports={set:ka,get:zr,has:Ra,enforce:Wy,getterFor:Qy}});var Gn=m((Q$,bd)=>{"use strict";var zy=Fr(),md=Function.prototype,hd=md.apply,fd=md.call;bd.exports=typeof Reflect=="object"&&Reflect.apply||(zy?fd.bind(hd):function(){return fd.apply(hd,arguments)})});var Yn=m((z$,Sd)=>{"use strict";var Ky=rr(),Jy=de();Sd.exports=function(a){if(Ky(a)==="Function")return Jy(a)}});var Td=m(yd=>{"use strict";var gd={}.propertyIsEnumerable,vd=Object.getOwnPropertyDescriptor,Xy=vd&&!gd.call({1:2},1);yd.f=Xy?function(e){var t=vd(this,e);return!!t&&t.enumerable}:gd});var xd=m(Ed=>{"use strict";var Zy=we(),eT=Te(),tT=Td(),rT=Qr(),iT=ar(),aT=Bn(),sT=Ne(),nT=Tn(),Id=Object.getOwnPropertyDescriptor;Ed.f=Zy?Id:function(e,t){if(e=iT(e),t=aT(t),nT)try{return Id(e,t)}catch(r){}if(sT(e,t))return rT(!eT(tT.f,e,t),e[t])}});var Wn=m((X$,Pd)=>{"use strict";var oT=ye(),uT=z(),lT=/#|\.prototype\./,Kr=function(a,e){var t=dT[cT(a)];return t===hT?!0:t===pT?!1:uT(e)?oT(e):!!e},cT=Kr.normalize=function(a){return String(a).replace(lT,".").toLowerCase()},dT=Kr.data={},pT=Kr.NATIVE="N",hT=Kr.POLYFILL="P";Pd.exports=Kr});var Jr=m((Z$,wd)=>{"use strict";var Ad=Yn(),fT=Je(),mT=Fr(),bT=Ad(Ad.bind);wd.exports=function(a,e){return fT(a),e===void 0?a:mT?bT(a,e):function(){return a.apply(e,arguments)}}});var ke=m((eM,Rd)=>{"use strict";var Xr=K(),ST=Gn(),gT=Yn(),vT=z(),yT=xd().f,TT=Wn(),ur=Ea(),IT=Jr(),lr=or(),kd=Ne();Yr();var ET=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};Rd.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?ur:ur[t]||lr(ur,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,S,g;for(p in e)l=TT(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&kd(n,p),f=o[p],c&&(a.dontCallGetSet?(g=yT(n,p),b=g&&g.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?S=IT(h,Xr):a.wrap&&c?S=ET(h):s&&vT(h)?S=gT(h):S=h,(a.sham||h&&h.sham||f&&f.sham)&&lr(S,"sham",!0),lr(o,p,S),s&&(d=t+"Prototype",kd(ur,d)||lr(ur,d,{}),lr(ur[d],p,h),a.real&&u&&(l||!u[p])&&lr(u,p,h)))}});var Md=m((tM,$d)=>{"use strict";var Qn=we(),xT=Ne(),Ld=Function.prototype,PT=Qn&&Object.getOwnPropertyDescriptor,zn=xT(Ld,"name"),AT=zn&&function(){}.name==="something",wT=zn&&(!Qn||Qn&&PT(Ld,"name").configurable);$d.exports={EXISTS:zn,PROPER:AT,CONFIGURABLE:wT}});var Dd=m((rM,Cd)=>{"use strict";var kT=Math.ceil,RT=Math.floor;Cd.exports=Math.trunc||function(e){var t=+e;return(t>0?RT:kT)(t)}});var La=m((iM,Od)=>{"use strict";var LT=Dd();Od.exports=function(a){var e=+a;return e!==e||e===0?0:LT(e)}});var Vd=m((aM,Bd)=>{"use strict";var $T=La(),MT=Math.max,CT=Math.min;Bd.exports=function(a,e){var t=$T(a);return t<0?MT(t+e,0):CT(t,e)}});var Nd=m((sM,_d)=>{"use strict";var DT=La(),OT=Math.min;_d.exports=function(a){var e=DT(a);return e>0?OT(e,9007199254740991):0}});var $a=m((nM,Fd)=>{"use strict";var BT=Nd();Fd.exports=function(a){return BT(a.length)}});var Hd=m((oM,Ud)=>{"use strict";var VT=ar(),_T=Vd(),NT=$a(),qd=function(a){return function(e,t,r){var i=VT(e),s=NT(i);if(s===0)return!a&&-1;var n=_T(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}};Ud.exports={includes:qd(!0),indexOf:qd(!1)}});var Yd=m((uM,Gd)=>{"use strict";var FT=de(),Kn=Ne(),qT=ar(),UT=Hd().indexOf,HT=wa(),jd=FT([].push);Gd.exports=function(a,e){var t=qT(a),r=0,i=[],s;for(s in t)!Kn(HT,s)&&Kn(t,s)&&jd(i,s);for(;e.length>r;)Kn(t,s=e[r++])&&(~UT(i,s)||jd(i,s));return i}});var Jn=m((lM,Wd)=>{"use strict";Wd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var zd=m((cM,Qd)=>{"use strict";var jT=Yd(),GT=Jn();Qd.exports=Object.keys||function(e){return jT(e,GT)}});var Jd=m(Kd=>{"use strict";var YT=we(),WT=In(),QT=$t(),zT=Ye(),KT=ar(),JT=zd();Kd.f=YT&&!WT?Object.defineProperties:function(e,t){zT(e);for(var r=KT(t),i=JT(t),s=i.length,n=0,o;s>n;)QT.f(e,o=i[n++],r[o]);return e}});var Xn=m((pM,Xd)=>{"use strict";var XT=Ke();Xd.exports=XT("document","documentElement")});var ro=m((hM,sp)=>{"use strict";var ZT=Ye(),eI=Jd(),Zd=Jn(),tI=wa(),rI=Xn(),iI=Ta(),aI=Aa(),ep=">",tp="<",eo="prototype",to="script",ip=aI("IE_PROTO"),Zn=function(){},ap=function(a){return tp+to+ep+a+tp+"/"+to+ep},rp=function(a){a.write(ap("")),a.close();var e=a.parentWindow.Object;return a=null,e},sI=function(){var a=iI("iframe"),e="java"+to+":",t;return a.style.display="none",rI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(ap("document.F=Object")),t.close(),t.F},Ma,Ca=function(){try{Ma=new ActiveXObject("htmlfile")}catch(e){}Ca=typeof document!="undefined"?document.domain&&Ma?rp(Ma):sI():rp(Ma);for(var a=Zd.length;a--;)delete Ca[eo][Zd[a]];return Ca()};tI[ip]=!0;sp.exports=Object.create||function(e,t){var r;return e!==null?(Zn[eo]=ZT(e),r=new Zn,Zn[eo]=null,r[ip]=e):r=Ca(),t===void 0?r:eI.f(r,t)}});var op=m((fM,np)=>{"use strict";var nI=ye();np.exports=!nI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ao=m((mM,lp)=>{"use strict";var oI=Ne(),uI=z(),lI=Wr(),cI=Aa(),dI=op(),up=cI("IE_PROTO"),io=Object,pI=io.prototype;lp.exports=dI?io.getPrototypeOf:function(a){var e=lI(a);if(oI(e,up))return e[up];var t=e.constructor;return uI(t)&&e instanceof t?t.prototype:e instanceof io?pI:null}});var cr=m((bM,cp)=>{"use strict";var hI=or();cp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:hI(a,e,t),a}});var uo=m((SM,hp)=>{"use strict";var fI=ye(),mI=z(),bI=Ae(),SI=ro(),dp=ao(),gI=cr(),vI=se(),yI=_e(),oo=vI("iterator"),pp=!1,Xe,so,no;[].keys&&(no=[].keys(),"next"in no?(so=dp(dp(no)),so!==Object.prototype&&(Xe=so)):pp=!0);var TI=!bI(Xe)||fI(function(){var a={};return Xe[oo].call(a)!==a});TI?Xe={}:yI&&(Xe=SI(Xe));mI(Xe[oo])||gI(Xe,oo,function(){return this});hp.exports={IteratorPrototype:Xe,BUGGY_SAFARI_ITERATORS:pp}});var Da=m((gM,mp)=>{"use strict";var II=se(),EI=II("toStringTag"),fp={};fp[EI]="z";mp.exports=String(fp)==="[object z]"});var Zr=m((vM,bp)=>{"use strict";var xI=Da(),PI=z(),Oa=rr(),AI=se(),wI=AI("toStringTag"),kI=Object,RI=Oa(function(){return arguments}())==="Arguments",LI=function(a,e){try{return a[e]}catch(t){}};bp.exports=xI?Oa:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=LI(e=kI(a),wI))=="string"?t:RI?Oa(e):(r=Oa(e))==="Object"&&PI(e.callee)?"Arguments":r}});var gp=m((yM,Sp)=>{"use strict";var $I=Da(),MI=Zr();Sp.exports=$I?{}.toString:function(){return"[object "+MI(this)+"]"}});var ei=m((TM,yp)=>{"use strict";var CI=Da(),DI=$t().f,OI=or(),BI=Ne(),VI=gp(),_I=se(),vp=_I("toStringTag");yp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(BI(i,vp)||DI(i,vp,{configurable:!0,value:e}),r&&!CI&&OI(i,"toString",VI))}});var Ip=m((IM,Tp)=>{"use strict";var NI=uo().IteratorPrototype,FI=ro(),qI=Qr(),UI=ei(),HI=Lt(),jI=function(){return this};Tp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=FI(NI,{next:qI(+!r,t)}),UI(a,i,!1,!0),HI[i]=jI,a}});var xp=m((EM,Ep)=>{"use strict";var GI=de(),YI=Je();Ep.exports=function(a,e,t){try{return GI(YI(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Ap=m((xM,Pp)=>{"use strict";var WI=Ae();Pp.exports=function(a){return WI(a)||a===null}});var kp=m((PM,wp)=>{"use strict";var QI=Ap(),zI=String,KI=TypeError;wp.exports=function(a){if(QI(a))return a;throw new KI("Can't set "+zI(a)+" as a prototype")}});var lo=m((AM,Rp)=>{"use strict";var JI=xp(),XI=Ae(),ZI=qr(),eE=kp();Rp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=JI(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return ZI(i),eE(s),XI(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Fp=m((wM,Np)=>{"use strict";var tE=ke(),rE=Te(),Ba=_e(),Vp=Md(),iE=z(),aE=Ip(),Lp=ao(),$p=lo(),sE=ei(),nE=or(),co=cr(),oE=se(),Mp=Lt(),_p=uo(),uE=Vp.PROPER,lE=Vp.CONFIGURABLE,Cp=_p.IteratorPrototype,Va=_p.BUGGY_SAFARI_ITERATORS,ti=oE("iterator"),Dp="keys",ri="values",Op="entries",Bp=function(){return this};Np.exports=function(a,e,t,r,i,s,n){aE(t,e,r);var o=function(g){if(g===i&&p)return p;if(!Va&&g&&g in c)return c[g];switch(g){case Dp:return function(){return new t(this,g)};case ri:return function(){return new t(this,g)};case Op:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[ti]||c["@@iterator"]||i&&c[i],p=!Va&&d||o(i),h=e==="Array"&&c.entries||d,f,b,S;if(h&&(f=Lp(h.call(new a)),f!==Object.prototype&&f.next&&(!Ba&&Lp(f)!==Cp&&($p?$p(f,Cp):iE(f[ti])||co(f,ti,Bp)),sE(f,u,!0,!0),Ba&&(Mp[u]=Bp))),uE&&i===ri&&d&&d.name!==ri&&(!Ba&&lE?nE(c,"name",ri):(l=!0,p=function(){return rE(d,this)})),i)if(b={values:o(ri),keys:s?p:o(Dp),entries:o(Op)},n)for(S in b)(Va||l||!(S in c))&&co(c,S,b[S]);else tE({target:e,proto:!0,forced:Va||l},b);return(!Ba||n)&&c[ti]!==p&&co(c,ti,p,{name:i}),Mp[e]=p,b}});var Up=m((kM,qp)=>{"use strict";qp.exports=function(a,e){return{value:a,done:e}}});var ho=m((RM,Wp)=>{"use strict";var cE=ar(),po=Sn(),Hp=Lt(),Gp=jn(),dE=$t().f,pE=Fp(),_a=Up(),hE=_e(),fE=we(),Yp="Array Iterator",mE=Gp.set,bE=Gp.getterFor(Yp);Wp.exports=pE(Array,"Array",function(a,e){mE(this,{type:Yp,target:cE(a),index:0,kind:e})},function(){var a=bE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,_a(void 0,!0);switch(a.kind){case"keys":return _a(t,!1);case"values":return _a(e[t],!1)}return _a([t,e[t]],!1)},"values");var jp=Hp.Arguments=Hp.Array;po("keys");po("values");po("entries");if(!hE&&fE&&jp.name!=="values")try{dE(jp,"name",{value:"values"})}catch(a){}});var zp=m((LM,Qp)=>{"use strict";var SE=se(),gE=Lt(),vE=SE("iterator"),yE=Array.prototype;Qp.exports=function(a){return a!==void 0&&(gE.Array===a||yE[vE]===a)}});var fo=m(($M,Jp)=>{"use strict";var TE=Zr(),Kp=Gr(),IE=ir(),EE=Lt(),xE=se(),PE=xE("iterator");Jp.exports=function(a){if(!IE(a))return Kp(a,PE)||Kp(a,"@@iterator")||EE[TE(a)]}});var Zp=m((MM,Xp)=>{"use strict";var AE=Te(),wE=Je(),kE=Ye(),RE=jr(),LE=fo(),$E=TypeError;Xp.exports=function(a,e){var t=arguments.length<2?LE(a):e;if(wE(t))return kE(AE(t,a));throw new $E(RE(a)+" is not iterable")}});var rh=m((CM,th)=>{"use strict";var ME=Te(),eh=Ye(),CE=Gr();th.exports=function(a,e,t){var r,i;eh(a);try{if(r=CE(a,"return"),!r){if(e==="throw")throw t;return t}r=ME(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return eh(r),t}});var Fa=m((DM,nh)=>{"use strict";var DE=Jr(),OE=Te(),BE=Ye(),VE=jr(),_E=zp(),NE=$a(),ih=Hr(),FE=Zp(),qE=fo(),ah=rh(),UE=TypeError,Na=function(a,e){this.stopped=a,this.result=e},sh=Na.prototype;nh.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=DE(e,r),l,c,d,p,h,f,b,S=function(I){return l&&ah(l,"normal",I),new Na(!0,I)},g=function(I){return i?(BE(I),o?u(I[0],I[1],S):u(I[0],I[1])):o?u(I,S):u(I)};if(s)l=a.iterator;else if(n)l=a;else{if(c=qE(a),!c)throw new UE(VE(a)+" is not iterable");if(_E(c)){for(d=0,p=NE(a);p>d;d++)if(h=g(a[d]),h&&ih(sh,h))return h;return new Na(!1)}l=FE(a,c)}for(f=s?a.next:l.next;!(b=OE(f,l)).done;){try{h=g(b.value)}catch(I){ah(l,"throw",I)}if(typeof h=="object"&&h&&ih(sh,h))return h}return new Na(!1)}});var uh=m((OM,oh)=>{"use strict";var HE=we(),jE=$t(),GE=Qr();oh.exports=function(a,e,t){HE?jE.f(a,e,GE(0,t)):a[e]=t}});var lh=m(()=>{"use strict";var YE=ke(),WE=Fa(),QE=uh();YE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return WE(e,function(r,i){QE(t,r,i)},{AS_ENTRIES:!0}),t}})});var dh=m((_M,ch)=>{"use strict";ho();lh();var zE=Ea();ch.exports=zE.Object.fromEntries});var hh=m((NM,ph)=>{"use strict";ph.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 mh=m(()=>{"use strict";ho();var KE=hh(),JE=K(),XE=ei(),fh=Lt();for(qa in KE)XE(JE[qa],qa),fh[qa]=fh.Array;var qa});var Sh=m((UM,bh)=>{"use strict";var ZE=dh();mh();bh.exports=ZE});var mo=m((HM,gh)=>{"use strict";var ex=Sh();gh.exports=ex});var vh=m(()=>{"use strict"});var bo=m((YM,yh)=>{"use strict";var ii=K(),tx=sr(),rx=rr(),Ua=function(a){return tx.slice(0,a.length)===a};yh.exports=function(){return Ua("Bun/")?"BUN":Ua("Cloudflare-Workers")?"CLOUDFLARE":Ua("Deno/")?"DENO":Ua("Node.js/")?"NODE":ii.Bun&&typeof Bun.version=="string"?"BUN":ii.Deno&&typeof Deno.version=="object"?"DENO":rx(ii.process)==="process"?"NODE":ii.window&&ii.document?"BROWSER":"REST"}()});var Ha=m((WM,Th)=>{"use strict";var ix=bo();Th.exports=ix==="NODE"});var Eh=m((QM,Ih)=>{"use strict";var ax=$t();Ih.exports=function(a,e,t){return ax.f(a,e,t)}});var Ah=m((zM,Ph)=>{"use strict";var sx=Ke(),nx=Eh(),ox=se(),ux=we(),xh=ox("species");Ph.exports=function(a){var e=sx(a);ux&&e&&!e[xh]&&nx(e,xh,{configurable:!0,get:function(){return this}})}});var kh=m((KM,wh)=>{"use strict";var lx=Hr(),cx=TypeError;wh.exports=function(a,e){if(lx(e,a))return a;throw new cx("Incorrect invocation")}});var go=m((JM,Rh)=>{"use strict";var dx=de(),px=z(),So=Yr(),hx=dx(Function.toString);px(So.inspectSource)||(So.inspectSource=function(a){return hx(a)});Rh.exports=So.inspectSource});var Oh=m((XM,Dh)=>{"use strict";var fx=de(),mx=ye(),Lh=z(),bx=Zr(),Sx=Ke(),gx=go(),$h=function(){},Mh=Sx("Reflect","construct"),vo=/^\s*(?:class|function)\b/,vx=fx(vo.exec),yx=!vo.test($h),ai=function(e){if(!Lh(e))return!1;try{return Mh($h,[],e),!0}catch(t){return!1}},Ch=function(e){if(!Lh(e))return!1;switch(bx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return yx||!!vx(vo,gx(e))}catch(t){return!0}};Ch.sham=!0;Dh.exports=!Mh||mx(function(){var a;return ai(ai.call)||!ai(Object)||!ai(function(){a=!0})||a})?Ch:ai});var Vh=m((ZM,Bh)=>{"use strict";var Tx=Oh(),Ix=jr(),Ex=TypeError;Bh.exports=function(a){if(Tx(a))return a;throw new Ex(Ix(a)+" is not a constructor")}});var yo=m((eC,Nh)=>{"use strict";var _h=Ye(),xx=Vh(),Px=ir(),Ax=se(),wx=Ax("species");Nh.exports=function(a,e){var t=_h(a).constructor,r;return t===void 0||Px(r=_h(t)[wx])?e:xx(r)}});var qh=m((tC,Fh)=>{"use strict";var kx=de();Fh.exports=kx([].slice)});var Hh=m((rC,Uh)=>{"use strict";var Rx=TypeError;Uh.exports=function(a,e){if(a<e)throw new Rx("Not enough arguments");return a}});var To=m((iC,jh)=>{"use strict";var Lx=sr();jh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Lx)});var Lo=m((aC,Zh)=>{"use strict";var Ie=K(),$x=Gn(),Mx=Jr(),Gh=z(),Cx=Ne(),Xh=ye(),Yh=Xn(),Dx=qh(),Wh=Ta(),Ox=Hh(),Bx=To(),Vx=Ha(),wo=Ie.setImmediate,ko=Ie.clearImmediate,_x=Ie.process,Io=Ie.Dispatch,Nx=Ie.Function,Qh=Ie.MessageChannel,Fx=Ie.String,Eo=0,si={},zh="onreadystatechange",ni,Ct,xo,Po;Xh(function(){ni=Ie.location});var Ro=function(a){if(Cx(si,a)){var e=si[a];delete si[a],e()}},Ao=function(a){return function(){Ro(a)}},Kh=function(a){Ro(a.data)},Jh=function(a){Ie.postMessage(Fx(a),ni.protocol+"//"+ni.host)};(!wo||!ko)&&(wo=function(e){Ox(arguments.length,1);var t=Gh(e)?e:Nx(e),r=Dx(arguments,1);return si[++Eo]=function(){$x(t,void 0,r)},Ct(Eo),Eo},ko=function(e){delete si[e]},Vx?Ct=function(a){_x.nextTick(Ao(a))}:Io&&Io.now?Ct=function(a){Io.now(Ao(a))}:Qh&&!Bx?(xo=new Qh,Po=xo.port2,xo.port1.onmessage=Kh,Ct=Mx(Po.postMessage,Po)):Ie.addEventListener&&Gh(Ie.postMessage)&&!Ie.importScripts&&ni&&ni.protocol!=="file:"&&!Xh(Jh)?(Ct=Jh,Ie.addEventListener("message",Kh,!1)):zh in Wh("script")?Ct=function(a){Yh.appendChild(Wh("script"))[zh]=function(){Yh.removeChild(this),Ro(a)}}:Ct=function(a){setTimeout(Ao(a),0)});Zh.exports={set:wo,clear:ko}});var rf=m((sC,tf)=>{"use strict";var ef=K(),qx=we(),Ux=Object.getOwnPropertyDescriptor;tf.exports=function(a){if(!qx)return ef[a];var e=Ux(ef,a);return e&&e.value}});var $o=m((nC,sf)=>{"use strict";var af=function(){this.head=null,this.tail=null};af.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}}};sf.exports=af});var of=m((oC,nf)=>{"use strict";var Hx=sr();nf.exports=/ipad|iphone|ipod/i.test(Hx)&&typeof Pebble!="undefined"});var lf=m((uC,uf)=>{"use strict";var jx=sr();uf.exports=/web0s(?!.*chrome)/i.test(jx)});var bf=m((lC,mf)=>{"use strict";var pr=K(),Gx=rf(),cf=Jr(),Mo=Lo().set,Yx=$o(),Wx=To(),Qx=of(),zx=lf(),Co=Ha(),df=pr.MutationObserver||pr.WebKitMutationObserver,pf=pr.document,hf=pr.process,ja=pr.Promise,Bo=Gx("queueMicrotask"),dr,Do,Oo,Ga,ff;Bo||(oi=new Yx,ui=function(){var a,e;for(Co&&(a=hf.domain)&&a.exit();e=oi.get();)try{e()}catch(t){throw oi.head&&dr(),t}a&&a.enter()},!Wx&&!Co&&!zx&&df&&pf?(Do=!0,Oo=pf.createTextNode(""),new df(ui).observe(Oo,{characterData:!0}),dr=function(){Oo.data=Do=!Do}):!Qx&&ja&&ja.resolve?(Ga=ja.resolve(void 0),Ga.constructor=ja,ff=cf(Ga.then,Ga),dr=function(){ff(ui)}):Co?dr=function(){hf.nextTick(ui)}:(Mo=cf(Mo,pr),dr=function(){Mo(ui)}),Bo=function(a){oi.head||dr(),oi.add(a)});var oi,ui;mf.exports=Bo});var gf=m((cC,Sf)=>{"use strict";Sf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ya=m((dC,vf)=>{"use strict";vf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Dt=m((pC,yf)=>{"use strict";var Kx=K();yf.exports=Kx.Promise});var hr=m((hC,xf)=>{"use strict";var Jx=K(),li=Dt(),Xx=z(),Zx=Wn(),eP=go(),tP=se(),Tf=bo(),rP=_e(),Vo=An(),If=li&&li.prototype,iP=tP("species"),_o=!1,Ef=Xx(Jx.PromiseRejectionEvent),aP=Zx("Promise",function(){var a=eP(li),e=a!==String(li);if(!e&&Vo===66||rP&&!(If.catch&&If.finally))return!0;if(!Vo||Vo<51||!/native code/.test(a)){var t=new li(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[iP]=r,_o=t.then(function(){})instanceof r,!_o)return!0}return!e&&(Tf==="BROWSER"||Tf==="DENO")&&!Ef});xf.exports={CONSTRUCTOR:aP,REJECTION_EVENT:Ef,SUBCLASSING:_o}});var fr=m((fC,Af)=>{"use strict";var Pf=Je(),sP=TypeError,nP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new sP("Bad Promise constructor");e=r,t=i}),this.resolve=Pf(e),this.reject=Pf(t)};Af.exports.f=function(a){return new nP(a)}});var Gf=m(()=>{"use strict";var oP=ke(),uP=_e(),Ka=Ha(),ht=K(),gr=Te(),wf=cr(),kf=lo(),lP=ei(),cP=Ah(),dP=Je(),za=z(),pP=Ae(),hP=kh(),fP=yo(),Cf=Lo().set,Ho=bf(),mP=gf(),bP=Ya(),SP=$o(),Df=jn(),Ja=Dt(),jo=hr(),Of=fr(),Xa="Promise",Bf=jo.CONSTRUCTOR,gP=jo.REJECTION_EVENT,vP=jo.SUBCLASSING,No=Df.getterFor(Xa),yP=Df.set,mr=Ja&&Ja.prototype,Ot=Ja,Wa=mr,Vf=ht.TypeError,Fo=ht.document,Go=ht.process,qo=Of.f,TP=qo,IP=!!(Fo&&Fo.createEvent&&ht.dispatchEvent),_f="unhandledrejection",EP="rejectionhandled",Rf=0,Nf=1,xP=2,Yo=1,Ff=2,Qa,Lf,PP,$f,qf=function(a){var e;return pP(a)&&za(e=a.then)?e:!1},Uf=function(a,e){var t=e.value,r=e.state===Nf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Ff&&wP(e),e.rejection=Yo),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Vf("Promise-chain cycle")):(l=qf(u))?gr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Hf=function(a,e){a.notified||(a.notified=!0,Ho(function(){for(var t=a.reactions,r;r=t.get();)Uf(r,a);a.notified=!1,e&&!a.rejection&&AP(a)}))},jf=function(a,e,t){var r,i;IP?(r=Fo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),ht.dispatchEvent(r)):r={promise:e,reason:t},!gP&&(i=ht["on"+a])?i(r):a===_f&&mP("Unhandled promise rejection",t)},AP=function(a){gr(Cf,ht,function(){var e=a.facade,t=a.value,r=Mf(a),i;if(r&&(i=bP(function(){Ka?Go.emit("unhandledRejection",t,e):jf(_f,e,t)}),a.rejection=Ka||Mf(a)?Ff:Yo,i.error))throw i.value})},Mf=function(a){return a.rejection!==Yo&&!a.parent},wP=function(a){gr(Cf,ht,function(){var e=a.facade;Ka?Go.emit("rejectionHandled",e):jf(EP,e,a.value)})},br=function(a,e,t){return function(r){a(e,r,t)}},Sr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=xP,Hf(a,!0))},Uo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Vf("Promise can't be resolved itself");var r=qf(e);r?Ho(function(){var i={done:!1};try{gr(r,e,br(Uo,i,a),br(Sr,i,a))}catch(s){Sr(i,s,a)}}):(a.value=e,a.state=Nf,Hf(a,!1))}catch(i){Sr({done:!1},i,a)}}};if(Bf&&(Ot=function(e){hP(this,Wa),dP(e),gr(Qa,this);var t=No(this);try{e(br(Uo,t),br(Sr,t))}catch(r){Sr(t,r)}},Wa=Ot.prototype,Qa=function(e){yP(this,{type:Xa,done:!1,notified:!1,parent:!1,reactions:new SP,rejection:!1,state:Rf,value:void 0})},Qa.prototype=wf(Wa,"then",function(e,t){var r=No(this),i=qo(fP(this,Ot));return r.parent=!0,i.ok=za(e)?e:!0,i.fail=za(t)&&t,i.domain=Ka?Go.domain:void 0,r.state===Rf?r.reactions.add(i):Ho(function(){Uf(i,r)}),i.promise}),Lf=function(){var a=new Qa,e=No(a);this.promise=a,this.resolve=br(Uo,e),this.reject=br(Sr,e)},Of.f=qo=function(a){return a===Ot||a===PP?new Lf(a):TP(a)},!uP&&za(Ja)&&mr!==Object.prototype)){$f=mr.then,vP||wf(mr,"then",function(e,t){var r=this;return new Ot(function(i,s){gr($f,r,i,s)}).then(e,t)},{unsafe:!0});try{delete mr.constructor}catch(a){}kf&&kf(mr,Wa)}oP({global:!0,constructor:!0,wrap:!0,forced:Bf},{Promise:Ot});lP(Ot,Xa,!1,!0);cP(Xa)});var Kf=m((SC,zf)=>{"use strict";var kP=se(),Wf=kP("iterator"),Qf=!1;try{Yf=0,Wo={next:function(){return{done:!!Yf++}},return:function(){Qf=!0}},Wo[Wf]=function(){return this},Array.from(Wo,function(){throw 2})}catch(a){}var Yf,Wo;zf.exports=function(a,e){try{if(!e&&!Qf)return!1}catch(i){return!1}var t=!1;try{var r={};r[Wf]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Qo=m((gC,Jf)=>{"use strict";var RP=Dt(),LP=Kf(),$P=hr().CONSTRUCTOR;Jf.exports=$P||!LP(function(a){RP.all(a).then(void 0,function(){})})});var Xf=m(()=>{"use strict";var MP=ke(),CP=Te(),DP=Je(),OP=fr(),BP=Ya(),VP=Fa(),_P=Qo();MP({target:"Promise",stat:!0,forced:_P},{all:function(e){var t=this,r=OP.f(t),i=r.resolve,s=r.reject,n=BP(function(){var o=DP(t.resolve),u=[],l=0,c=1;VP(e,function(d){var p=l++,h=!1;c++,CP(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var em=m(()=>{"use strict";var NP=ke(),FP=_e(),qP=hr().CONSTRUCTOR,Ko=Dt(),UP=Ke(),HP=z(),jP=cr(),Zf=Ko&&Ko.prototype;NP({target:"Promise",proto:!0,forced:qP,real:!0},{catch:function(a){return this.then(void 0,a)}});!FP&&HP(Ko)&&(zo=UP("Promise").prototype.catch,Zf.catch!==zo&&jP(Zf,"catch",zo,{unsafe:!0}));var zo});var tm=m(()=>{"use strict";var GP=ke(),YP=Te(),WP=Je(),QP=fr(),zP=Ya(),KP=Fa(),JP=Qo();GP({target:"Promise",stat:!0,forced:JP},{race:function(e){var t=this,r=QP.f(t),i=r.reject,s=zP(function(){var n=WP(t.resolve);KP(e,function(o){YP(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var rm=m(()=>{"use strict";var XP=ke(),ZP=fr(),eA=hr().CONSTRUCTOR;XP({target:"Promise",stat:!0,forced:eA},{reject:function(e){var t=ZP.f(this),r=t.reject;return r(e),t.promise}})});var Jo=m((wC,im)=>{"use strict";var tA=Ye(),rA=Ae(),iA=fr();im.exports=function(a,e){if(tA(a),rA(e)&&e.constructor===a)return e;var t=iA.f(a),r=t.resolve;return r(e),t.promise}});var nm=m(()=>{"use strict";var aA=ke(),sA=Ke(),am=_e(),nA=Dt(),sm=hr().CONSTRUCTOR,oA=Jo(),uA=sA("Promise"),lA=am&&!sm;aA({target:"Promise",stat:!0,forced:am||sm},{resolve:function(e){return oA(lA&&this===uA?nA:this,e)}})});var om=m(()=>{"use strict";Gf();Xf();em();tm();rm();nm()});var dm=m(()=>{"use strict";var cA=ke(),dA=_e(),Za=Dt(),pA=ye(),lm=Ke(),cm=z(),hA=yo(),um=Jo(),fA=cr(),Zo=Za&&Za.prototype,mA=!!Za&&pA(function(){Zo.finally.call({then:function(){}},function(){})});cA({target:"Promise",proto:!0,real:!0,forced:mA},{finally:function(a){var e=hA(this,lm("Promise")),t=cm(a);return this.then(t?function(r){return um(e,a()).then(function(){return r})}:a,t?function(r){return um(e,a()).then(function(){throw r})}:a)}});!dA&&cm(Za)&&(Xo=lm("Promise").prototype.finally,Zo.finally!==Xo&&fA(Zo,"finally",Xo,{unsafe:!0}));var Xo});var es=m((DC,pm)=>{"use strict";var bA=Ke();pm.exports=bA});var fm=m((OC,hm)=>{"use strict";vh();om();dm();var SA=es();hm.exports=SA("Promise","finally")});var bm=m((BC,mm)=>{"use strict";var gA=fm();mm.exports=gA});var ts=m((VC,Sm)=>{"use strict";var vA=bm();Sm.exports=vA});var Um=m(()=>{"use strict";var QA=ke(),zA=Wr(),KA=$a(),JA=La(),XA=Sn();QA({target:"Array",proto:!0},{at:function(e){var t=zA(this),r=KA(t),i=JA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});XA("at")});var jm=m((YD,Hm)=>{"use strict";Um();var ZA=es();Hm.exports=ZA("Array","at")});var Ym=m((WD,Gm)=>{"use strict";var ew=jm();Gm.exports=ew});var hi=m((QD,Wm)=>{"use strict";var tw=Ym();Wm.exports=tw});var Gb=m(()=>{"use strict"});var Yb=m(()=>{"use strict"});var Qb=m((t_,Wb)=>{"use strict";var dk=Ae(),pk=rr(),hk=se(),fk=hk("match");Wb.exports=function(a){var e;return dk(a)&&((e=a[fk])!==void 0?!!e:pk(a)==="RegExp")}});var Kb=m((r_,zb)=>{"use strict";var mk=Zr(),bk=String;zb.exports=function(a){if(mk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return bk(a)}});var Xb=m((i_,Jb)=>{"use strict";var Sk=Ye();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 tS=m((a_,eS)=>{"use strict";var gk=Te(),vk=Ne(),yk=Hr(),Tk=Xb(),Zb=RegExp.prototype;eS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Zb)&&!vk(a,"flags")&&yk(Zb,a)?gk(Tk,a):e}});var iS=m((s_,rS)=>{"use strict";var Ru=de(),Ik=Wr(),Ek=Math.floor,wu=Ru("".charAt),xk=Ru("".replace),ku=Ru("".slice),Pk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Ak=/\$([$&'`]|\d{1,2})/g;rS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=Ak;return i!==void 0&&(i=Ik(i),u=Pk),xk(s,u,function(l,c){var d;switch(wu(c,0)){case"$":return"$";case"&":return a;case"`":return ku(e,0,t);case"'":return ku(e,n);case"<":d=i[ku(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=Ek(p/10);return h===0?l:h<=o?r[h-1]===void 0?wu(c,1):r[h-1]+wu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var nS=m(()=>{"use strict";var wk=ke(),kk=Te(),$u=de(),aS=qr(),Rk=z(),Lk=ir(),$k=Qb(),kr=Kb(),Mk=Gr(),Ck=tS(),Dk=iS(),Ok=se(),Bk=_e(),Vk=Ok("replace"),_k=TypeError,Lu=$u("".indexOf),Nk=$u("".replace),sS=$u("".slice),Fk=Math.max;wk({target:"String",proto:!0},{replaceAll:function(e,t){var r=aS(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!Lk(e)){if(i=$k(e),i&&(s=kr(aS(Ck(e))),!~Lu(s,"g")))throw new _k("`.replaceAll` does not allow non-global regexes");if(n=Mk(e,Vk),n)return kk(n,e,r,t);if(Bk&&i)return Nk(kr(r),e,t)}for(o=kr(r),u=kr(e),l=Rk(t),l||(t=kr(t)),c=u.length,d=Fk(1,c),p=Lu(o,u);p!==-1;)h=l?kr(t(u,p,o)):Dk(u,o,p,[],void 0,t),b+=sS(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Lu(o,u,p+d);return f<o.length&&(b+=sS(o,f)),b}})});var uS=m((u_,oS)=>{"use strict";Gb();Yb();nS();var qk=es();oS.exports=qk("String","replaceAll")});var cS=m((l_,lS)=>{"use strict";var Uk=uS();lS.exports=Uk});var pS=m((c_,dS)=>{"use strict";var Hk=cS();dS.exports=Hk});var Bl="2.0.108-dev.3b4522e2.0";var ce=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ce||{}),pt=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(pt||{});var ga=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ga||{}),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 Ul,assertNonNullable as sv,isNonNullable as va,ValueSubject as hn,Subject as nv,Subscription as ov,merge as uv,observableFrom as lv,fromEvent as _l,map as Nl,tap as Fl,filterChanged as cv,isNullable as fn,ErrorCategory as ql}from"@vkontakte/videoplayer-shared";var Vl=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 ya=class{constructor(e){this.connection$=new hn(void 0);this.castState$=new hn("NOT_AVAILABLE");this.errorEvent$=new nv;this.realCastState$=new hn("NOT_AVAILABLE");this.subscription=new ov;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=va((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Vl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ql.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(){va(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(_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 Ul(i.sessionState)}})).add(uv(_l(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Fl(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Nl(i=>i.castState)),lv([r.getCastState()])).pipe(cv(),Nl(dv),Fl(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o;let s=i==="CONNECTED",n=va(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();sv(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;(fn(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"?va(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:ql.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},dv=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 Ul(a)}};var cg=Ge(mo(),1);var wm=Ge(ts(),1);import{assertNever as gm}from"@vkontakte/videoplayer-shared";var ae=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:gm(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:gm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as yA,Subject as rs,merge as vm}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new rs;this.transitionEnded$=new rs;this.transitionUpdated$=new rs;this.forceChanged$=new rs;this.stateChangeStarted$=vm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=vm(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||yA(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 TA}from"@vkontakte/videoplayer-shared";var ym=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 TA(a)}};import{assertNever as vr,assertNonNullable as Bt,debounce as Tm,ErrorCategory as Im,fromEvent as Vt,isNonNullable as Em,map as xm,merge as Pm,observableFrom as IA,Subject as EA,Subscription as tu,timeout as xA,getHighestQuality as PA}from"@vkontakte/videoplayer-shared";var AA=5,wA=5,kA=500,Am=7e3,ci=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:vr(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:vr(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:vr(e)}break}default:vr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ym(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(Pm(this.videoState.stateChangeStarted$.pipe(xm(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(xm(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 EA;e.add(i.pipe(Tm(kA)).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)>AA)&&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<wA&&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:vr(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=Pm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,IA(["init"])).pipe(Tm(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];Bt(c);let d=PA(Object.keys(c));Bt(d);let p=c[d];Bt(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Bt(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];Bt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Bt(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];Bt(c),r=ae(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Im.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return vr(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 Em(o)&&(n.metadata.title=o),Em(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(xA(Am).subscribe(()=>s(`timeout(${Am})`)))});(0,wm.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:Im.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Rm}from"@vkontakte/videoplayer-shared";import{clearVideoElement as RA}from"@vkontakte/videoplayer-shared";var km=a=>{try{a.pause(),a.playbackRate=0,RA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as LA,Subscription as $A}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,MA=(a,e=20)=>{let t=0;return LA(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},pe=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Rm(t):(t=document.createElement("video"),a.appendChild(t)),iu.set(t,r);let i=new $A;return i.add(MA(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},he=a=>{let e=au.get(a);e==null||e.unsubscribe(),au.delete(a);let t=iu.get(a);iu.delete(a),t?Rm(a):km(a)};import{assertNonNullable as di,isNonNullable as Qe,isNullable as OA,fromEvent as yr,merge as Lm,observableFrom as $m,filterChanged as Mm,map as pi,Subject as Cm,Subscription as BA,ValueSubject as VA,ErrorCategory as _A}from"@vkontakte/videoplayer-shared";import{isNonNullable as su,isNullable as CA,Subscription as DA}from"@vkontakte/videoplayer-shared";var is=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=CA(i),l=new DA;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},We=(a,e,t)=>is(e,()=>a.loop,r=>{su(r)&&(a.loop=r)},{onError:t}),fe=(a,e,t,r)=>is(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}),Re=(a,e,t,r)=>is(e,()=>a.playbackRate,i=>{su(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),ft=is;var NA=a=>["__",a.language,a.label].join("|"),FA=(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 Cm;this.current$=new VA(void 0);this.error$=new Cm;this.subscription=new BA;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:_A.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(ft(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Qe(s)&&this.setInternal(s)},{equal:(s,n)=>Qe(s)&&Qe(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(ft(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Qe(s)&&this.setExternal(s)},{equal:(s,n)=>Qe(s)&&Qe(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(ft(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(ft(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(yr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Lm(yr(e,"addtrack"),yr(e,"removetrack"),$m(["init"])).pipe(pi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Mm((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Lm(yr(e,"change"),$m(["init"])).pipe(pi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),pi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Mm()).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(yr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(yr(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;Qe(t.align)&&(i.align=t.align),Qe(t.position)&&(i.position=t.position),Qe(t.size)&&(i.size=t.size),Qe(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:NA(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))(OA(e)||!FA(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)}},Le=nu;var et=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 Dm=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=Dm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Om=a=>{let e=Dm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as $e,map as mt,merge as Vm,filterChanged as UA,isNonNullable as _m,Subject as HA,filter as Nm,mapTo as Fm,combine as jA,once as GA,ErrorCategory as YA,ValueSubject as qm,clientChecker as WA}from"@vkontakte/videoplayer-shared";var qA=3,Bm=(a,e,t=qA)=>{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 me=a=>{let e=v=>$e(a,v).pipe(Fm(void 0)),r=Vm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>$e(a,v))).pipe(mt(v=>v.type==="ended"?a.readyState<2:a.readyState<3),UA()),i=Vm($e(a,"progress"),$e(a,"timeupdate")).pipe(mt(()=>Bm(a.buffered,a.currentTime))),s=WA.isSafari?jA({play:e("play").pipe(GA()),playing:e("playing")}).pipe(Fm(void 0)):e("playing"),n=$e(a,"volumechange").pipe(mt(()=>({muted:a.muted,volume:a.volume}))),o=$e(a,"ratechange").pipe(mt(()=>a.playbackRate)),u=$e(a,"error").pipe(Nm(()=>!!(a.error||a.played.length)),mt(()=>{var T;let v=a.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:YA.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(T=a.error)!=null?T:void 0}})),l=$e(a,"timeupdate").pipe(mt(()=>a.currentTime)),c=new HA,d=.3,p;l.subscribe(v=>{a.loop&&_m(p)&&_m(v)&&p>=a.duration-d&&v<=d&&c.next(p),p=v});let h=e("pause").pipe(Nm(()=>!a.error&&p!==a.duration)),f=$e(a,"enterpictureinpicture"),b=$e(a,"leavepictureinpicture"),S=new qm(Om(a));f.subscribe(()=>S.next(!0)),b.subscribe(()=>S.next(!1));let g=new qm(ou(a));return $e(a,"fullscreenchange").pipe(mt(()=>ou(a))).subscribe(g),{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$:$e(a,"durationchange").pipe(mt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:g}};import{VideoQuality as bt}from"@vkontakte/videoplayer-shared";var St=a=>{switch(a){case"mobile":return bt.Q_144P;case"lowest":return bt.Q_240P;case"low":return bt.Q_360P;case"sd":case"medium":return bt.Q_480P;case"hd":case"high":return bt.Q_720P;case"fullhd":case"full":return bt.Q_1080P;case"quadhd":case"quad":return bt.Q_1440P;case"ultrahd":case"ultra":return bt.Q_2160P}};var pu=Ge(hi(),1);import{isNonNullable as gt,isNullable as lu,now as Zm,isHigher as cu,isHigherOrEqual as Jm,isInvariantQuality as Xm,isLower as du,isLowerOrEqual as rw,videoSizeToQuality as iw,assertNotEmptyArray as aw}from"@vkontakte/videoplayer-shared";var uu=!1,tt={},Qm=a=>{uu=a},zm=()=>{tt={}},Km=a=>{a(tt)},fi=(a,e)=>{var t;uu&&(tt.meta=(t=tt.meta)!=null?t:{},tt.meta[a]=e)},ne=class{constructor(e){this.name=e}next(e){var r,i;if(!uu)return;tt.series=(r=tt.series)!=null?r:{};let t=(i=tt.series[this.name])!=null?i:[];t.push([Date.now(),e]),tt.series[this.name]=t}};var sw=new ne("best_bitrate"),nw=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t,as=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Zm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ow='Assertion "ABR Tracks is empty array" failed',uw=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{var U,L,A,H,W;aw(a,ow);let p=r.usePixelRatio&&(U=window.devicePixelRatio)!=null?U:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},f=h&&iw(h),b=r.considerPlaybackRate&&gt(o)?o:1,S=a.filter(k=>!Xm(k.quality)).sort((k,x)=>cu(k.quality,x.quality)?-1:1),g=(L=(0,pu.default)(S,-1))==null?void 0:L.quality,I=(A=(0,pu.default)(S,0))==null?void 0:A.quality,v=lu(i)||gt(i.min)&&gt(i.max)&&du(i.max,i.min)||gt(i.min)&&I&&cu(i.min,I)||gt(i.max)&&g&&du(i.max,g),T=b*nw(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),y={},C=S.filter(k=>(f?du(k.quality,f):!0)?(gt(t)&&isFinite(t)&&gt(k.bitrate)?t-s>=k.bitrate*T:!0)?r.lazyQualitySwitch&&gt(r.minBufferToSwitchUp)&&u&&!Xm(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&cu(k.quality,u.quality)?(y[k.quality]="Buffer",!1):!!c&&Jm(k.quality,c)?(y[k.quality]="DroppedFramesLimit",!1):v||(lu(i.max)||rw(k.quality,i.max))&&(lu(i.min)||Jm(k.quality,i.min))?!0:(y[k.quality]="FitsQualityLimits",!1):(y[k.quality]="FitsThroughput",!1):(y[k.quality]="FitsContainer",!1))[0];C&&C.bitrate&&sw.next(C.bitrate);let $=(H=C!=null?C:S[Math.ceil((S.length-1)/2)])!=null?H:a[0];$.quality!==((W=l==null?void 0:l.last)==null?void 0:W.quality)&&d({message:`
7
- [available tracks]
8
- ${a.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
6
+ var cv=Object.create;var bn=Object.defineProperty,lv=Object.defineProperties,dv=Object.getOwnPropertyDescriptor,pv=Object.getOwnPropertyDescriptors,hv=Object.getOwnPropertyNames,Nc=Object.getOwnPropertySymbols,fv=Object.getPrototypeOf,qc=Object.prototype.hasOwnProperty,mv=Object.prototype.propertyIsEnumerable;var bv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var We=Math.pow,Fc=(a,e,t)=>e in a?bn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,k=(a,e)=>{for(var t in e||(e={}))qc.call(e,t)&&Fc(a,t,e[t]);if(Nc)for(var t of Nc(e))mv.call(e,t)&&Fc(a,t,e[t]);return a},V=(a,e)=>lv(a,pv(e));var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var gv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of hv(e))!qc.call(a,i)&&i!==t&&bn(a,i,{get:()=>e[i],enumerable:!(r=dv(e,i))||r.enumerable});return a};var Ye=(a,e,t)=>(t=a!=null?cv(fv(a)):{},gv(e||!a||!a.__esModule?bn(t,"default",{value:a,enumerable:!0}):t,a));var R=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(c){i(c)}},n=u=>{try{o(t.throw(u))}catch(c){i(c)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),Sv=function(a,e){this[0]=a,this[1]=e},te=(a,e,t)=>{var r=(n,o,u,c)=>{try{var l=t[n](o),d=(o=l.value)instanceof Sv,p=l.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,c):u({value:h,done:p})).catch(h=>r("throw",h,u,c))}catch(h){c(h)}},i=n=>s[n]=o=>new Promise((u,c)=>r(n,o,u,c)),s={};return t=t.apply(a,e),s[bv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var Ee=m((dL,zc)=>{"use strict";zc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Gr=m((pL,Kc)=>{"use strict";var Av=Ee();Kc.exports=!Av(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var he=m((hL,Zc)=>{"use strict";var Jc=Gr(),Xc=Function.prototype,Tn=Xc.call,wv=Jc&&Xc.bind.bind(Tn,Tn);Zc.exports=Jc?wv:function(a){return function(){return Tn.apply(a,arguments)}}});var nr=m((fL,tl)=>{"use strict";var el=he(),kv=el({}.toString),Rv=el("".slice);tl.exports=function(a){return Rv(kv(a),8,-1)}});var il=m((mL,rl)=>{"use strict";var $v=he(),Lv=Ee(),Mv=nr(),In=Object,Cv=$v("".split);rl.exports=Lv(function(){return!In("z").propertyIsEnumerable(0)})?function(a){return Mv(a)==="String"?Cv(a,""):In(a)}:In});var or=m((bL,al)=>{"use strict";al.exports=function(a){return a==null}});var Wr=m((gL,sl)=>{"use strict";var Dv=or(),Bv=TypeError;sl.exports=function(a){if(Dv(a))throw new Bv("Can't call method on "+a);return a}});var ur=m((SL,nl)=>{"use strict";var Ov=il(),Vv=Wr();nl.exports=function(a){return Ov(Vv(a))}});var En=m((vL,ol)=>{"use strict";ol.exports=function(){}});var Bt=m((yL,ul)=>{"use strict";ul.exports={}});var K=m((xn,cl)=>{"use strict";var Yr=function(a){return a&&a.Math===Math&&a};cl.exports=Yr(typeof globalThis=="object"&&globalThis)||Yr(typeof window=="object"&&window)||Yr(typeof self=="object"&&self)||Yr(typeof global=="object"&&global)||Yr(typeof xn=="object"&&xn)||function(){return this}()||Function("return this")()});var z=m((TL,ll)=>{"use strict";var Pn=typeof document=="object"&&document.all;ll.exports=typeof Pn=="undefined"&&Pn!==void 0?function(a){return typeof a=="function"||a===Pn}:function(a){return typeof a=="function"}});var hl=m((IL,pl)=>{"use strict";var _v=K(),Nv=z(),dl=_v.WeakMap;pl.exports=Nv(dl)&&/native code/.test(String(dl))});var Re=m((EL,fl)=>{"use strict";var Fv=z();fl.exports=function(a){return typeof a=="object"?a!==null:Fv(a)}});var $e=m((xL,ml)=>{"use strict";var qv=Ee();ml.exports=!qv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ka=m((PL,gl)=>{"use strict";var Uv=K(),bl=Re(),An=Uv.document,Hv=bl(An)&&bl(An.createElement);gl.exports=function(a){return Hv?An.createElement(a):{}}});var wn=m((AL,Sl)=>{"use strict";var jv=$e(),Gv=Ee(),Wv=ka();Sl.exports=!jv&&!Gv(function(){return Object.defineProperty(Wv("div"),"a",{get:function(){return 7}}).a!==7})});var kn=m((wL,vl)=>{"use strict";var Yv=$e(),Qv=Ee();vl.exports=Yv&&Qv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Qe=m((kL,yl)=>{"use strict";var zv=Re(),Kv=String,Jv=TypeError;yl.exports=function(a){if(zv(a))return a;throw new Jv(Kv(a)+" is not an object")}});var xe=m((RL,Tl)=>{"use strict";var Xv=Gr(),Ra=Function.prototype.call;Tl.exports=Xv?Ra.bind(Ra):function(){return Ra.apply(Ra,arguments)}});var $a=m(($L,Il)=>{"use strict";Il.exports={}});var Xe=m((LL,xl)=>{"use strict";var Rn=$a(),$n=K(),Zv=z(),El=function(a){return Zv(a)?a:void 0};xl.exports=function(a,e){return arguments.length<2?El(Rn[a])||El($n[a]):Rn[a]&&Rn[a][e]||$n[a]&&$n[a][e]}});var Qr=m((ML,Pl)=>{"use strict";var ey=he();Pl.exports=ey({}.isPrototypeOf)});var cr=m((CL,kl)=>{"use strict";var ty=K(),Al=ty.navigator,wl=Al&&Al.userAgent;kl.exports=wl?String(wl):""});var Mn=m((DL,Dl)=>{"use strict";var Cl=K(),Ln=cr(),Rl=Cl.process,$l=Cl.Deno,Ll=Rl&&Rl.versions||$l&&$l.version,Ml=Ll&&Ll.v8,Ne,La;Ml&&(Ne=Ml.split("."),La=Ne[0]>0&&Ne[0]<4?1:+(Ne[0]+Ne[1]));!La&&Ln&&(Ne=Ln.match(/Edge\/(\d+)/),(!Ne||Ne[1]>=74)&&(Ne=Ln.match(/Chrome\/(\d+)/),Ne&&(La=+Ne[1])));Dl.exports=La});var Cn=m((BL,Ol)=>{"use strict";var Bl=Mn(),ry=Ee(),iy=K(),ay=iy.String;Ol.exports=!!Object.getOwnPropertySymbols&&!ry(function(){var a=Symbol("symbol detection");return!ay(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Bl&&Bl<41})});var Dn=m((OL,Vl)=>{"use strict";var sy=Cn();Vl.exports=sy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Bn=m((VL,_l)=>{"use strict";var ny=Xe(),oy=z(),uy=Qr(),cy=Dn(),ly=Object;_l.exports=cy?function(a){return typeof a=="symbol"}:function(a){var e=ny("Symbol");return oy(e)&&uy(e.prototype,ly(a))}});var zr=m((_L,Nl)=>{"use strict";var dy=String;Nl.exports=function(a){try{return dy(a)}catch(e){return"Object"}}});var Ze=m((NL,Fl)=>{"use strict";var py=z(),hy=zr(),fy=TypeError;Fl.exports=function(a){if(py(a))return a;throw new fy(hy(a)+" is not a function")}});var Kr=m((FL,ql)=>{"use strict";var my=Ze(),by=or();ql.exports=function(a,e){var t=a[e];return by(t)?void 0:my(t)}});var Hl=m((qL,Ul)=>{"use strict";var On=xe(),Vn=z(),_n=Re(),gy=TypeError;Ul.exports=function(a,e){var t,r;if(e==="string"&&Vn(t=a.toString)&&!_n(r=On(t,a))||Vn(t=a.valueOf)&&!_n(r=On(t,a))||e!=="string"&&Vn(t=a.toString)&&!_n(r=On(t,a)))return r;throw new gy("Can't convert object to primitive value")}});var Fe=m((UL,jl)=>{"use strict";jl.exports=!0});var Yl=m((HL,Wl)=>{"use strict";var Gl=K(),Sy=Object.defineProperty;Wl.exports=function(a,e){try{Sy(Gl,a,{value:e,configurable:!0,writable:!0})}catch(t){Gl[a]=e}return e}});var Jr=m((jL,Kl)=>{"use strict";var vy=Fe(),yy=K(),Ty=Yl(),Ql="__core-js_shared__",zl=Kl.exports=yy[Ql]||Ty(Ql,{});(zl.versions||(zl.versions=[])).push({version:"3.38.0",mode:vy?"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 Nn=m((GL,Xl)=>{"use strict";var Jl=Jr();Xl.exports=function(a,e){return Jl[a]||(Jl[a]=e||{})}});var Xr=m((WL,Zl)=>{"use strict";var Iy=Wr(),Ey=Object;Zl.exports=function(a){return Ey(Iy(a))}});var qe=m((YL,ed)=>{"use strict";var xy=he(),Py=Xr(),Ay=xy({}.hasOwnProperty);ed.exports=Object.hasOwn||function(e,t){return Ay(Py(e),t)}});var Fn=m((QL,td)=>{"use strict";var wy=he(),ky=0,Ry=Math.random(),$y=wy(1 .toString);td.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+$y(++ky+Ry,36)}});var se=m((zL,id)=>{"use strict";var Ly=K(),My=Nn(),rd=qe(),Cy=Fn(),Dy=Cn(),By=Dn(),lr=Ly.Symbol,qn=My("wks"),Oy=By?lr.for||lr:lr&&lr.withoutSetter||Cy;id.exports=function(a){return rd(qn,a)||(qn[a]=Dy&&rd(lr,a)?lr[a]:Oy("Symbol."+a)),qn[a]}});var od=m((KL,nd)=>{"use strict";var Vy=xe(),ad=Re(),sd=Bn(),_y=Kr(),Ny=Hl(),Fy=se(),qy=TypeError,Uy=Fy("toPrimitive");nd.exports=function(a,e){if(!ad(a)||sd(a))return a;var t=_y(a,Uy),r;if(t){if(e===void 0&&(e="default"),r=Vy(t,a,e),!ad(r)||sd(r))return r;throw new qy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ny(a,e)}});var Un=m((JL,ud)=>{"use strict";var Hy=od(),jy=Bn();ud.exports=function(a){var e=Hy(a,"string");return jy(e)?e:e+""}});var Ot=m(ld=>{"use strict";var Gy=$e(),Wy=wn(),Yy=kn(),Ma=Qe(),cd=Un(),Qy=TypeError,Hn=Object.defineProperty,zy=Object.getOwnPropertyDescriptor,jn="enumerable",Gn="configurable",Wn="writable";ld.f=Gy?Yy?function(e,t,r){if(Ma(e),t=cd(t),Ma(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Wn in r&&!r[Wn]){var i=zy(e,t);i&&i[Wn]&&(e[t]=r.value,r={configurable:Gn in r?r[Gn]:i[Gn],enumerable:jn in r?r[jn]:i[jn],writable:!1})}return Hn(e,t,r)}:Hn:function(e,t,r){if(Ma(e),t=cd(t),Ma(r),Wy)try{return Hn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Qy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Zr=m((ZL,dd)=>{"use strict";dd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var dr=m((eM,pd)=>{"use strict";var Ky=$e(),Jy=Ot(),Xy=Zr();pd.exports=Ky?function(a,e,t){return Jy.f(a,e,Xy(1,t))}:function(a,e,t){return a[e]=t,a}});var Ca=m((tM,fd)=>{"use strict";var Zy=Nn(),eT=Fn(),hd=Zy("keys");fd.exports=function(a){return hd[a]||(hd[a]=eT(a))}});var Da=m((rM,md)=>{"use strict";md.exports={}});var Kn=m((iM,Sd)=>{"use strict";var tT=hl(),gd=K(),rT=Re(),iT=dr(),Yn=qe(),Qn=Jr(),aT=Ca(),sT=Da(),bd="Object already initialized",zn=gd.TypeError,nT=gd.WeakMap,Ba,ei,Oa,oT=function(a){return Oa(a)?ei(a):Ba(a,{})},uT=function(a){return function(e){var t;if(!rT(e)||(t=ei(e)).type!==a)throw new zn("Incompatible receiver, "+a+" required");return t}};tT||Qn.state?(Ue=Qn.state||(Qn.state=new nT),Ue.get=Ue.get,Ue.has=Ue.has,Ue.set=Ue.set,Ba=function(a,e){if(Ue.has(a))throw new zn(bd);return e.facade=a,Ue.set(a,e),e},ei=function(a){return Ue.get(a)||{}},Oa=function(a){return Ue.has(a)}):(Vt=aT("state"),sT[Vt]=!0,Ba=function(a,e){if(Yn(a,Vt))throw new zn(bd);return e.facade=a,iT(a,Vt,e),e},ei=function(a){return Yn(a,Vt)?a[Vt]:{}},Oa=function(a){return Yn(a,Vt)});var Ue,Vt;Sd.exports={set:Ba,get:ei,has:Oa,enforce:oT,getterFor:uT}});var Jn=m((aM,Id)=>{"use strict";var cT=Gr(),Td=Function.prototype,vd=Td.apply,yd=Td.call;Id.exports=typeof Reflect=="object"&&Reflect.apply||(cT?yd.bind(vd):function(){return yd.apply(vd,arguments)})});var Xn=m((sM,Ed)=>{"use strict";var lT=nr(),dT=he();Ed.exports=function(a){if(lT(a)==="Function")return dT(a)}});var wd=m(Ad=>{"use strict";var xd={}.propertyIsEnumerable,Pd=Object.getOwnPropertyDescriptor,pT=Pd&&!xd.call({1:2},1);Ad.f=pT?function(e){var t=Pd(this,e);return!!t&&t.enumerable}:xd});var $d=m(Rd=>{"use strict";var hT=$e(),fT=xe(),mT=wd(),bT=Zr(),gT=ur(),ST=Un(),vT=qe(),yT=wn(),kd=Object.getOwnPropertyDescriptor;Rd.f=hT?kd:function(e,t){if(e=gT(e),t=ST(t),yT)try{return kd(e,t)}catch(r){}if(vT(e,t))return bT(!fT(mT.f,e,t),e[t])}});var Zn=m((uM,Ld)=>{"use strict";var TT=Ee(),IT=z(),ET=/#|\.prototype\./,ti=function(a,e){var t=PT[xT(a)];return t===wT?!0:t===AT?!1:IT(e)?TT(e):!!e},xT=ti.normalize=function(a){return String(a).replace(ET,".").toLowerCase()},PT=ti.data={},AT=ti.NATIVE="N",wT=ti.POLYFILL="P";Ld.exports=ti});var ri=m((cM,Cd)=>{"use strict";var Md=Xn(),kT=Ze(),RT=Gr(),$T=Md(Md.bind);Cd.exports=function(a,e){return kT(a),e===void 0?a:RT?$T(a,e):function(){return a.apply(e,arguments)}}});var Le=m((lM,Bd)=>{"use strict";var ii=K(),LT=Jn(),MT=Xn(),CT=z(),DT=$d().f,BT=Zn(),pr=$a(),OT=ri(),hr=dr(),Dd=qe();Jr();var VT=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 LT(a,this,arguments)};return e.prototype=a.prototype,e};Bd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?ii:i?ii[t]:ii[t]&&ii[t].prototype,o=r?pr:pr[t]||hr(pr,t,{})[t],u=o.prototype,c,l,d,p,h,f,b,g,S;for(p in e)c=BT(r?p:t+(i?".":"#")+p,a.forced),l=!c&&n&&Dd(n,p),f=o[p],l&&(a.dontCallGetSet?(S=DT(n,p),b=S&&S.value):b=n[p]),h=l&&b?b:e[p],!(!c&&!s&&typeof f==typeof h)&&(a.bind&&l?g=OT(h,ii):a.wrap&&l?g=VT(h):s&&CT(h)?g=MT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&hr(g,"sham",!0),hr(o,p,g),s&&(d=t+"Prototype",Dd(pr,d)||hr(pr,d,{}),hr(pr[d],p,h),a.real&&u&&(c||!u[p])&&hr(u,p,h)))}});var _d=m((dM,Vd)=>{"use strict";var eo=$e(),_T=qe(),Od=Function.prototype,NT=eo&&Object.getOwnPropertyDescriptor,to=_T(Od,"name"),FT=to&&function(){}.name==="something",qT=to&&(!eo||eo&&NT(Od,"name").configurable);Vd.exports={EXISTS:to,PROPER:FT,CONFIGURABLE:qT}});var Fd=m((pM,Nd)=>{"use strict";var UT=Math.ceil,HT=Math.floor;Nd.exports=Math.trunc||function(e){var t=+e;return(t>0?HT:UT)(t)}});var Va=m((hM,qd)=>{"use strict";var jT=Fd();qd.exports=function(a){var e=+a;return e!==e||e===0?0:jT(e)}});var Hd=m((fM,Ud)=>{"use strict";var GT=Va(),WT=Math.max,YT=Math.min;Ud.exports=function(a,e){var t=GT(a);return t<0?WT(t+e,0):YT(t,e)}});var Gd=m((mM,jd)=>{"use strict";var QT=Va(),zT=Math.min;jd.exports=function(a){var e=QT(a);return e>0?zT(e,9007199254740991):0}});var _a=m((bM,Wd)=>{"use strict";var KT=Gd();Wd.exports=function(a){return KT(a.length)}});var zd=m((gM,Qd)=>{"use strict";var JT=ur(),XT=Hd(),ZT=_a(),Yd=function(a){return function(e,t,r){var i=JT(e),s=ZT(i);if(s===0)return!a&&-1;var n=XT(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Qd.exports={includes:Yd(!0),indexOf:Yd(!1)}});var Xd=m((SM,Jd)=>{"use strict";var eI=he(),ro=qe(),tI=ur(),rI=zd().indexOf,iI=Da(),Kd=eI([].push);Jd.exports=function(a,e){var t=tI(a),r=0,i=[],s;for(s in t)!ro(iI,s)&&ro(t,s)&&Kd(i,s);for(;e.length>r;)ro(t,s=e[r++])&&(~rI(i,s)||Kd(i,s));return i}});var io=m((vM,Zd)=>{"use strict";Zd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var tp=m((yM,ep)=>{"use strict";var aI=Xd(),sI=io();ep.exports=Object.keys||function(e){return aI(e,sI)}});var ip=m(rp=>{"use strict";var nI=$e(),oI=kn(),uI=Ot(),cI=Qe(),lI=ur(),dI=tp();rp.f=nI&&!oI?Object.defineProperties:function(e,t){cI(e);for(var r=lI(t),i=dI(t),s=i.length,n=0,o;s>n;)uI.f(e,o=i[n++],r[o]);return e}});var ao=m((IM,ap)=>{"use strict";var pI=Xe();ap.exports=pI("document","documentElement")});var uo=m((EM,dp)=>{"use strict";var hI=Qe(),fI=ip(),sp=io(),mI=Da(),bI=ao(),gI=ka(),SI=Ca(),np=">",op="<",no="prototype",oo="script",cp=SI("IE_PROTO"),so=function(){},lp=function(a){return op+oo+np+a+op+"/"+oo+np},up=function(a){a.write(lp("")),a.close();var e=a.parentWindow.Object;return a=null,e},vI=function(){var a=gI("iframe"),e="java"+oo+":",t;return a.style.display="none",bI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(lp("document.F=Object")),t.close(),t.F},Na,Fa=function(){try{Na=new ActiveXObject("htmlfile")}catch(e){}Fa=typeof document!="undefined"?document.domain&&Na?up(Na):vI():up(Na);for(var a=sp.length;a--;)delete Fa[no][sp[a]];return Fa()};mI[cp]=!0;dp.exports=Object.create||function(e,t){var r;return e!==null?(so[no]=hI(e),r=new so,so[no]=null,r[cp]=e):r=Fa(),t===void 0?r:fI.f(r,t)}});var hp=m((xM,pp)=>{"use strict";var yI=Ee();pp.exports=!yI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var lo=m((PM,mp)=>{"use strict";var TI=qe(),II=z(),EI=Xr(),xI=Ca(),PI=hp(),fp=xI("IE_PROTO"),co=Object,AI=co.prototype;mp.exports=PI?co.getPrototypeOf:function(a){var e=EI(a);if(TI(e,fp))return e[fp];var t=e.constructor;return II(t)&&e instanceof t?t.prototype:e instanceof co?AI:null}});var fr=m((AM,bp)=>{"use strict";var wI=dr();bp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:wI(a,e,t),a}});var mo=m((wM,vp)=>{"use strict";var kI=Ee(),RI=z(),$I=Re(),LI=uo(),gp=lo(),MI=fr(),CI=se(),DI=Fe(),fo=CI("iterator"),Sp=!1,et,po,ho;[].keys&&(ho=[].keys(),"next"in ho?(po=gp(gp(ho)),po!==Object.prototype&&(et=po)):Sp=!0);var BI=!$I(et)||kI(function(){var a={};return et[fo].call(a)!==a});BI?et={}:DI&&(et=LI(et));RI(et[fo])||MI(et,fo,function(){return this});vp.exports={IteratorPrototype:et,BUGGY_SAFARI_ITERATORS:Sp}});var qa=m((kM,Tp)=>{"use strict";var OI=se(),VI=OI("toStringTag"),yp={};yp[VI]="z";Tp.exports=String(yp)==="[object z]"});var ai=m((RM,Ip)=>{"use strict";var _I=qa(),NI=z(),Ua=nr(),FI=se(),qI=FI("toStringTag"),UI=Object,HI=Ua(function(){return arguments}())==="Arguments",jI=function(a,e){try{return a[e]}catch(t){}};Ip.exports=_I?Ua:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=jI(e=UI(a),qI))=="string"?t:HI?Ua(e):(r=Ua(e))==="Object"&&NI(e.callee)?"Arguments":r}});var xp=m(($M,Ep)=>{"use strict";var GI=qa(),WI=ai();Ep.exports=GI?{}.toString:function(){return"[object "+WI(this)+"]"}});var si=m((LM,Ap)=>{"use strict";var YI=qa(),QI=Ot().f,zI=dr(),KI=qe(),JI=xp(),XI=se(),Pp=XI("toStringTag");Ap.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(KI(i,Pp)||QI(i,Pp,{configurable:!0,value:e}),r&&!YI&&zI(i,"toString",JI))}});var kp=m((MM,wp)=>{"use strict";var ZI=mo().IteratorPrototype,eE=uo(),tE=Zr(),rE=si(),iE=Bt(),aE=function(){return this};wp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=eE(ZI,{next:tE(+!r,t)}),rE(a,i,!1,!0),iE[i]=aE,a}});var $p=m((CM,Rp)=>{"use strict";var sE=he(),nE=Ze();Rp.exports=function(a,e,t){try{return sE(nE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Mp=m((DM,Lp)=>{"use strict";var oE=Re();Lp.exports=function(a){return oE(a)||a===null}});var Dp=m((BM,Cp)=>{"use strict";var uE=Mp(),cE=String,lE=TypeError;Cp.exports=function(a){if(uE(a))return a;throw new lE("Can't set "+cE(a)+" as a prototype")}});var bo=m((OM,Bp)=>{"use strict";var dE=$p(),pE=Re(),hE=Wr(),fE=Dp();Bp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=dE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return hE(i),fE(s),pE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Wp=m((VM,Gp)=>{"use strict";var mE=Le(),bE=xe(),Ha=Fe(),Hp=_d(),gE=z(),SE=kp(),Op=lo(),Vp=bo(),vE=si(),yE=dr(),go=fr(),TE=se(),_p=Bt(),jp=mo(),IE=Hp.PROPER,EE=Hp.CONFIGURABLE,Np=jp.IteratorPrototype,ja=jp.BUGGY_SAFARI_ITERATORS,ni=TE("iterator"),Fp="keys",oi="values",qp="entries",Up=function(){return this};Gp.exports=function(a,e,t,r,i,s,n){SE(t,e,r);var o=function(S){if(S===i&&p)return p;if(!ja&&S&&S in l)return l[S];switch(S){case Fp:return function(){return new t(this,S)};case oi:return function(){return new t(this,S)};case qp:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[ni]||l["@@iterator"]||i&&l[i],p=!ja&&d||o(i),h=e==="Array"&&l.entries||d,f,b,g;if(h&&(f=Op(h.call(new a)),f!==Object.prototype&&f.next&&(!Ha&&Op(f)!==Np&&(Vp?Vp(f,Np):gE(f[ni])||go(f,ni,Up)),vE(f,u,!0,!0),Ha&&(_p[u]=Up))),IE&&i===oi&&d&&d.name!==oi&&(!Ha&&EE?yE(l,"name",oi):(c=!0,p=function(){return bE(d,this)})),i)if(b={values:o(oi),keys:s?p:o(Fp),entries:o(qp)},n)for(g in b)(ja||c||!(g in l))&&go(l,g,b[g]);else mE({target:e,proto:!0,forced:ja||c},b);return(!Ha||n)&&l[ni]!==p&&go(l,ni,p,{name:i}),_p[e]=p,b}});var Qp=m((_M,Yp)=>{"use strict";Yp.exports=function(a,e){return{value:a,done:e}}});var vo=m((NM,Zp)=>{"use strict";var xE=ur(),So=En(),zp=Bt(),Jp=Kn(),PE=Ot().f,AE=Wp(),Ga=Qp(),wE=Fe(),kE=$e(),Xp="Array Iterator",RE=Jp.set,$E=Jp.getterFor(Xp);Zp.exports=AE(Array,"Array",function(a,e){RE(this,{type:Xp,target:xE(a),index:0,kind:e})},function(){var a=$E(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ga(void 0,!0);switch(a.kind){case"keys":return Ga(t,!1);case"values":return Ga(e[t],!1)}return Ga([t,e[t]],!1)},"values");var Kp=zp.Arguments=zp.Array;So("keys");So("values");So("entries");if(!wE&&kE&&Kp.name!=="values")try{PE(Kp,"name",{value:"values"})}catch(a){}});var th=m((FM,eh)=>{"use strict";var LE=se(),ME=Bt(),CE=LE("iterator"),DE=Array.prototype;eh.exports=function(a){return a!==void 0&&(ME.Array===a||DE[CE]===a)}});var yo=m((qM,ih)=>{"use strict";var BE=ai(),rh=Kr(),OE=or(),VE=Bt(),_E=se(),NE=_E("iterator");ih.exports=function(a){if(!OE(a))return rh(a,NE)||rh(a,"@@iterator")||VE[BE(a)]}});var sh=m((UM,ah)=>{"use strict";var FE=xe(),qE=Ze(),UE=Qe(),HE=zr(),jE=yo(),GE=TypeError;ah.exports=function(a,e){var t=arguments.length<2?jE(a):e;if(qE(t))return UE(FE(t,a));throw new GE(HE(a)+" is not iterable")}});var uh=m((HM,oh)=>{"use strict";var WE=xe(),nh=Qe(),YE=Kr();oh.exports=function(a,e,t){var r,i;nh(a);try{if(r=YE(a,"return"),!r){if(e==="throw")throw t;return t}r=WE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return nh(r),t}});var Ya=m((jM,ph)=>{"use strict";var QE=ri(),zE=xe(),KE=Qe(),JE=zr(),XE=th(),ZE=_a(),ch=Qr(),ex=sh(),tx=yo(),lh=uh(),rx=TypeError,Wa=function(a,e){this.stopped=a,this.result=e},dh=Wa.prototype;ph.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=QE(e,r),c,l,d,p,h,f,b,g=function(T){return c&&lh(c,"normal",T),new Wa(!0,T)},S=function(T){return i?(KE(T),o?u(T[0],T[1],g):u(T[0],T[1])):o?u(T,g):u(T)};if(s)c=a.iterator;else if(n)c=a;else{if(l=tx(a),!l)throw new rx(JE(a)+" is not iterable");if(XE(l)){for(d=0,p=ZE(a);p>d;d++)if(h=S(a[d]),h&&ch(dh,h))return h;return new Wa(!1)}c=ex(a,l)}for(f=s?a.next:c.next;!(b=zE(f,c)).done;){try{h=S(b.value)}catch(T){lh(c,"throw",T)}if(typeof h=="object"&&h&&ch(dh,h))return h}return new Wa(!1)}});var fh=m((GM,hh)=>{"use strict";var ix=$e(),ax=Ot(),sx=Zr();hh.exports=function(a,e,t){ix?ax.f(a,e,sx(0,t)):a[e]=t}});var mh=m(()=>{"use strict";var nx=Le(),ox=Ya(),ux=fh();nx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return ox(e,function(r,i){ux(t,r,i)},{AS_ENTRIES:!0}),t}})});var gh=m((QM,bh)=>{"use strict";vo();mh();var cx=$a();bh.exports=cx.Object.fromEntries});var vh=m((zM,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 Th=m(()=>{"use strict";vo();var lx=vh(),dx=K(),px=si(),yh=Bt();for(Qa in lx)px(dx[Qa],Qa),yh[Qa]=yh.Array;var Qa});var Eh=m((XM,Ih)=>{"use strict";var hx=gh();Th();Ih.exports=hx});var To=m((ZM,xh)=>{"use strict";var fx=Eh();xh.exports=fx});var Ph=m(()=>{"use strict"});var Io=m((rC,Ah)=>{"use strict";var ui=K(),mx=cr(),bx=nr(),za=function(a){return mx.slice(0,a.length)===a};Ah.exports=function(){return za("Bun/")?"BUN":za("Cloudflare-Workers")?"CLOUDFLARE":za("Deno/")?"DENO":za("Node.js/")?"NODE":ui.Bun&&typeof Bun.version=="string"?"BUN":ui.Deno&&typeof Deno.version=="object"?"DENO":bx(ui.process)==="process"?"NODE":ui.window&&ui.document?"BROWSER":"REST"}()});var Ka=m((iC,wh)=>{"use strict";var gx=Io();wh.exports=gx==="NODE"});var Rh=m((aC,kh)=>{"use strict";var Sx=Ot();kh.exports=function(a,e,t){return Sx.f(a,e,t)}});var Mh=m((sC,Lh)=>{"use strict";var vx=Xe(),yx=Rh(),Tx=se(),Ix=$e(),$h=Tx("species");Lh.exports=function(a){var e=vx(a);Ix&&e&&!e[$h]&&yx(e,$h,{configurable:!0,get:function(){return this}})}});var Dh=m((nC,Ch)=>{"use strict";var Ex=Qr(),xx=TypeError;Ch.exports=function(a,e){if(Ex(e,a))return a;throw new xx("Incorrect invocation")}});var xo=m((oC,Bh)=>{"use strict";var Px=he(),Ax=z(),Eo=Jr(),wx=Px(Function.toString);Ax(Eo.inspectSource)||(Eo.inspectSource=function(a){return wx(a)});Bh.exports=Eo.inspectSource});var qh=m((uC,Fh)=>{"use strict";var kx=he(),Rx=Ee(),Oh=z(),$x=ai(),Lx=Xe(),Mx=xo(),Vh=function(){},_h=Lx("Reflect","construct"),Po=/^\s*(?:class|function)\b/,Cx=kx(Po.exec),Dx=!Po.test(Vh),ci=function(e){if(!Oh(e))return!1;try{return _h(Vh,[],e),!0}catch(t){return!1}},Nh=function(e){if(!Oh(e))return!1;switch($x(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Dx||!!Cx(Po,Mx(e))}catch(t){return!0}};Nh.sham=!0;Fh.exports=!_h||Rx(function(){var a;return ci(ci.call)||!ci(Object)||!ci(function(){a=!0})||a})?Nh:ci});var Hh=m((cC,Uh)=>{"use strict";var Bx=qh(),Ox=zr(),Vx=TypeError;Uh.exports=function(a){if(Bx(a))return a;throw new Vx(Ox(a)+" is not a constructor")}});var Ao=m((lC,Gh)=>{"use strict";var jh=Qe(),_x=Hh(),Nx=or(),Fx=se(),qx=Fx("species");Gh.exports=function(a,e){var t=jh(a).constructor,r;return t===void 0||Nx(r=jh(t)[qx])?e:_x(r)}});var Yh=m((dC,Wh)=>{"use strict";var Ux=he();Wh.exports=Ux([].slice)});var zh=m((pC,Qh)=>{"use strict";var Hx=TypeError;Qh.exports=function(a,e){if(a<e)throw new Hx("Not enough arguments");return a}});var wo=m((hC,Kh)=>{"use strict";var jx=cr();Kh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(jx)});var Oo=m((fC,nf)=>{"use strict";var Pe=K(),Gx=Jn(),Wx=ri(),Jh=z(),Yx=qe(),sf=Ee(),Xh=ao(),Qx=Yh(),Zh=ka(),zx=zh(),Kx=wo(),Jx=Ka(),Co=Pe.setImmediate,Do=Pe.clearImmediate,Xx=Pe.process,ko=Pe.Dispatch,Zx=Pe.Function,ef=Pe.MessageChannel,eP=Pe.String,Ro=0,li={},tf="onreadystatechange",di,_t,$o,Lo;sf(function(){di=Pe.location});var Bo=function(a){if(Yx(li,a)){var e=li[a];delete li[a],e()}},Mo=function(a){return function(){Bo(a)}},rf=function(a){Bo(a.data)},af=function(a){Pe.postMessage(eP(a),di.protocol+"//"+di.host)};(!Co||!Do)&&(Co=function(e){zx(arguments.length,1);var t=Jh(e)?e:Zx(e),r=Qx(arguments,1);return li[++Ro]=function(){Gx(t,void 0,r)},_t(Ro),Ro},Do=function(e){delete li[e]},Jx?_t=function(a){Xx.nextTick(Mo(a))}:ko&&ko.now?_t=function(a){ko.now(Mo(a))}:ef&&!Kx?($o=new ef,Lo=$o.port2,$o.port1.onmessage=rf,_t=Wx(Lo.postMessage,Lo)):Pe.addEventListener&&Jh(Pe.postMessage)&&!Pe.importScripts&&di&&di.protocol!=="file:"&&!sf(af)?(_t=af,Pe.addEventListener("message",rf,!1)):tf in Zh("script")?_t=function(a){Xh.appendChild(Zh("script"))[tf]=function(){Xh.removeChild(this),Bo(a)}}:_t=function(a){setTimeout(Mo(a),0)});nf.exports={set:Co,clear:Do}});var cf=m((mC,uf)=>{"use strict";var of=K(),tP=$e(),rP=Object.getOwnPropertyDescriptor;uf.exports=function(a){if(!tP)return of[a];var e=rP(of,a);return e&&e.value}});var Vo=m((bC,df)=>{"use strict";var lf=function(){this.head=null,this.tail=null};lf.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}}};df.exports=lf});var hf=m((gC,pf)=>{"use strict";var iP=cr();pf.exports=/ipad|iphone|ipod/i.test(iP)&&typeof Pebble!="undefined"});var mf=m((SC,ff)=>{"use strict";var aP=cr();ff.exports=/web0s(?!.*chrome)/i.test(aP)});var If=m((vC,Tf)=>{"use strict";var br=K(),sP=cf(),bf=ri(),_o=Oo().set,nP=Vo(),oP=wo(),uP=hf(),cP=mf(),No=Ka(),gf=br.MutationObserver||br.WebKitMutationObserver,Sf=br.document,vf=br.process,Ja=br.Promise,Uo=sP("queueMicrotask"),mr,Fo,qo,Xa,yf;Uo||(pi=new nP,hi=function(){var a,e;for(No&&(a=vf.domain)&&a.exit();e=pi.get();)try{e()}catch(t){throw pi.head&&mr(),t}a&&a.enter()},!oP&&!No&&!cP&&gf&&Sf?(Fo=!0,qo=Sf.createTextNode(""),new gf(hi).observe(qo,{characterData:!0}),mr=function(){qo.data=Fo=!Fo}):!uP&&Ja&&Ja.resolve?(Xa=Ja.resolve(void 0),Xa.constructor=Ja,yf=bf(Xa.then,Xa),mr=function(){yf(hi)}):No?mr=function(){vf.nextTick(hi)}:(_o=bf(_o,br),mr=function(){_o(hi)}),Uo=function(a){pi.head||mr(),pi.add(a)});var pi,hi;Tf.exports=Uo});var xf=m((yC,Ef)=>{"use strict";Ef.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Za=m((TC,Pf)=>{"use strict";Pf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Nt=m((IC,Af)=>{"use strict";var lP=K();Af.exports=lP.Promise});var gr=m((EC,$f)=>{"use strict";var dP=K(),fi=Nt(),pP=z(),hP=Zn(),fP=xo(),mP=se(),wf=Io(),bP=Fe(),Ho=Mn(),kf=fi&&fi.prototype,gP=mP("species"),jo=!1,Rf=pP(dP.PromiseRejectionEvent),SP=hP("Promise",function(){var a=fP(fi),e=a!==String(fi);if(!e&&Ho===66||bP&&!(kf.catch&&kf.finally))return!0;if(!Ho||Ho<51||!/native code/.test(a)){var t=new fi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[gP]=r,jo=t.then(function(){})instanceof r,!jo)return!0}return!e&&(wf==="BROWSER"||wf==="DENO")&&!Rf});$f.exports={CONSTRUCTOR:SP,REJECTION_EVENT:Rf,SUBCLASSING:jo}});var Sr=m((xC,Mf)=>{"use strict";var Lf=Ze(),vP=TypeError,yP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new vP("Bad Promise constructor");e=r,t=i}),this.resolve=Lf(e),this.reject=Lf(t)};Mf.exports.f=function(a){return new yP(a)}});var Jf=m(()=>{"use strict";var TP=Le(),IP=Fe(),is=Ka(),bt=K(),Ir=xe(),Cf=fr(),Df=bo(),EP=si(),xP=Mh(),PP=Ze(),rs=z(),AP=Re(),wP=Dh(),kP=Ao(),Nf=Oo().set,zo=If(),RP=xf(),$P=Za(),LP=Vo(),Ff=Kn(),as=Nt(),Ko=gr(),qf=Sr(),ss="Promise",Uf=Ko.CONSTRUCTOR,MP=Ko.REJECTION_EVENT,CP=Ko.SUBCLASSING,Go=Ff.getterFor(ss),DP=Ff.set,vr=as&&as.prototype,Ft=as,es=vr,Hf=bt.TypeError,Wo=bt.document,Jo=bt.process,Yo=qf.f,BP=Yo,OP=!!(Wo&&Wo.createEvent&&bt.dispatchEvent),jf="unhandledrejection",VP="rejectionhandled",Bf=0,Gf=1,_P=2,Xo=1,Wf=2,ts,Of,NP,Vf,Yf=function(a){var e;return AP(a)&&rs(e=a.then)?e:!1},Qf=function(a,e){var t=e.value,r=e.state===Gf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{i?(r||(e.rejection===Wf&&qP(e),e.rejection=Xo),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),l=!0)),u===a.promise?n(new Hf("Promise-chain cycle")):(c=Yf(u))?Ir(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},zf=function(a,e){a.notified||(a.notified=!0,zo(function(){for(var t=a.reactions,r;r=t.get();)Qf(r,a);a.notified=!1,e&&!a.rejection&&FP(a)}))},Kf=function(a,e,t){var r,i;OP?(r=Wo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),bt.dispatchEvent(r)):r={promise:e,reason:t},!MP&&(i=bt["on"+a])?i(r):a===jf&&RP("Unhandled promise rejection",t)},FP=function(a){Ir(Nf,bt,function(){var e=a.facade,t=a.value,r=_f(a),i;if(r&&(i=$P(function(){is?Jo.emit("unhandledRejection",t,e):Kf(jf,e,t)}),a.rejection=is||_f(a)?Wf:Xo,i.error))throw i.value})},_f=function(a){return a.rejection!==Xo&&!a.parent},qP=function(a){Ir(Nf,bt,function(){var e=a.facade;is?Jo.emit("rejectionHandled",e):Kf(VP,e,a.value)})},yr=function(a,e,t){return function(r){a(e,r,t)}},Tr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=_P,zf(a,!0))},Qo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Hf("Promise can't be resolved itself");var r=Yf(e);r?zo(function(){var i={done:!1};try{Ir(r,e,yr(Qo,i,a),yr(Tr,i,a))}catch(s){Tr(i,s,a)}}):(a.value=e,a.state=Gf,zf(a,!1))}catch(i){Tr({done:!1},i,a)}}};if(Uf&&(Ft=function(e){wP(this,es),PP(e),Ir(ts,this);var t=Go(this);try{e(yr(Qo,t),yr(Tr,t))}catch(r){Tr(t,r)}},es=Ft.prototype,ts=function(e){DP(this,{type:ss,done:!1,notified:!1,parent:!1,reactions:new LP,rejection:!1,state:Bf,value:void 0})},ts.prototype=Cf(es,"then",function(e,t){var r=Go(this),i=Yo(kP(this,Ft));return r.parent=!0,i.ok=rs(e)?e:!0,i.fail=rs(t)&&t,i.domain=is?Jo.domain:void 0,r.state===Bf?r.reactions.add(i):zo(function(){Qf(i,r)}),i.promise}),Of=function(){var a=new ts,e=Go(a);this.promise=a,this.resolve=yr(Qo,e),this.reject=yr(Tr,e)},qf.f=Yo=function(a){return a===Ft||a===NP?new Of(a):BP(a)},!IP&&rs(as)&&vr!==Object.prototype)){Vf=vr.then,CP||Cf(vr,"then",function(e,t){var r=this;return new Ft(function(i,s){Ir(Vf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete vr.constructor}catch(a){}Df&&Df(vr,es)}TP({global:!0,constructor:!0,wrap:!0,forced:Uf},{Promise:Ft});EP(Ft,ss,!1,!0);xP(ss)});var rm=m((wC,tm)=>{"use strict";var UP=se(),Zf=UP("iterator"),em=!1;try{Xf=0,Zo={next:function(){return{done:!!Xf++}},return:function(){em=!0}},Zo[Zf]=function(){return this},Array.from(Zo,function(){throw 2})}catch(a){}var Xf,Zo;tm.exports=function(a,e){try{if(!e&&!em)return!1}catch(i){return!1}var t=!1;try{var r={};r[Zf]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var eu=m((kC,im)=>{"use strict";var HP=Nt(),jP=rm(),GP=gr().CONSTRUCTOR;im.exports=GP||!jP(function(a){HP.all(a).then(void 0,function(){})})});var am=m(()=>{"use strict";var WP=Le(),YP=xe(),QP=Ze(),zP=Sr(),KP=Za(),JP=Ya(),XP=eu();WP({target:"Promise",stat:!0,forced:XP},{all:function(e){var t=this,r=zP.f(t),i=r.resolve,s=r.reject,n=KP(function(){var o=QP(t.resolve),u=[],c=0,l=1;JP(e,function(d){var p=c++,h=!1;l++,YP(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 nm=m(()=>{"use strict";var ZP=Le(),eA=Fe(),tA=gr().CONSTRUCTOR,ru=Nt(),rA=Xe(),iA=z(),aA=fr(),sm=ru&&ru.prototype;ZP({target:"Promise",proto:!0,forced:tA,real:!0},{catch:function(a){return this.then(void 0,a)}});!eA&&iA(ru)&&(tu=rA("Promise").prototype.catch,sm.catch!==tu&&aA(sm,"catch",tu,{unsafe:!0}));var tu});var om=m(()=>{"use strict";var sA=Le(),nA=xe(),oA=Ze(),uA=Sr(),cA=Za(),lA=Ya(),dA=eu();sA({target:"Promise",stat:!0,forced:dA},{race:function(e){var t=this,r=uA.f(t),i=r.reject,s=cA(function(){var n=oA(t.resolve);lA(e,function(o){nA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var um=m(()=>{"use strict";var pA=Le(),hA=Sr(),fA=gr().CONSTRUCTOR;pA({target:"Promise",stat:!0,forced:fA},{reject:function(e){var t=hA.f(this),r=t.reject;return r(e),t.promise}})});var iu=m((VC,cm)=>{"use strict";var mA=Qe(),bA=Re(),gA=Sr();cm.exports=function(a,e){if(mA(a),bA(e)&&e.constructor===a)return e;var t=gA.f(a),r=t.resolve;return r(e),t.promise}});var pm=m(()=>{"use strict";var SA=Le(),vA=Xe(),lm=Fe(),yA=Nt(),dm=gr().CONSTRUCTOR,TA=iu(),IA=vA("Promise"),EA=lm&&!dm;SA({target:"Promise",stat:!0,forced:lm||dm},{resolve:function(e){return TA(EA&&this===IA?yA:this,e)}})});var hm=m(()=>{"use strict";Jf();am();nm();om();um();pm()});var gm=m(()=>{"use strict";var xA=Le(),PA=Fe(),ns=Nt(),AA=Ee(),mm=Xe(),bm=z(),wA=Ao(),fm=iu(),kA=fr(),su=ns&&ns.prototype,RA=!!ns&&AA(function(){su.finally.call({then:function(){}},function(){})});xA({target:"Promise",proto:!0,real:!0,forced:RA},{finally:function(a){var e=wA(this,mm("Promise")),t=bm(a);return this.then(t?function(r){return fm(e,a()).then(function(){return r})}:a,t?function(r){return fm(e,a()).then(function(){throw r})}:a)}});!PA&&bm(ns)&&(au=mm("Promise").prototype.finally,su.finally!==au&&kA(su,"finally",au,{unsafe:!0}));var au});var os=m((jC,Sm)=>{"use strict";var $A=Xe();Sm.exports=$A});var ym=m((GC,vm)=>{"use strict";Ph();hm();gm();var LA=os();vm.exports=LA("Promise","finally")});var Im=m((WC,Tm)=>{"use strict";var MA=ym();Tm.exports=MA});var us=m((YC,Em)=>{"use strict";var CA=Im();Em.exports=CA});var Qm=m(()=>{"use strict";var uw=Le(),cw=Xr(),lw=_a(),dw=Va(),pw=En();uw({target:"Array",proto:!0},{at:function(e){var t=cw(this),r=lw(t),i=dw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});pw("at")});var Km=m((r0,zm)=>{"use strict";Qm();var hw=os();zm.exports=hw("Array","at")});var Xm=m((i0,Jm)=>{"use strict";var fw=Km();Jm.exports=fw});var Si=m((a0,Zm)=>{"use strict";var mw=Xm();Zm.exports=mw});var ag=m(()=>{"use strict"});var sg=m(()=>{"use strict"});var og=m((d_,ng)=>{"use strict";var Tk=Re(),Ik=nr(),Ek=se(),xk=Ek("match");ng.exports=function(a){var e;return Tk(a)&&((e=a[xk])!==void 0?!!e:Ik(a)==="RegExp")}});var cg=m((p_,ug)=>{"use strict";var Pk=ai(),Ak=String;ug.exports=function(a){if(Pk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Ak(a)}});var dg=m((h_,lg)=>{"use strict";var wk=Qe();lg.exports=function(){var a=wk(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 fg=m((f_,hg)=>{"use strict";var kk=xe(),Rk=qe(),$k=Qr(),Lk=dg(),pg=RegExp.prototype;hg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in pg)&&!Rk(a,"flags")&&$k(pg,a)?kk(Lk,a):e}});var bg=m((m_,mg)=>{"use strict";var Bu=he(),Mk=Xr(),Ck=Math.floor,Cu=Bu("".charAt),Dk=Bu("".replace),Du=Bu("".slice),Bk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Ok=/\$([$&'`]|\d{1,2})/g;mg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=Ok;return i!==void 0&&(i=Mk(i),u=Bk),Dk(s,u,function(c,l){var d;switch(Cu(l,0)){case"$":return"$";case"&":return a;case"`":return Du(e,0,t);case"'":return Du(e,n);case"<":d=i[Du(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=Ck(p/10);return h===0?c:h<=o?r[h-1]===void 0?Cu(l,1):r[h-1]+Cu(l,1):c}d=r[p-1]}return d===void 0?"":d})}});var vg=m(()=>{"use strict";var Vk=Le(),_k=xe(),Vu=he(),gg=Wr(),Nk=z(),Fk=or(),qk=og(),Mr=cg(),Uk=Kr(),Hk=fg(),jk=bg(),Gk=se(),Wk=Fe(),Yk=Gk("replace"),Qk=TypeError,Ou=Vu("".indexOf),zk=Vu("".replace),Sg=Vu("".slice),Kk=Math.max;Vk({target:"String",proto:!0},{replaceAll:function(e,t){var r=gg(this),i,s,n,o,u,c,l,d,p,h,f=0,b="";if(!Fk(e)){if(i=qk(e),i&&(s=Mr(gg(Hk(e))),!~Ou(s,"g")))throw new Qk("`.replaceAll` does not allow non-global regexes");if(n=Uk(e,Yk),n)return _k(n,e,r,t);if(Wk&&i)return zk(Mr(r),e,t)}for(o=Mr(r),u=Mr(e),c=Nk(t),c||(t=Mr(t)),l=u.length,d=Kk(1,l),p=Ou(o,u);p!==-1;)h=c?Mr(t(u,p,o)):jk(u,o,p,[],void 0,t),b+=Sg(o,f,p)+h,f=p+l,p=p+d>o.length?-1:Ou(o,u,p+d);return f<o.length&&(b+=Sg(o,f)),b}})});var Tg=m((S_,yg)=>{"use strict";ag();sg();vg();var Jk=os();yg.exports=Jk("String","replaceAll")});var Eg=m((v_,Ig)=>{"use strict";var Xk=Tg();Ig.exports=Xk});var Pg=m((y_,xg)=>{"use strict";var Zk=Eg();xg.exports=Zk});var Uc="2.0.108-dev.3ff897f5.0";var pe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(pe||{}),mt=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(mt||{});var Pa=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Pa||{}),gn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(gn||{});var Sn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Sn||{});import{assertNever as Qc,assertNonNullable as vv,isNonNullable as Aa,ValueSubject as vn,Subject as yv,Subscription as Tv,merge as Iv,observableFrom as Ev,fromEvent as jc,map as Gc,tap as Wc,filterChanged as xv,isNullable as yn,ErrorCategory as Yc}from"@vkontakte/videoplayer-shared";var Hc=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 wa=class{constructor(e){this.connection$=new vn(void 0);this.castState$=new vn("NOT_AVAILABLE");this.errorEvent$=new yv;this.realCastState$=new vn("NOT_AVAILABLE");this.subscription=new Tv;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=Aa((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Hc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Yc.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(){Aa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();yn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();yn(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(jc(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 Qc(i.sessionState)}})).add(Iv(jc(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Wc(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Gc(i=>i.castState)),Ev([r.getCastState()])).pipe(xv(),Gc(Pv),Wc(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Aa(this.connection$.getValue());if(s&&!n){let c=r.getCurrentSession();vv(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(yn(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"?Aa(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:Yc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Pv=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 Qc(a)}};var ES=Ye(To(),1);var Cm=Ye(us(),1);import{assertNever as xm}from"@vkontakte/videoplayer-shared";var ae=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:xm(t)}return a},nu=(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:xm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as DA,Subject as cs,merge as Pm}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new cs;this.transitionEnded$=new cs;this.transitionUpdated$=new cs;this.forceChanged$=new cs;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||DA(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 BA}from"@vkontakte/videoplayer-shared";var Am=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 BA(a)}};import{assertNever as Er,assertNonNullable as qt,debounce as wm,ErrorCategory as km,fromEvent as Ut,isNonNullable as Rm,map as $m,merge as Lm,observableFrom as OA,Subject as VA,Subscription as ou,timeout as _A,getHighestQuality as NA}from"@vkontakte/videoplayer-shared";var FA=5,qA=5,UA=500,Mm=7e3,mi=class{constructor(e){this.subscription=new ou;this.loadMediaTimeoutSubscription=new ou;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:Er(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:Er(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:Er(e)}break}default:Er(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Am(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 ou;this.subscription.add(e),this.subscription.add(Lm(this.videoState.stateChangeStarted$.pipe($m(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe($m(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 VA;e.add(i.pipe(wm(UA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Ut(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(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ut(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<qA&&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:Er(n)}}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Lm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,OA(["init"])).pipe(wm(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];qt(l);let d=NA(Object.keys(l));qt(d);let p=l[d];qt(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];qt(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];qt(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];qt(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];qt(l),r=ae(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:km.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Er(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 Rm(o)&&(n.metadata.title=o),Rm(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(_A(Mm).subscribe(()=>s(`timeout(${Mm})`)))});(0,Cm.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:km.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Bm}from"@vkontakte/videoplayer-shared";import{clearVideoElement as HA}from"@vkontakte/videoplayer-shared";var Dm=a=>{try{a.pause(),a.playbackRate=0,HA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as jA,Subscription as GA}from"@vkontakte/videoplayer-shared";var uu=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)}},cu=window.WeakMap?new WeakMap:new uu,lu=window.WeakMap?new WeakMap:new Map,WA=(a,e=20)=>{let t=0;return jA(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},fe=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Bm(t):(t=document.createElement("video"),a.appendChild(t)),cu.set(t,r);let i=new GA;return i.add(WA(t,e)),lu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},me=a=>{let e=lu.get(a);e==null||e.unsubscribe(),lu.delete(a);let t=cu.get(a);cu.delete(a),t?Bm(a):Dm(a)};import{assertNonNullable as bi,isNonNullable as Ke,isNullable as zA,fromEvent as xr,merge as Om,observableFrom as Vm,filterChanged as _m,map as gi,Subject as Nm,Subscription as KA,ValueSubject as JA,ErrorCategory as XA}from"@vkontakte/videoplayer-shared";import{isNonNullable as du,isNullable as YA,Subscription as QA}from"@vkontakte/videoplayer-shared";var ls=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=YA(i),c=new QA;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},ze=(a,e,t)=>ls(e,()=>a.loop,r=>{du(r)&&(a.loop=r)},{onError:t}),be=(a,e,t,r)=>ls(e,()=>({muted:a.muted,volume:a.volume}),i=>{du(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}),Me=(a,e,t,r)=>ls(e,()=>a.playbackRate,i=>{du(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),gt=ls;var ZA=a=>["__",a.language,a.label].join("|"),ew=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},pu=class a{constructor(){this.available$=new Nm;this.current$=new JA(void 0);this.error$=new Nm;this.subscription=new KA;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:XA.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(gt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Ke(s)&&this.setInternal(s)},{equal:(s,n)=>Ke(s)&&Ke(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(gi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(gt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Ke(s)&&this.setExternal(s)},{equal:(s,n)=>Ke(s)&&Ke(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(gi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(gt(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(gt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){bi(this.video);let{textTracks:e}=this.video;this.subscription.add(xr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Om(xr(e,"addtrack"),xr(e,"removetrack"),Vm(["init"])).pipe(gi(()=>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(Om(xr(e,"change"),Vm(["init"])).pipe(gi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),gi(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(xr(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(xr(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;Ke(t.align)&&(i.align=t.align),Ke(t.position)&&(i.position=t.position),Ke(t.size)&&(i.size=t.size),Ke(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){bi(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:ZA(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){bi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(zA(e)||!ew(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){bi(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){bi(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)}},Ce=pu;var rt=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 Fm=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},hu=a=>{let e=Fm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},qm=a=>{let e=Fm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as De,map as St,merge as Hm,filterChanged as rw,isNonNullable as jm,Subject as iw,filter as Gm,mapTo as Wm,combine as aw,once as sw,ErrorCategory as nw,ValueSubject as Ym,clientChecker as ow}from"@vkontakte/videoplayer-shared";var tw=3,Um=(a,e,t=tw)=>{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 ge=a=>{let e=v=>De(a,v).pipe(Wm(void 0)),r=Hm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>De(a,v))).pipe(St(v=>v.type==="ended"?a.readyState<2:a.readyState<3),rw()),i=Hm(De(a,"progress"),De(a,"timeupdate")).pipe(St(()=>Um(a.buffered,a.currentTime))),s=ow.isSafari?aw({play:e("play").pipe(sw()),playing:e("playing")}).pipe(Wm(void 0)):e("playing"),n=De(a,"volumechange").pipe(St(()=>({muted:a.muted,volume:a.volume}))),o=De(a,"ratechange").pipe(St(()=>a.playbackRate)),u=De(a,"error").pipe(Gm(()=>!!(a.error||a.played.length)),St(()=>{var y;let v=a.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:nw.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(y=a.error)!=null?y:void 0}})),c=De(a,"timeupdate").pipe(St(()=>a.currentTime)),l=new iw,d=.3,p;c.subscribe(v=>{a.loop&&jm(p)&&jm(v)&&p>=a.duration-d&&v<=d&&l.next(p),p=v});let h=e("pause").pipe(Gm(()=>!a.error&&p!==a.duration)),f=De(a,"enterpictureinpicture"),b=De(a,"leavepictureinpicture"),g=new Ym(qm(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new Ym(hu(a));return De(a,"fullscreenchange").pipe(St(()=>hu(a))).subscribe(S),{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$:De(a,"durationchange").pipe(St(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S}};import{VideoQuality as vt}from"@vkontakte/videoplayer-shared";var yt=a=>{switch(a){case"mobile":return vt.Q_144P;case"lowest":return vt.Q_240P;case"low":return vt.Q_360P;case"sd":case"medium":return vt.Q_480P;case"hd":case"high":return vt.Q_720P;case"fullhd":case"full":return vt.Q_1080P;case"quadhd":case"quad":return vt.Q_1440P;case"ultrahd":case"ultra":return vt.Q_2160P}};var Ht=Ye(Si(),1);import{isNonNullable as Se,isNullable as mu,now as ob,isHigher as bu,isHigherOrEqual as ib,isInvariantQuality as ab,isLower as gu,isLowerOrEqual as sb,videoSizeToQuality as bw,assertNotEmptyArray as ub,assertNonNullable as gw}from"@vkontakte/videoplayer-shared";var fu=!1,it={},eb=a=>{fu=a},tb=()=>{it={}},rb=a=>{a(it)},vi=(a,e)=>{var t;fu&&(it.meta=(t=it.meta)!=null?t:{},it.meta[a]=e)},ne=class{constructor(e){this.name=e}next(e){var r,i;if(!fu)return;it.series=(r=it.series)!=null?r:{};let t=(i=it.series[this.name])!=null?i:[];t.push([Date.now(),e]),it.series[this.name]=t}};var Sw=new ne("best_bitrate"),cb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Su=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),yi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ob()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},lb='Assertion "ABR Tracks is empty array" failed',ds=(a,e,t,r)=>{var u;let i=[...e].sort(Su(1)),s=[...t].sort(Su(1)),n=s.filter(c=>Se(c.bitrate)&&Se(a.bitrate)?a.bitrate/c.bitrate>r:!0),o=(u=(0,Ht.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Ht.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Ht.default)(n,-1):(0,Ht.default)(s,0)},nb=a=>"quality"in a,db=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&ob()-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=nb(s)?"video":"audio",o=nb(s)?s.quality:s.bitrate;return e({message:`
7
+ [last ${n} selected] ${o}
8
+ `}),s}return r==null||r.recordSwitch(t),t},Tt=(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 H,N,L,F,_;ub(a,lb);let h=r.usePixelRatio&&(H=window.devicePixelRatio)!=null?H: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&&bw(f),g=r.considerPlaybackRate&&Se(o)?o:1,S=a.filter(w=>!ab(w.quality)).sort((w,x)=>bu(w.quality,x.quality)?-1:1),T=(N=(0,Ht.default)(S,-1))==null?void 0:N.quality,v=(L=(0,Ht.default)(S,0))==null?void 0:L.quality,y=mu(i)||Se(i.min)&&Se(i.max)&&gu(i.max,i.min)||Se(i.min)&&v&&bu(i.min,v)||Se(i.max)&&T&&gu(i.max,T),I=g*cb(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),$={},O=S.filter(w=>{if(!(b?gu(w.quality,b):!0))return $[w.quality]="FitsContainer",!1;if(!(Se(t)&&isFinite(t)&&Se(w.bitrate)?t-s>=w.bitrate*I:!0))return $[w.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&Se(r.minBufferToSwitchUp)&&u&&!ab(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&bu(w.quality,u.quality))return $[w.quality]="Buffer",!1;if(!!d&&ib(w.quality,d))return $[w.quality]="DroppedFramesLimit",!1;let X=y||(mu(i.max)||sb(w.quality,i.max))&&(mu(i.min)||ib(w.quality,i.min)),ce=Se(l)&&!l?sb(w.quality,r.backgroundVideoQualityLimit):!0;return!X||!ce?($[w.quality]="FitsQualityLimits",!1):!0})[0];O&&O.bitrate&&Sw.next(O.bitrate);let C=(F=O!=null?O:S[Math.ceil((S.length-1)/2)])!=null?F:a[0];return C.quality!==((_=c==null?void 0:c.last)==null?void 0:_.quality)&&p({message:`
9
+ [VIDEO TRACKS ABR]
10
+ [available video tracks]
11
+ ${a.map(w=>`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate} }`).join(`
9
12
  `)}
10
13
 
11
14
  [tuning]
12
- ${Object.entries(r!=null?r:{}).map(([k,x])=>`${k}: ${x}`).join(`
15
+ ${Object.entries(r!=null?r:{}).map(([w,x])=>`${w}: ${x}`).join(`
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: ${T},
25
+ bitrateFactor: ${I},
23
26
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
24
- droppedVideoMaxQualityLimit: ${c},
25
- limitsAreInvalid: ${v},
27
+ droppedVideoMaxQualityLimit: ${d},
28
+ limitsAreInvalid: ${y},
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(y).map(([k,x])=>`${k}: ${x}`).join(`
32
+ [limited video tracks]
33
+ ${Object.entries($).map(([w,x])=>`${w}: ${x}`).join(`
31
34
  `)||"All tracks are available"}
32
35
 
33
- [best track] ${C==null?void 0:C.quality}
34
- [selected track] ${$==null?void 0:$.quality}
35
- `});let B=$&&l&&l.history[$.id]&&Zm()-l.history[$.id]<=r.trackCooldown&&(!l.last||$.id!==l.last.id);if($!=null&&$.id&&l&&!B&&l.recordSelection($),B&&(l!=null&&l.last)){let k=l.last;return l==null||l.recordSwitch(k),d({message:`
36
- [last selected] ${k==null?void 0:k.quality}
37
- `}),k}return l==null||l.recordSwitch($),$},vt=uw;var re=a=>new URL(a).hostname;import{assertNever as sb,assertNonNullable as nb,combine as kw,debounce as Rw,ErrorCategory as ob,filter as ub,filterChanged as Lw,isNonNullable as Su,map as ls,merge as lb,observableFrom as $w,once as Mw,Subscription as Cw,ValueSubject as gu,videoQualityToHeight as Dw,videoSizeToQuality as Ow}from"@vkontakte/videoplayer-shared";var eb=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"))},be=a=>w(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!eb(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return eb(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as ns,isNullable as dw,assertNonNullable as Si}from"@vkontakte/videoplayer-shared";import{isNonNullable as tb,assertNonNullable as ss,now as lw}from"@vkontakte/videoplayer-shared";function ie(){return lw()}function hu(a){return ie()-a}function fu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function rb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Tr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,S=()=>{if(u)return;ss(c);let A=hu(c),H;if(A<b){H=b-A,setTimeout(S,H);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,O()},g=A=>(s=A,L),I=A=>(d=A,L),v=()=>(h="json",L),T=()=>{if(!u){if(--l>=0){S(),r&&r();return}u=!0,d&&d(),t&&t()}},y=A=>(p=A,L),O=()=>{c=ie(),n=new i,n.open("get",a);let A=0,H,W=0,k=()=>(ss(c),Math.max(c,Math.max(H||0,W||0)));if(s&&n.addEventListener("progress",x=>{let N=ie();s.updateChunk&&x.loaded>A&&(s.updateChunk(k(),x.loaded-A),A=x.loaded,H=N)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;ss(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let N=n.response.byteLength-A;N&&s.updateChunk&&s.updateChunk(k(),N)}n.responseType==="json"&&!Object.values(n.response).length?T():(d&&d(),e(n.response))}else T()}),n.addEventListener("error",()=>{T()}),p){let x=()=>{ss(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(W=ie(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),L},L={withBitrateReporting:g,withParallel:y,withJSONResponse:v,withRetryCount:A=>(l=A,L),withRetryInterval:(A,H)=>(tb(A)&&(b=A),tb(H)&&(f=H),L),withTimeout:A=>(o=A,L),withFinally:I,send:O,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return L}var mi=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 bi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ie(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ie()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Tr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ie()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ie();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){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 os=1e4,mu=3;var pw=6e4,hw=10,fw=1,mw=500,gi=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 mi(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||ns(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=()=>{rb(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 bi(mu,os,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let T=s&&(!c||c===this.rep);return T||t("Not running!"),T},p=(T,y,O)=>{u&&u.abort(),u=Tr(this.urlResolver.resolve(T,!1),y,O,()=>this._retryCallback()).withTimeout(os).withBitrateReporting(this.bitrateSwitcher).withRetryCount(mu).withFinally(()=>{u=null}).send()},h=(T,y,O)=>{Si(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),y,O,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=T=>{let y=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${y}=>${T}`),r.playbackRate=T)},b=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let O=ie()-1e4,C=0;for(let B=0;B<this.bufferStates.length;B++){let U=this.bufferStates[B];T=Math.min(T,U.buf),U.ts<O&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${T} drop=${C} jitter=${this.sourceJitter}`);let $=T-fw;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?f(1.15):$>1?f(1.1):$>.3?f(1.05):f(1)}},g=T=>{let y,O=()=>y&&y.start?y.start.length:0,C=x=>y.start[x]/1e3,$=x=>y.dur[x]/1e3,B=x=>y.fragIndex+x,U=(x,N)=>({chunkIdx:B(x),startTS:C(x),dur:$(x),discontinuity:N}),L=()=>{let x=0;if(y&&y.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Q=N;this.sourceJitter>1&&(Q+=this.sourceJitter-1);let Z=y.dur.length-1;for(;Z>=0&&(Q-=y.dur[Z],!(Q<=0));--Z);x=Math.min(Z,y.dur.length-1-G),x=Math.max(x,0)}return U(x,!0)},A=x=>{let N=O();if(!(N<=0)){if(ns(x)){for(let G=0;G<N;G++)if(C(G)>x)return U(G)}return L()}},H=x=>{let N=O(),G=x?x.chunkIdx+1:0,Q=G-y.fragIndex;if(!(N<=0)){if(!x||Q<0||Q-N>hw)return t(`Resync: offset=${Q} bChunks=${N} chunk=`+JSON.stringify(x)),L();if(!(Q>=N))return U(G-y.fragIndex,!1)}},W=(x,N,G)=>{l&&l.abort(),l=Tr(this.urlResolver.resolve(x,!0,this.lowLatency),N,G,()=>this._retryCallback()).withTimeout(os).withRetryCount(mu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(x,N)=>{W(T,G=>{if(!d())return;y=G;let Q=!!y.lowLatency;Q!==this.lowLatency&&b(Q);let Z=0;for(let F=0;F<y.dur.length;++F)Z+=y.dur[F];Z>0&&(Si(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Z/y.dur.length)),i({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,x(A(N))},()=>this._handleNetworkError())},nextChunk:H}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Si(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{let{videoElement:y,logger:O}=this.params,C=g(e.jidxUrl),$,B,U,L,A=0,H,W,k,x=()=>{H&&(clearTimeout(H),H=void 0);let V=Math.max(mw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ue=A+V,ve=ie(),Pe=Math.min(1e4,ue-ve);A=ve;let lt=()=>{l||d()&&C.seek(()=>{d()&&(A=ie(),N(),x())})};Pe>0?H=window.setTimeout(()=>{this.paused?x():lt()},Pe):lt()},N=()=>{let V;for(;V=C.nextChunk(L);)L=V,Kt(V);let ue=C.nextChunk(U);if(ue){if(U&&ue.discontinuity){O("Detected discontinuity; restarting playback"),this.paused?x():(I(),this._initPlayerWith(e));return}F(ue)}else x()},G=(V,ue)=>{if(!d()||!this.sourceBuffer)return;let ve,Pe,lt,Jt=ct=>{window.setTimeout(()=>{d()&&G(V,ue)},ct)};if(this.sourceBuffer.updating)O("Source buffer is updating; delaying appendBuffer"),Jt(100);else{let ct=ie(),xt=y.currentTime;!this.paused&&y.buffered.length>1&&W===xt&&ct-k>500&&(O("Stall suspected; trying to fix"),this._fixupStall()),W!==xt&&(W=xt,k=ct);let Xt=this._getBufferSizeSec();if(Xt>30)O(`Buffered ${Xt} seconds; delaying appendBuffer`),Jt(2e3);else try{this.sourceBuffer.appendBuffer(V),this.videoPlayStarted?(this.bufferStates.push({ts:ct,buf:Xt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ue&&ue()}catch(Or){if(Or.name==="QuotaExceededError")O("QuotaExceededError; delaying appendBuffer"),lt=this.sourceBuffer.buffered.length,lt!==0&&(ve=this.sourceBuffer.buffered.start(0),Pe=xt,Pe-ve>4&&this.sourceBuffer.remove(ve,Pe-3)),Jt(1e3);else throw Or}}},Q=()=>{B&&$&&(O([`Appending chunk, sz=${B.byteLength}:`,JSON.stringify(U)]),G(B,function(){B=null,N()}))},Z=V=>e.fragUrlTemplate.replace("%%id%%",V.chunkIdx),F=V=>{d()&&h(Z(V),(ue,ve)=>{if(d()){if(ve/=1e3,B=ue,U=V,n=V.startTS,ve){let Pe=Math.min(10,V.dur/ve);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}Q()}},()=>this._handleNetworkError())},Kt=V=>{d()&&(Si(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Z(V),!1)))},ut=V=>{d()&&(e.cachedHeader=V,G(V,()=>{$=!0,Q()}))};s=!0,C.seek(V=>{if(d()){if(A=ie(),!V){x();return}L=V,!dw(T)||V.startTS>T?F(V):(U=V,N())}},T),e.cachedHeader?ut(e.cachedHeader):p(e.headerUrl,ut,()=>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(),ns(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 ns(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=ie();if(this.chunkRateEstimator.addInterval(p,f,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&hu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ie();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Tr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(os).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;be(e).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))},pw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as bw,filter as ib,fromEvent as Sw,interval as gw,isHigher as vw,isInvariantQuality as yw,isLower as Tw,merge as Iw,Subject as ab,Subscription as Ew}from"@vkontakte/videoplayer-shared";var bu=class{constructor(){this.onDroopedVideoFramesLimit$=new ab;this.subscription=new Ew;this.playing=!1;this.tracks=[];this.forceChecker$=new ab;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&&!yw(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&&vw(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=gw(this.droppedFramesChecker.checkTime).pipe(ib(()=>this.playing),ib(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(bw(this.droppedFramesChecker.checkTime)),r=Iw(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])=>Tw(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}},us=bu;import{map as xw,Observable as Pw}from"@vkontakte/videoplayer-shared";import{fromEvent as Aw}from"@vkontakte/videoplayer-shared";var vi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var ww=(a,e)=>new Pw(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||vi()))},R(R({},r),e));i.observe(a);let s=Aw(document,"visibilitychange").pipe(xw(n=>!document.hidden||vi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Me=ww;var Bw=["paused","playing","ready"],Vw=["paused","playing","ready"],yi=class{constructor(e){this.subscription=new Cw;this.videoState=new M("stopped");this.representations$=new gu([]);this.textTracksManager=new Le;this.droppedFramesManager=new us;this.maxSeekBackTime$=new gu(1/0);this.zeroTime$=new gu(void 0);this.liveOffset=new et;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:ob.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=St(u.name))!=null?r:Ow(u.video),d=u.bitrate/1e3,p=R({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Su(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(Vw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Bw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ae(this.params.source.url,u))}return;default:return sb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:ob.WTF,message:"DashLiveProvider internal logic error",thrown:i})};lb(this.videoState.stateChangeStarted$.pipe(ls(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ls(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=pe(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(re(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=me(this.video);this.subscription.add(this.representations$.pipe(ls(i=>i.map(({track:s})=>s)),ub(i=>!!i.length),Mw()).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(Lw(),ls(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(kw({zeroTime:this.zeroTime$.pipe(ub(Su)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(We(this.video,this.params.desiredState.isLooped,t)).add(fe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Re(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(Me(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&Dw(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 sb(i.to)}},t)).add(lb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,$w(["init"])).pipe(Rw(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),he(this.video)}createLiveDashPlayer(){let e=new gi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&Su(t)?t:vt(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:S})=>S.id===s))==null?void 0:f.representation;nb(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;nb(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ae(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var cb=yi;var rt=(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 nR,assertNonNullable as oR,debounce as uR,ErrorCategory as Wu,filter as BS,filterChanged as Qu,fromEvent as lR,isLowerOrEqual as VS,isNonNullable as cR,isInvariantQuality as dR,map as _S,merge as Ds,observableFrom as pR,observeElementSize as hR,once as NS,Subscription as fR,ValueSubject as mR}from"@vkontakte/videoplayer-shared";var cs=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}},Ir=class extends cs{constructor(){super(),this.listeners||cs.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)}},Ti=class{constructor(){Object.defineProperty(this,"signal",{value:new Ir,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&&(Ti.prototype[Symbol.toStringTag]="AbortController",Ir.prototype[Symbol.toStringTag]="AbortSignal");function ds(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(!ds({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Ii=ds({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),db=Ii?vu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,it=Ii?db.fetch:window.fetch,vO=Ii?db.Request:window.Request,at=Ii?Ti:window.AbortController,yO=Ii?Ir:window.AbortSignal;var xb=Ge(hi(),1);var st=()=>window.ManagedMediaSource||window.MediaSource,ps=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},pb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},hb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Ts,clientChecker as ys}from"@vkontakte/videoplayer-shared";var Ce=document.createElement("video"),Fw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',qw='video/mp4; codecs="hev1.1.6.L93.B0"',Pb='video/webm; codecs="vp09.00.10.08"',Ab='video/webm; codecs="av01.0.00M.08"',Uw='audio/mp4; codecs="mp4a.40.2"',Hw='audio/webm; codecs="opus"',fb,mb,_t={mms:ps(),mse:pb(),hls:!!((fb=Ce.canPlayType)!=null&&fb.call(Ce,"application/x-mpegurl")||(mb=Ce.canPlayType)!=null&&mb.call(Ce,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},bb,Sb,Se={mp4:!!((bb=Ce.canPlayType)!=null&&bb.call(Ce,"video/mp4")),webm:!!((Sb=Ce.canPlayType)!=null&&Sb.call(Ce,"video/webm")),cmaf:!0},fs,gb,ms,vb,bs,yb,Ss,Tb,gs,Ib,vs,Eb,ge={h264:!!((gb=(fs=st())==null?void 0:fs.isTypeSupported)!=null&&gb.call(fs,Fw)),h265:!!((vb=(ms=st())==null?void 0:ms.isTypeSupported)!=null&&vb.call(ms,qw)),vp9:!!((yb=(bs=st())==null?void 0:bs.isTypeSupported)!=null&&yb.call(bs,Pb)),av1:!!((Tb=(Ss=st())==null?void 0:Ss.isTypeSupported)!=null&&Tb.call(Ss,Ab)),aac:!!((Ib=(gs=st())==null?void 0:gs.isTypeSupported)!=null&&Ib.call(gs,Uw)),opus:!!((Eb=(vs=st())==null?void 0:vs.isTypeSupported)!=null&&Eb.call(vs,Hw))},Er=(ge.h264||ge.h265)&&ge.aac,Nt,jw=()=>w(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(q(R({},a),{video:q(R({},a.video),{contentType:Ab})})),window.navigator.mediaCapabilities.decodingInfo(q(R({},a),{video:q(R({},a.video),{contentType:Pb})}))]);Nt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{jw()}catch(a){console.error(a)}var xr=_t.hls&&Se.mp4,wb=()=>Object.keys(ge).filter(a=>ge[a]),kb=(a,e=!1,t=!1)=>{let r=_t.mse||_t.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&Se.mp4&&Er;case"DASH_WEBM":return r&&Se.webm&&ge.vp9&&ge.opus;case"DASH_WEBM_AV1":return r&&Se.webm&&ge.av1&&ge.opus;case"DASH_STREAMS":return r&&(Se.mp4&&Er||Se.webm&&(ge.vp9||ge.av1)&&(ge.opus||ge.aac));case"DASH_LIVE":return _t.mse&&Se.mp4&&Er;case"DASH_LIVE_CMAF":return r&&Se.mp4&&Er&&Se.cmaf;case"DASH_ONDEMAND":return r&&Se.mp4&&Er;case"HLS":case"HLS_ONDEMAND":return xr||e&&_t.mse&&Se.mp4&&Er;case"HLS_LIVE":case"HLS_LIVE_CMAF":return xr;case"MPEG":return Se.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return _t.webrtc&&_t.ws&&ge.h264&&(Se.mp4||Se.webm);default:return Ts(i)}})},hs=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 Nt?Nt[t].smooth?[t,e]:Nt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Nt?Nt[t].powerEfficient?[t,e]:Nt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ts(a)}return[e,t]},Rb=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...hs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ys.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",...hs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...hs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...hs(a),...i,"HLS","HLS_ONDEMAND"];default:Ts(e)}return xr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Lb=({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=ys.isMac&&ys.isSafari;if(ys.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:Ts(a)}else xr&&!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"],$b=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,xb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as Ei}from"@vkontakte/videoplayer-shared";var Mb=a=>{if(!a)return{id:"EmptyResponse",category:Ei.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Ei.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:Ei.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:Ei.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ei.PARSER,message:"Response is valid XML, but parser failed"}};var xi=(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 ju,assertNonNullable as Qt,combine as ks,ErrorCategory as Tt,filter as Rs,filterChanged as RS,fromEvent as $r,interval as Gu,isNonNullable as LS,map as Yu,merge as Mr,Subject as $S,Subscription as MS,tap as Zk,throttle as eR,clientChecker as tR,ValueSubject as oe}from"@vkontakte/videoplayer-shared";var Lr=Ge(hi(),1);var Gw=(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)},Yw=a=>window.clearTimeout(a),Cb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Tu=Cb?Gw:window.requestIdleCallback,OO=Cb?Yw:window.cancelIdleCallback;var IS=Ge(ts(),1);import{assertNever as Ww,ErrorCategory as Db,clientChecker as Iu,Subject as Ob}from"@vkontakte/videoplayer-shared";var Qw=16,Bb=!1;try{Bb=Iu.isSafari&&!!Iu.macVersion&&Iu.macVersion<=Qw}catch(a){console.error(a)}var Eu=class{constructor(e){this.bufferFull$=new Ob;this.error$=new Ob;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:Db.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return w(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return w(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return w(this,null,function*(){return new Promise(t=>{let r;Bb&&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:Db.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:Ww(t)}}},Vb=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 Rr,assertNonNullable as ze,ErrorCategory as Gt,fromEvent as Vu,getExponentialDelay as _u,isNonNullable as Nu,isNullable as De,once as Gk,Subject as Yk,Subscription as Wk,ValueSubject as Wi}from"@vkontakte/videoplayer-shared";var j=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 Pr=class extends j{};var Pi=class extends j{};var Ai=class extends j{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 wi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ki=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var J=class extends j{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ft=class extends J{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 Li=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mi=class extends J{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 Ci=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Di=class extends J{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 j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends J{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 Vi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ni=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Fi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qi=class extends J{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 Ui=class extends J{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 Hi=class extends J{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 Kw={ftyp:Ai,moov:wi,moof:ki,mdat:Ri,sidx:Ft,trak:Li,mdia:Oi,mfhd:Ni,tkhd:Bi,traf:Fi,tfhd:qi,tfdt:Ui,trun:Hi,minf:Vi,sv3d:$i,st3d:Mi,prhd:Ci,proj:_i,equi:Di,uuid:Pi,unknown:Pr},qt=class a{constructor(e={}){this.options=R({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=Kw[e];return r?new r(t,new a):new Pr(t,new a)}};var Ar=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Xw=new TextDecoder("ascii"),Zw=a=>Xw.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",ek=a=>{let e=new Ft(a,new qt),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})},tk=(a,e)=>{let r=new qt().parse(a),i=new Ar(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},rk=(a,e)=>{let r=new qt().parse(a),s=new Ar(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},ik=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 qt().parse(a),i=new Ar(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},_b={validateData:Zw,parseInit:ik,getIndexRange:()=>{},parseSegments:ek,parseFeedableSegmentChunk:tk,getSegmentEndTime:rk};import{assertNonNullable as Au,isNonNullable as Ub,isNullable as sk}from"@vkontakte/videoplayer-shared";import{assertNever as ak}from"@vkontakte/videoplayer-shared";var Nb={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"}},Fb=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=ji(a,t),i=r in Nb,s=i?Nb[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=ji(u),d=l*je(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ji=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*je(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*je(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*je(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},qe=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ji(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:ak(e)}},Ut=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Fb(r);if(!e(i))return;i.type==="master"&&Ut(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},qb=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Fb(a);return Ut(i.value,({tag:s,type:n,value:o})=>(s===17143?e=qe(o,n):s===17026?t=qe(o,n):s===17029&&(r=qe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Hb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],nk=[231,22612,22743,167,171,163,160,175],ok=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Ut(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let S=qe(f,h);l=ji(S)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=qe(f,h):p===17545?i=qe(f,h):p===21420&&l===475249515?u=qe(f,h):p===374648427?Ut(f,({tag:S,type:g,value:I})=>S===30321?(c=qe(I,g)===1,!1):!0):s&&n&&Hb.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:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},uk=a=>{if(sk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},lk=(a,e)=>{let t=!1,r=!1,i=o=>Ub(o.time)&&Ub(o.position),s=[],n;return Ut(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=qe(l,u));break;case 183:break;case 241:n&&(n.position=qe(l,u));break;default:t&&Hb.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},ck=a=>{let e=0,t=!1;try{Ut(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):nk.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},jb={validateData:qb,parseInit:ok,getIndexRange:uk,parseSegments:lk,parseFeedableSegmentChunk:ck};var wr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return jb;case"mp4":return _b}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Cu=Ge(pS(),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 fS,isNullable as mS}from"@vkontakte/videoplayer-shared";var hS=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var bS=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},Ht=(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)=>mS(s)?o:mS(u)?s:s.padStart(parseInt(u,10),"0"))}return t},gS=(a,e)=>{var T,y,O,C,$,B,U,L,A,H,W,k,x,N,G,Q,Z,F,Kt,ut,V,ue,ve,Pe,lt,Jt,ct,xt,Xt,Or,ll,cl,dl,pl,hl,fl,ml,bl,Sl,gl,vl,yl,Tl,Il,El,xl,Pl,Al,wl,kl;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(O=(y=(T=s.querySelector("BaseURL"))==null?void 0:T.textContent)==null?void 0:y.trim())!=null?O:"",u=n.children,l=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],S=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=bS(h);else if(f){let le=bS(f);fS(le)&&(p=le)}else S&&(p=parseInt(S,10));let g=0,I=($=(C=s.getAttribute("profiles"))==null?void 0:C.split(","))!=null?$:[];for(let le of u){let kg=(B=le.getAttribute("id"))!=null?B:"id"+(g++).toString(10),Br=(U=le.getAttribute("mimeType"))!=null?U:"",Ks=(L=le.getAttribute("codecs"))!=null?L:"",Js=(A=le.getAttribute("contentType"))!=null?A:Br==null?void 0:Br.split("/")[0],Rg=(W=(H=le.getAttribute("profiles"))==null?void 0:H.split(","))!=null?W:[],Lg=(k=le.getAttribute("lang"))!=null?k:void 0,$g=(G=(N=(x=le.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:N.trim())!=null?G:void 0,Mg=le.querySelectorAll("Representation"),Cg=le.querySelector("SegmentTemplate"),Dg=(Z=(Q=le.querySelector("Role"))==null?void 0:Q.getAttribute("value"))!=null?Z:void 0,Vr=Js,ee={id:kg,language:Lg,isDefault:Dg==="main",label:$g,codecs:Ks,hdr:Vr==="video"&&Mu(Ks),mime:Br,representations:[]};for(let X of Mg){let Og=(F=X.getAttribute("lang"))!=null?F:void 0,Bg=(Kt=X.getAttribute("label"))!=null?Kt:void 0,Vg=(ue=(V=(ut=X.querySelector("BaseURL"))==null?void 0:ut.textContent)==null?void 0:V.trim())!=null?ue:"",Xs=new URL(Vg||o,e).toString(),Zt=(ve=X.getAttribute("mimeType"))!=null?ve:Br,ha=(lt=(Pe=X.getAttribute("codecs"))!=null?Pe:Ks)!=null?lt:"",Zs;if(Js==="text"){let Pt=X.getAttribute("id")||"",en=Pt.includes("_auto");Zs={id:Pt,isAuto:en,kind:"text",url:Xs}}else{let Pt=(ct=(Jt=X.getAttribute("contentType"))!=null?Jt:Zt==null?void 0:Zt.split("/")[0])!=null?ct:Js,en=(Xt=(xt=le.getAttribute("profiles"))==null?void 0:xt.split(","))!=null?Xt:[],_g=parseInt((Or=X.getAttribute("width"))!=null?Or:"",10),Rl=parseInt((ll=X.getAttribute("height"))!=null?ll:"",10),Ll=parseInt((cl=X.getAttribute("bandwidth"))!=null?cl:"",10)/1e3,$l=(dl=X.getAttribute("frameRate"))!=null?dl:"",Ng=(pl=X.getAttribute("quality"))!=null?pl:void 0,Fg=$l?hS($l):void 0,qg=(hl=X.getAttribute("id"))!=null?hl:"id"+(g++).toString(10),Ug=Pt==="video"?`${Rl}p`:Pt==="audio"?`${Ll}Kbps`:ha,Hg=`${qg}@${Ug}`,jg=[...I,...Rg,...en],tn,Gg=X.querySelector("SegmentBase"),At=(fl=X.querySelector("SegmentTemplate"))!=null?fl:Cg;if(Gg){let wt=(bl=(ml=X.querySelector("SegmentBase Initialization"))==null?void 0:ml.getAttribute("range"))!=null?bl:"",[kt,an]=wt.split("-").map(er=>parseInt(er,10)),dt={from:kt,to:an},_r=(Sl=X.querySelector("SegmentBase"))==null?void 0:Sl.getAttribute("indexRange"),[sn,fa]=_r?_r.split("-").map(er=>parseInt(er,10)):[],Nr=_r?{from:sn,to:fa}:void 0;tn={type:"byteRange",url:Xs,initRange:dt,indexRange:Nr}}else if(At){let wt={representationId:(gl=X.getAttribute("id"))!=null?gl:void 0,bandwidth:(vl=X.getAttribute("bandwidth"))!=null?vl:void 0},kt=parseInt((yl=At.getAttribute("timescale"))!=null?yl:"",10),an=(Tl=At.getAttribute("initialization"))!=null?Tl:"",dt=At.getAttribute("media"),_r=(El=parseInt((Il=At.getAttribute("startNumber"))!=null?Il:"",10))!=null?El:1,sn=Ht(an,wt);if(!dt)throw new ReferenceError("No media attribute in SegmentTemplate");let fa=(xl=At.querySelectorAll("SegmentTimeline S"))!=null?xl:[],Nr=[],er=0,nn="",on=0;if(fa.length){let ma=_r,Be=0;for(let tr of fa){let He=parseInt((Pl=tr.getAttribute("d"))!=null?Pl:"",10),Rt=parseInt((Al=tr.getAttribute("r"))!=null?Al:"",10)||0,ba=parseInt((wl=tr.getAttribute("t"))!=null?wl:"",10);Be=Number.isFinite(ba)?ba:Be;let un=He/kt*1e3,ln=Be/kt*1e3;for(let Sa=0;Sa<Rt+1;Sa++){let Wg=Ht(dt,q(R({},wt),{segmentNumber:ma.toString(10),segmentTime:(Be+Sa*He).toString(10)})),Ml=(ln!=null?ln:0)+Sa*un,Qg=Ml+un;ma++,Nr.push({time:{from:Ml,to:Qg},url:Wg})}Be+=(Rt+1)*He,er+=(Rt+1)*un}on=Be/kt*1e3,nn=Ht(dt,q(R({},wt),{segmentNumber:ma.toString(10),segmentTime:Be.toString(10)}))}else if(fS(p)){let Be=parseInt((kl=At.getAttribute("duration"))!=null?kl:"",10)/kt*1e3,tr=Math.ceil(p/Be),He=0;for(let Rt=1;Rt<tr;Rt++){let ba=Ht(dt,q(R({},wt),{segmentNumber:Rt.toString(10),segmentTime:He.toString(10)}));Nr.push({time:{from:He,to:He+Be},url:ba}),He+=Be}on=He,nn=Ht(dt,q(R({},wt),{segmentNumber:tr.toString(10),segmentTime:He.toString(10)}))}let Yg={time:{from:on,to:1/0},url:nn};tn={type:"template",baseUrl:Xs,segmentTemplateUrl:dt,initUrl:sn,totalSegmentsDurationMs:er,segments:Nr,nextSegmentBeyondManifest:Yg,timescale:kt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pt||!Zt)continue;let rn={video:"video",audio:"audio",text:"text"}[Pt];if(!rn)continue;Vr||(Vr=rn),Zs={id:Hg,kind:rn,segmentReference:tn,profiles:jg,duration:p,bitrate:Ll,mime:Zt,codecs:ha,width:_g,height:Rl,fps:Fg,quality:Ng}}ee.language||(ee.language=Og),ee.label||(ee.label=Bg),ee.mime||(ee.mime=Zt),ee.codecs||(ee.codecs=ha),ee.hdr||(ee.hdr=Vr==="video"&&Mu(ha)),ee.representations.push(Zs)}Vr&&i[Vr].push(ee)}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,streams:i}};var Gi=Ge(hi(),1);import{videoSizeToQuality as jk}from"@vkontakte/videoplayer-shared";var vS=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?St(s):void 0)!=null?o:jk({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},yS=({id:a,bitrate:e})=>({id:a,bitrate:e}),Is=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Gi.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Gi.default)(t,-1)},TS=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Ou=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Gi.default)(r.split("."),0),isDefault:i}),Bu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Gi.default)(i.split("."),0)}),Es=a=>"url"in a,jt=a=>a.type==="template",Yi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Qi=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new Wi(0);this.onLastSegment$=new Wi(!1);this.fullyBuffered$=new Wi(!1);this.playingRepresentation$=new Wi(void 0);this.playingRepresentationInit$=new Wi(void 0);this.error$=new Yk;this.gaps=[];this.subscription=new Wk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new at;this.destroyAbortController=new at;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=Rr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){let t=this.representations.get(e);ze(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Vb(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 l=rt(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);ze(r,"No init buffer for starting representation"),ze(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=Rr(this.destroyAbortController.signal,function(e,t=!1){return te(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);ze(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(De(s)||De(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),ze(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=Rr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){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 d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!jt(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);ze(i);let s=this.segments.get(r);ze(s,"No segments for starting representation");let n=this.initData.get(r);if(ze(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.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 at,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(De(e)||De(this.downloadingRepresentationId)||De(this.playingRepresentationId)||De(this.sourceBuffer)||!De(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(ze(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.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 p=rt(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=rt(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,Lr.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&&rt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Lr.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||!jt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>q(R({},p),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Lr.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(c)>=Math.floor(p.time.from)&&Math.floor(c)<=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,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ze(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBufferAfterStall(){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(!jt(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=Ht(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:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,S=p>r||b||f===0&&r===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&p<=r+g||h<=r+g;return(d==="none"||d==="partially_ejected"&&S&&I&&this.sourceBuffer&&!xi(this.sourceBuffer.buffered,r))&&S&&I});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return w(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return w(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Rr(o,function(){return te(this,null,function*(){let c=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=wr(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Yi(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return w(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Rr(n,function(){return te(this,null,function*(){let u=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Vu(window,"online").pipe(Gk()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Yi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(jt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Lr.default)(e,0).byte.from,to:(0,Lr.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:Gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!jt(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 d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category: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)}onSomeTemplateDataLoaded(n){return w(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=wr(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({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:d}=c,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:l;if(c.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,S=p?d.byte.to-r:e.byteLength,g=b<i,I=S<=i;if(d.status==="downloading"&&g&&I){d.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+b,h),T=this.getCurrentPosition();Nu(T)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-T,this.bufferAccumulation.accumulated.push({segmentView:v,segmentProgress:c}),this.activeSegments.delete(c));let y=({segmentView:O,segmentProgress:C})=>this.sourceBufferTaskQueue.append(O,s).then($=>$&&!s.aborted?this.onSegmentFullyAppended(C,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(y),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||De(T))&&(y({segmentView:v,segmentProgress:c}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&!I&&(c.loadedBytes=Math.min(h,i-b),c.loadedBytes>c.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),T=c.loadedBytes===h?v:wr(o.mime).parseFeedableSegmentChunk(v);T!=null&&T.byteLength&&(d.status="partially_fed",c.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,s).then(y=>{if(s.aborted)n();else if(y)c.fedBytes+=T.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return w(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,f=d<i,b=p<=i;if(f){if(c.status==="downloading"&&b){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),g=l.loadedBytes===h?S:wr(u.mime).parseFeedableSegmentChunk(S);g!=null&&g.byteLength&&(c.status="partially_fed",l.feedingBytes+=g.byteLength,(yield this.sourceBufferTaskQueue.append(g,s))&&!s.aborted?(l.fedBytes+=g.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,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",Es(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,IS.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return w(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Rr(this.destroyAbortController.signal,function(){return te(this,null,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,wr(e.mime),i)).then(o=>w(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&jt(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})}dropBuffer(){return w(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return w(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return w(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||De(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(u.time),i=n(i);let l=Es(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}pruneBufferOld(e,t,r=!1){return w(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||De(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=l=>{var d;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=Es(l)?(d=l.size)!=null?d: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,d=this.sourceBuffer.buffered.end(l)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)){s=c,n=d;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 d of c)d.time.from>e+l&&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(De(this.sourceBuffer)||De(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 zi=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var ES=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 Ki,assertNever as xS,fromEvent as PS,merge as Qk,now as Fu,Subscription as zk,ValueSubject as qu}from"@vkontakte/videoplayer-shared";var xs=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new qu(void 0);this.lastConnectionReused$=new qu(void 0);this.lastRequestFirstBytes$=new qu(void 0);this.abortAllController=new at;this.subscription=new zk;this.fetchManifest=Ki(this.abortAllController.signal,function(e){return te(this,null,function*(){let t=e;this.requestQuic&&(t=zi(t));let r=yield it(t,{signal:this.abortAllController.signal}).catch(Ji);return r?(this.onHeadersReceived(r.headers),r.text()):null})}.bind(this));this.fetch=Ki(this.abortAllController.signal,function(l){return te(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var B,U;let c=e,d=new Headers;if(r)switch(t){case 0:{d.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:xS(t)}this.requestQuic&&(c=zi(c));let p=this.abortAllController.signal,h;if(n){let L=new at;if(h=Qk(PS(this.abortAllController.signal,"abort"),PS(n,"abort")).subscribe(()=>{try{L.abort()}catch(A){Ji(A)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(A){Ji(A)}p=L.signal}let f=Fu(),b=yield it(c,{priority:s,headers:d,signal:p}).catch(Ji),S=Fu();if(!b)return h==null||h.unsubscribe(),null;if((B=this.throughputEstimator)==null||B.addRawRtt(S-f),!b.ok||!b.body)return h==null||h.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!i&&!o)return h==null||h.unsubscribe(),b.arrayBuffer();let[g,I]=b.body.tee(),v=g.getReader();o&&((U=this.throughputEstimator)==null||U.trackStream(I,u));let T=0,y=new Uint8Array(0),O=!1,C=L=>{h==null||h.unsubscribe(),O=!0,Ji(L)},$=Ki(p,function(H){return te(this,arguments,function*({done:L,value:A}){if(T===0&&this.lastRequestFirstBytes$.next(Fu()-f),p.aborted){h==null||h.unsubscribe();return}if(!L&&A){let W=new Uint8Array(y.length+A.length);W.set(y),W.set(A,y.length),y=W,T+=A.byteLength,i==null||i(new DataView(y.buffer),T),yield v==null?void 0:v.read().then($,C)}})}.bind(this));return yield v==null?void 0:v.read().then($,C),h==null||h.unsubscribe(),O?null:y.buffer})}.bind(this));this.fetchByteRangeRepresentation=Ki(this.abortAllController.signal,function(e,t,r){return te(this,null,function*(){var g;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(g=e.indexRange)!=null?g: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 S=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=Ki(this.abortAllController.signal,function(e,t){return te(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>q(R({},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}=ES(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return w(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:xS(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Ji=a=>{if(!Yi(a))throw a};var Yt=(a,e,t)=>t*e+(1-t)*a,Uu=(a,e)=>a.reduce((t,r)=>t+r,0)/e,AS=(a,e,t,r)=>{let i=0,s=t,n=Uu(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 Kk,ValueSubject as wS}from"@vkontakte/videoplayer-shared";var yt=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 wS(e.initial),this.debounced$=new wS(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ne(`raw_${t}`),this.smoothedSeries$=new ne(`smoothed_${t}`),this.reportedSeries$=new ne(`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+=je(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)&&(Kk(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 Ps=class extends yt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Yt(this.slow,e,this.params.emaAlphaSlow),this.fast=Yt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var As=class extends yt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Uu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Yt(this.emaSmoothed,e,this.params.emaAlpha);let r=AS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var ws=class extends yt{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?Yt(this.smoothed,t,this.params.emaAlpha):t}};var Wt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Ps({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new As({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 ws(R({initial:e,label:"liveEdgeDelay"},t))}};var Hu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var CS=["timeupdate","progress","play","seeked","stalled","waiting"];var Ls=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new MS;this.representationSubscription=new MS;this.state$=new M("none");this.currentVideoRepresentation$=new oe(void 0);this.currentVideoRepresentationInit$=new oe(void 0);this.currentAudioRepresentation$=new oe(void 0);this.currentVideoSegmentLength$=new oe(0);this.currentAudioSegmentLength$=new oe(0);this.error$=new $S;this.lastConnectionType$=new oe(void 0);this.lastConnectionReused$=new oe(void 0);this.lastRequestFirstBytes$=new oe(void 0);this.isLive$=new oe(!1);this.liveDuration$=new oe(0);this.liveAvailabilityStartTime$=new oe(void 0);this.bufferLength$=new oe(0);this.liveLoadBufferLength$=new oe(0);this.livePositionFromPlayer$=new oe(0);this.timeInWaiting=0;this.isActiveLowLatency$=new oe(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new $S;this.gapWatchdogActive=!1;this.destroyController=new at;this.initManifest=ju(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var i;this.element=e,this.manifestUrlString=ae(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Tt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=ju(this.destroyController.signal,function(){return te(this,null,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:Tt.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t;try{t=gS(e!=null?e:"",this.manifestUrlString)}catch(o){let u=(s=Mb(e))!=null?s:{id:"ManifestParsing",category:Tt.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(u)}if(!t)return null;let r=(o,u,l)=>{var c,d,p,h;return!!((d=(c=this.element)==null?void 0:c.canPlayType)!=null&&d.call(c,u)&&((h=(p=st())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${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:p,codecs:h})=>r(o,p,h)),c=new Set(l.map(({codecs:p})=>p)),d=$b(c);if(d&&(i[o]=l.filter(({codecs:p})=>p.startsWith(d))),o==="video"){let p=this.tuning.preferHDR,h=i.video.some(b=>b.hdr),f=i.video.some(b=>!b.hdr);tR.isHDR&&p&&h?i.video=i.video.filter(b=>b.hdr):f&&(i.video=i.video.filter(b=>!b.hdr))}}return q(R({},t),{streams:i})})}.bind(this));this.initRepresentations=ju(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var d;Qt(this.manifest),Qt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add($r(p,"error").pipe(Rs(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Tt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?hb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ps())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 Qi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],LS(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Qi("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(Gu(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=eu(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Mr(...CS.filter(p=>p!=="waiting").map(p=>$r(this.element,p))).pipe(Yu(p=>this.element?rt(this.element.buffered,this.element.currentTime*1e3):0),RS(),Rs(p=>!!p),Zk(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(RS()).subscribe(h=>Hu(this.element,1))),this.representationSubscription.add(ks({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Rs(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(ks({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b,v=1;Math.abs(I)>S&&(v=1+Math.sign(I)*g),Hu(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,S;let f=0;if(h){let g=((S=(b=this.element)==null?void 0:b.currentTime)!=null?S:0)*1e3;f=Math.min(...this.bufferManagers.map(v=>{var T,y;return(y=(T=v.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?y:g}))-g}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(ks({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(eR(1e3)).subscribe(b=>w(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(Qt(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,g=eu(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,O=isFinite(h)?h:f,C=this.isActiveLowLatency$.getValue(),$=I<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(C&&$);let B="none";if(C?B="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&$?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(U=>U.proceedLowLatencyLive()),B="active_low_latency"):g!==0&&O<v?B="live_forward_buffering":O<v+y&&(B="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),B==="live_forward_buffering"||B==="live_with_target_offset"){let U=p-(v+T),L=this.normolizeLiveOffset(Math.trunc(g+U/S)),A=Math.abs(L-g),H;!h||A<=this.tuning.dashCmafLive.offsetCalculationError?H=g:L>0&&A>this.tuning.dashCmafLive.offsetCalculationError?H=L:H=0,this.manifestUrlString=ae(this.manifestUrlString,H,2)}B!=="none"&&B!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=Mr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Yu(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=Mr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Yu(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Mr(this.forceEnded$,ks({allBuffersFull:u,someBufferEnded:l}).pipe(Rs(({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:Tt.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 c=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{var h;return(h=p.duration)!=null?h:0})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&LS(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=Gu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:Tt.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new xs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Wt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,R({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return w(this,null,function*(){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=ae(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video),yield(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(...CS.map(e=>$r(this.element,e)),$r(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Tt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add($r(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add($r(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&xi(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.startAccumulateBufferAfterStall(),(r=this.audioBufferManager)==null||r.startAccumulateBufferAfterStall(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=Gu(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:Tt.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return w(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u;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),xi(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.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}updateLive(){return w(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield 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 $s=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ms=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/je(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=R({},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*je(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 DS=`attribute vec2 a_vertex;
36
+ [best video track] ${O==null?void 0:O.quality}
37
+ [selected video track] ${C==null?void 0:C.quality}
38
+ `}),db(r,p,C,c)},pb=(a,e,t,{throughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var f;ub(t,lb);let c=i.considerPlaybackRate&&Se(s)?s:1,l=[...t].sort(Su(-1)),d=a.bitrate;gw(d);let p=c*cb(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),h;return Se(r)&&isFinite(r)&&(h=l.find(b=>Se(b.bitrate)?r-d>=b.bitrate*p:!0)),h||(h=ds(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&&db(i,u,h,o)};var re=a=>new URL(a).hostname;import{assertNever as Sb,assertNonNullable as vb,combine as _w,debounce as Nw,ErrorCategory as yb,filter as Tb,filterChanged as Fw,isNonNullable as Eu,map as bs,merge as Ib,observableFrom as qw,once as Uw,Subscription as Hw,ValueSubject as xu,videoQualityToHeight as jw,videoSizeToQuality as Gw}from"@vkontakte/videoplayer-shared";var hb=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"))},ve=a=>R(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!hb(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return hb(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as hs,isNullable as Tw,assertNonNullable as Ei}from"@vkontakte/videoplayer-shared";import{isNonNullable as fb,assertNonNullable as ps,now as vw}from"@vkontakte/videoplayer-shared";function ie(){return vw()}function vu(a){return ie()-a}function yu(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 mb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Pr(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;ps(l);let L=vu(l),F;if(L<b){F=b-L,setTimeout(g,F);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,$()},S=L=>(s=L,N),T=L=>(d=L,N),v=()=>(h="json",N),y=()=>{if(!u){if(--c>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=L=>(p=L,N),$=()=>{l=ie(),n=new i,n.open("get",a);let L=0,F,_=0,w=()=>(ps(l),Math.max(l,Math.max(F||0,_||0)));if(s&&n.addEventListener("progress",x=>{let D=ie();s.updateChunk&&x.loaded>L&&(s.updateChunk(w(),x.loaded-L),L=x.loaded,F=D)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;ps(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let D=n.response.byteLength-L;D&&s.updateChunk&&s.updateChunk(w(),D)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),p){let x=()=>{ps(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(_=ie(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),N},N={withBitrateReporting:S,withParallel:I,withJSONResponse:v,withRetryCount:L=>(c=L,N),withRetryInterval:(L,F)=>(fb(L)&&(b=L),fb(F)&&(f=F),N),withTimeout:L=>(o=L,N),withFinally:T,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return N}var Ti=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 Ii=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ie(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ie()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Pr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ie()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ie();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){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 fs=1e4,Tu=3;var Iw=6e4,Ew=10,xw=1,Pw=500,xi=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 Ti(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=yu(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=yu(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||hs(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{mb(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ii(Tu,fs,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 y=s&&(!l||l===this.rep);return y||t("Not running!"),y},p=(y,I,$)=>{u&&u.abort(),u=Pr(this.urlResolver.resolve(y,!1),I,$,()=>this._retryCallback()).withTimeout(fs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Tu).withFinally(()=>{u=null}).send()},h=(y,I,$)=>{Ei(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),I,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=y=>{let I=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${I}=>${y}`),r.playbackRate=y)},b=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let $=ie()-1e4,G=0;for(let C=0;C<this.bufferStates.length;C++){let H=this.bufferStates[C];y=Math.min(y,H.buf),H.ts<$&&G++}this.bufferStates.splice(0,G),t(`update playback rate; minBuffer=${y} drop=${G} jitter=${this.sourceJitter}`);let O=y-xw;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?f(1.15):O>1?f(1.1):O>.3?f(1.05):f(1)}},S=y=>{let I,$=()=>I&&I.start?I.start.length:0,G=x=>I.start[x]/1e3,O=x=>I.dur[x]/1e3,C=x=>I.fragIndex+x,H=(x,D)=>({chunkIdx:C(x),startTS:G(x),dur:O(x),discontinuity:D}),N=()=>{let x=0;if(I&&I.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Q=D;this.sourceJitter>1&&(Q+=this.sourceJitter-1);let X=I.dur.length-1;for(;X>=0&&(Q-=I.dur[X],!(Q<=0));--X);x=Math.min(X,I.dur.length-1-W),x=Math.max(x,0)}return H(x,!0)},L=x=>{let D=$();if(!(D<=0)){if(hs(x)){for(let W=0;W<D;W++)if(G(W)>x)return H(W)}return N()}},F=x=>{let D=$(),W=x?x.chunkIdx+1:0,Q=W-I.fragIndex;if(!(D<=0)){if(!x||Q<0||Q-D>Ew)return t(`Resync: offset=${Q} bChunks=${D} chunk=`+JSON.stringify(x)),N();if(!(Q>=D))return H(W-I.fragIndex,!1)}},_=(x,D,W)=>{c&&c.abort(),c=Pr(this.urlResolver.resolve(x,!0,this.lowLatency),D,W,()=>this._retryCallback()).withTimeout(fs).withRetryCount(Tu).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(x,D)=>{_(y,W=>{if(!d())return;I=W;let Q=!!I.lowLatency;Q!==this.lowLatency&&b(Q);let X=0;for(let ce=0;ce<I.dur.length;++ce)X+=I.dur[ce];X>0&&(Ei(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(X/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,x(L(D))},()=>this._handleNetworkError())},nextChunk:F}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),Ei(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:y=>{let{videoElement:I,logger:$}=this.params,G=S(e.jidxUrl),O,C,H,N,L=0,F,_,w,x=()=>{F&&(clearTimeout(F),F=void 0);let A=Math.max(Pw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),le=L+A,Ie=ie(),ke=Math.min(1e4,le-Ie);L=Ie;let pt=()=>{c||d()&&G.seek(()=>{d()&&(L=ie(),D(),x())})};ke>0?F=window.setTimeout(()=>{this.paused?x():pt()},ke):pt()},D=()=>{let A;for(;A=G.nextChunk(N);)N=A,kt(A);let le=G.nextChunk(H);if(le){if(H&&le.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?x():(T(),this._initPlayerWith(e));return}ce(le)}else x()},W=(A,le)=>{if(!d()||!this.sourceBuffer)return;let Ie,ke,pt,tr=ht=>{window.setTimeout(()=>{d()&&W(A,le)},ht)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),tr(100);else{let ht=ie(),Rt=I.currentTime;!this.paused&&I.buffered.length>1&&_===Rt&&ht-w>500&&($("Stall suspected; trying to fix"),this._fixupStall()),_!==Rt&&(_=Rt,w=ht);let rr=this._getBufferSizeSec();if(rr>30)$(`Buffered ${rr} seconds; delaying appendBuffer`),tr(2e3);else try{this.sourceBuffer.appendBuffer(A),this.videoPlayStarted?(this.bufferStates.push({ts:ht,buf:rr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),le&&le()}catch(Fr){if(Fr.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),pt=this.sourceBuffer.buffered.length,pt!==0&&(Ie=this.sourceBuffer.buffered.start(0),ke=Rt,ke-Ie>4&&this.sourceBuffer.remove(Ie,ke-3)),tr(1e3);else throw Fr}}},Q=()=>{C&&O&&($([`Appending chunk, sz=${C.byteLength}:`,JSON.stringify(H)]),W(C,function(){C=null,D()}))},X=A=>e.fragUrlTemplate.replace("%%id%%",A.chunkIdx),ce=A=>{d()&&h(X(A),(le,Ie)=>{if(d()){if(Ie/=1e3,C=le,H=A,n=A.startTS,Ie){let ke=Math.min(10,A.dur/Ie);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ke:ke}Q()}},()=>this._handleNetworkError())},kt=A=>{d()&&(Ei(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(X(A),!1)))},dt=A=>{d()&&(e.cachedHeader=A,W(A,()=>{O=!0,Q()}))};s=!0,G.seek(A=>{if(d()){if(L=ie(),!A){x();return}N=A,!Tw(y)||A.startTS>y?ce(A):(H=A,D())}},y),e.cachedHeader?dt(e.cachedHeader):p(e.headerUrl,dt,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},l}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),hs(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,Ei(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return hs(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=ie();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&&vu(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=ie();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Pr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(fs).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;ve(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))},Iw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Aw,filter as bb,fromEvent as ww,interval as kw,isHigher as Rw,isInvariantQuality as $w,isLower as Lw,merge as Mw,Subject as gb,Subscription as Cw}from"@vkontakte/videoplayer-shared";var Iu=class{constructor(){this.onDroopedVideoFramesLimit$=new gb;this.subscription=new Cw;this.playing=!1;this.tracks=[];this.forceChecker$=new gb;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&&!$w(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&&Rw(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(ww(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=kw(this.droppedFramesChecker.checkTime).pipe(bb(()=>this.playing),bb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(Aw(this.droppedFramesChecker.checkTime)),r=Mw(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}},ms=Iu;import{map as Dw,Observable as Bw}from"@vkontakte/videoplayer-shared";import{fromEvent as Ow}from"@vkontakte/videoplayer-shared";var Pi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Vw=(a,e)=>new Bw(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Pi()))},k(k({},r),e));i.observe(a);let s=Ow(document,"visibilitychange").pipe(Dw(n=>!document.hidden||Pi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Be=Vw;var Ww=["paused","playing","ready"],Yw=["paused","playing","ready"],Ai=class{constructor(e){this.subscription=new Hw;this.videoState=new M("stopped");this.representations$=new xu([]);this.textTracksManager=new Ce;this.droppedFramesManager=new ms;this.maxSeekBackTime$=new xu(1/0);this.zeroTime$=new xu(void 0);this.liveOffset=new rt;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:yb.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=yt(u.name))!=null?r:Gw(u.video),d=u.bitrate/1e3,p=k({},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),Eu(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(Yw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Ww.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ae(this.params.source.url,u))}return;default:return Sb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:yb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Ib(this.videoState.stateChangeStarted$.pipe(bs(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(bs(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=fe(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(re(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=ge(this.video);this.subscription.add(this.representations$.pipe(bs(i=>i.map(({track:s})=>s)),Tb(i=>!!i.length),Uw()).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(Fw(),bs(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(_w({zeroTime:this.zeroTime$.pipe(Tb(Eu)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(ze(this.video,this.params.desiredState.isLooped,t)).add(be(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Me(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(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&jw(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 Sb(i.to)}},t)).add(Ib(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,qw(["init"])).pipe(Nw(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),me(this.video)}createLiveDashPlayer(){let e=new xi({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&&Eu(t)?t:Tt(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;vb(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;vb(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ae(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Eb=Ai;var at=(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 gR,assertNonNullable as SR,debounce as vR,ErrorCategory as Xu,filter as zg,filterChanged as Zu,fromEvent as yR,isNonNullable as TR,map as Kg,merge as qs,observableFrom as IR,observeElementSize as ER,once as Jg,Subscription as xR,ValueSubject as PR}from"@vkontakte/videoplayer-shared";var gs=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}},Ar=class extends gs{constructor(){super(),this.listeners||gs.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)}},wi=class{constructor(){Object.defineProperty(this,"signal",{value:new Ar,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&&(wi.prototype[Symbol.toStringTag]="AbortController",Ar.prototype[Symbol.toStringTag]="AbortSignal");function Ss(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 Pu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Ss({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 ki=Ss({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),xb=ki?Pu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,st=ki?xb.fetch:window.fetch,RB=ki?xb.Request:window.Request,nt=ki?wi:window.AbortController,$B=ki?Ar:window.AbortSignal;var Vb=Ye(Si(),1);var ot=()=>window.ManagedMediaSource||window.MediaSource,vs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Pb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Ab=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as ks,clientChecker as ws}from"@vkontakte/videoplayer-shared";var Oe=document.createElement("video"),Kw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Jw='video/mp4; codecs="hev1.1.6.L93.B0"',_b='video/webm; codecs="vp09.00.10.08"',Nb='video/webm; codecs="av01.0.00M.08"',Xw='audio/mp4; codecs="mp4a.40.2"',Zw='audio/webm; codecs="opus"',wb,kb,jt={mms:vs(),mse:Pb(),hls:!!((wb=Oe.canPlayType)!=null&&wb.call(Oe,"application/x-mpegurl")||(kb=Oe.canPlayType)!=null&&kb.call(Oe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Rb,$b,ye={mp4:!!((Rb=Oe.canPlayType)!=null&&Rb.call(Oe,"video/mp4")),webm:!!(($b=Oe.canPlayType)!=null&&$b.call(Oe,"video/webm")),cmaf:!0},Ts,Lb,Is,Mb,Es,Cb,xs,Db,Ps,Bb,As,Ob,Te={h264:!!((Lb=(Ts=ot())==null?void 0:Ts.isTypeSupported)!=null&&Lb.call(Ts,Kw)),h265:!!((Mb=(Is=ot())==null?void 0:Is.isTypeSupported)!=null&&Mb.call(Is,Jw)),vp9:!!((Cb=(Es=ot())==null?void 0:Es.isTypeSupported)!=null&&Cb.call(Es,_b)),av1:!!((Db=(xs=ot())==null?void 0:xs.isTypeSupported)!=null&&Db.call(xs,Nb)),aac:!!((Bb=(Ps=ot())==null?void 0:Ps.isTypeSupported)!=null&&Bb.call(Ps,Xw)),opus:!!((Ob=(As=ot())==null?void 0:As.isTypeSupported)!=null&&Ob.call(As,Zw))},wr=(Te.h264||Te.h265)&&Te.aac,Gt,ek=()=>R(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(V(k({},a),{video:V(k({},a.video),{contentType:Nb})})),window.navigator.mediaCapabilities.decodingInfo(V(k({},a),{video:V(k({},a.video),{contentType:_b})}))]);Gt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{ek()}catch(a){console.error(a)}var kr=jt.hls&&ye.mp4,Fb=()=>Object.keys(Te).filter(a=>Te[a]),qb=(a,e=!1,t=!1)=>{let r=jt.mse||jt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&ye.mp4&&wr;case"DASH_WEBM":return r&&ye.webm&&Te.vp9&&Te.opus;case"DASH_WEBM_AV1":return r&&ye.webm&&Te.av1&&Te.opus;case"DASH_STREAMS":return r&&(ye.mp4&&wr||ye.webm&&(Te.vp9||Te.av1)&&(Te.opus||Te.aac));case"DASH_LIVE":return jt.mse&&ye.mp4&&wr;case"DASH_LIVE_CMAF":return r&&ye.mp4&&wr&&ye.cmaf;case"DASH_ONDEMAND":return r&&ye.mp4&&wr;case"HLS":case"HLS_ONDEMAND":return kr||e&&jt.mse&&ye.mp4&&wr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return kr;case"MPEG":return ye.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return jt.webrtc&&jt.ws&&Te.h264&&(ye.mp4||ye.webm);default:return ks(i)}})},ys=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 Gt?Gt[t].smooth?[t,e]:Gt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Gt?Gt[t].powerEfficient?[t,e]:Gt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:ks(a)}return[e,t]},Ub=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ys(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ws.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",...ys(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ys(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ys(a),...i,"HLS","HLS_ONDEMAND"];default:ks(e)}return kr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Hb=({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=ws.isMac&&ws.isSafari;if(ws.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:ks(a)}else kr&&!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"]},Au=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],jb=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,Vb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as Ri}from"@vkontakte/videoplayer-shared";var Gb=a=>{if(!a)return{id:"EmptyResponse",category:Ri.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Ri.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:Ri.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:Ri.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ri.PARSER,message:"Response is valid XML, but parser failed"}};var $i=(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 zu,assertNonNullable as Zt,combine as Bs,ErrorCategory as Et,filter as Os,filterChanged as Ug,fromEvent as Or,interval as Ku,isNonNullable as Hg,map as Ju,merge as Vr,Subject as jg,Subscription as Gg,tap as cR,throttle as lR,clientChecker as dR,ValueSubject as oe,flattenObject as sa,getTraceSubscriptionMethod as pR}from"@vkontakte/videoplayer-shared";var Dr=Ye(Si(),1);var tk=(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)},rk=a=>window.clearTimeout(a),Wb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",wu=Wb?tk:window.requestIdleCallback,GB=Wb?rk:window.cancelIdleCallback;var Bg=Ye(us(),1);import{assertNever as ik,ErrorCategory as Yb,clientChecker as ku,Subject as Qb}from"@vkontakte/videoplayer-shared";var ak=16,zb=!1;try{zb=ku.isSafari&&!!ku.macVersion&&ku.macVersion<=ak}catch(a){console.error(a)}var Ru=class{constructor(e){this.bufferFull$=new Qb;this.error$=new Qb;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:Yb.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return R(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return R(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let r;zb&&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:Yb.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:ik(t)}}},Kb=Ru;var $u=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 Cr,assertNonNullable as Je,ErrorCategory as Kt,fromEvent as Hu,getExponentialDelay as ju,isNonNullable as Gu,isNullable as Ve,once as tR,Subject as rR,Subscription as iR,ValueSubject as Zi}from"@vkontakte/videoplayer-shared";var j=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 Rr=class extends j{};var Li=class extends j{};var Mi=class extends j{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 Ci=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var J=class extends j{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Wt=class extends J{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 Oi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends J{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 Ni=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Fi=class extends J{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var qi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends J{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 Hi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Wi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yi=class extends J{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 Qi=class extends J{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 zi=class extends J{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 nk={ftyp:Mi,moov:Ci,moof:Di,mdat:Bi,sidx:Wt,trak:Oi,mdia:qi,mfhd:Gi,tkhd:Ui,traf:Wi,tfhd:Yi,tfdt:Qi,trun:zi,minf:Hi,sv3d:Vi,st3d:_i,prhd:Ni,proj:ji,equi:Fi,uuid:Li,unknown:Rr},Yt=class a{constructor(e={}){this.options=k({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=nk[e];return r?new r(t,new a):new Rr(t,new a)}};var $r=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 uk=new TextDecoder("ascii"),ck=a=>uk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",lk=a=>{let e=new Wt(a,new Yt),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})},dk=(a,e)=>{let r=new Yt().parse(a),i=new $r(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)},pk=(a,e)=>{let r=new Yt().parse(a),s=new $r(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},hk=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 Yt().parse(a),i=new $r(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},Jb={validateData:ck,parseInit:hk,getIndexRange:()=>{},parseSegments:lk,parseFeedableSegmentChunk:dk,getSegmentEndTime:pk};import{assertNonNullable as Mu,isNonNullable as tg,isNullable as mk}from"@vkontakte/videoplayer-shared";import{assertNever as fk}from"@vkontakte/videoplayer-shared";var Xb={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"}},Zb=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=Ki(a,t),i=r in Xb,s=i?Xb[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=Ki(u),d=c*We(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}},Ki=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*We(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*We(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*We(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},He=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ki(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:fk(e)}},Qt=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Zb(r);if(!e(i))return;i.type==="master"&&Qt(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},eg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Zb(a);return Qt(i.value,({tag:s,type:n,value:o})=>(s===17143?e=He(o,n):s===17026?t=He(o,n):s===17029&&(r=He(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var rg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],bk=[231,22612,22743,167,171,163,160,175],gk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,c,l=!1,d=0;return Qt(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=He(f,h);c=Ki(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=He(f,h):p===17545?i=He(f,h):p===21420&&c===475249515?u=He(f,h):p===374648427?Qt(f,({tag:g,type:S,value:T})=>g===30321?(l=He(T,S)===1,!1):!0):s&&n&&rg.includes(p)&&(o=!0),!o}),Mu(e,"Failed to parse webm Segment start"),Mu(t,"Failed to parse webm Segment end"),Mu(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}}}},Sk=a=>{if(mk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},vk=(a,e)=>{let t=!1,r=!1,i=o=>tg(o.time)&&tg(o.position),s=[],n;return Qt(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=He(c,u));break;case 183:break;case 241:n&&(n.position=He(c,u));break;default:t&&rg.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}}})},yk=a=>{let e=0,t=!1;try{Qt(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):bk.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},ig={validateData:eg,parseInit:gk,getIndexRange:Sk,parseSegments:vk,parseFeedableSegmentChunk:yk};var Lr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return ig;case"mp4":return Jb}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Nu=Ye(Pg(),1);var _u=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 wg,isNullable as kg}from"@vkontakte/videoplayer-shared";var Ag=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Rg=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},zt=(a,e)=>{let t=a;t=(0,Nu.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,Nu.default)(t,n,(o,u)=>kg(s)?o:kg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Lg=(a,e)=>{var y,I,$,G,O,C,H,N,L,F,_,w,x,D,W,Q,X,ce,kt,dt,A,le,Ie,ke,pt,tr,ht,Rt,rr,Fr,mc,bc,gc,Sc,vc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc,Rc,$c,Lc,Mc,Cc,Dc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=($=(I=(y=s.querySelector("BaseURL"))==null?void 0:y.textContent)==null?void 0:I.trim())!=null?$:"",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=Rg(h);else if(f){let de=Rg(f);wg(de)&&(p=de)}else g&&(p=parseInt(g,10));let S=0,T=(O=(G=s.getAttribute("profiles"))==null?void 0:G.split(","))!=null?O:[];for(let de of u){let US=(C=de.getAttribute("id"))!=null?C:"id"+(S++).toString(10),qr=(H=de.getAttribute("mimeType"))!=null?H:"",rn=(N=de.getAttribute("codecs"))!=null?N:"",an=(L=de.getAttribute("contentType"))!=null?L:qr==null?void 0:qr.split("/")[0],HS=(_=(F=de.getAttribute("profiles"))==null?void 0:F.split(","))!=null?_:[],jS=(w=de.getAttribute("lang"))!=null?w:void 0,GS=(W=(D=(x=de.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:D.trim())!=null?W:void 0,WS=de.querySelectorAll("Representation"),YS=de.querySelector("SegmentTemplate"),QS=(X=(Q=de.querySelector("Role"))==null?void 0:Q.getAttribute("value"))!=null?X:void 0,Ur=an,ee={id:US,language:jS,isDefault:QS==="main",label:GS,codecs:rn,hdr:Ur==="video"&&_u(rn),mime:qr,representations:[]};for(let Z of WS){let zS=(ce=Z.getAttribute("lang"))!=null?ce:void 0,KS=(kt=Z.getAttribute("label"))!=null?kt:void 0,JS=(le=(A=(dt=Z.querySelector("BaseURL"))==null?void 0:dt.textContent)==null?void 0:A.trim())!=null?le:"",sn=new URL(JS||o,e).toString(),ir=(Ie=Z.getAttribute("mimeType"))!=null?Ie:qr,ya=(pt=(ke=Z.getAttribute("codecs"))!=null?ke:rn)!=null?pt:"",nn;if(an==="text"){let $t=Z.getAttribute("id")||"",on=$t.includes("_auto");nn={id:$t,isAuto:on,kind:"text",url:sn}}else{let $t=(ht=(tr=Z.getAttribute("contentType"))!=null?tr:ir==null?void 0:ir.split("/")[0])!=null?ht:an,on=(rr=(Rt=de.getAttribute("profiles"))==null?void 0:Rt.split(","))!=null?rr:[],XS=parseInt((Fr=Z.getAttribute("width"))!=null?Fr:"",10),Bc=parseInt((mc=Z.getAttribute("height"))!=null?mc:"",10),Oc=parseInt((bc=Z.getAttribute("bandwidth"))!=null?bc:"",10)/1e3,Vc=(gc=Z.getAttribute("frameRate"))!=null?gc:"",ZS=(Sc=Z.getAttribute("quality"))!=null?Sc:void 0,ev=Vc?Ag(Vc):void 0,tv=(vc=Z.getAttribute("id"))!=null?vc:"id"+(S++).toString(10),rv=$t==="video"?`${Bc}p`:$t==="audio"?`${Oc}Kbps`:ya,iv=`${tv}@${rv}`,av=[...T,...HS,...on],un,sv=Z.querySelector("SegmentBase"),Lt=(yc=Z.querySelector("SegmentTemplate"))!=null?yc:YS;if(sv){let Mt=(Ic=(Tc=Z.querySelector("SegmentBase Initialization"))==null?void 0:Tc.getAttribute("range"))!=null?Ic:"",[Ct,ln]=Mt.split("-").map(ar=>parseInt(ar,10)),ft={from:Ct,to:ln},Hr=(Ec=Z.querySelector("SegmentBase"))==null?void 0:Ec.getAttribute("indexRange"),[dn,Ta]=Hr?Hr.split("-").map(ar=>parseInt(ar,10)):[],jr=Hr?{from:dn,to:Ta}:void 0;un={type:"byteRange",url:sn,initRange:ft,indexRange:jr}}else if(Lt){let Mt={representationId:(xc=Z.getAttribute("id"))!=null?xc:void 0,bandwidth:(Pc=Z.getAttribute("bandwidth"))!=null?Pc:void 0},Ct=parseInt((Ac=Lt.getAttribute("timescale"))!=null?Ac:"",10),ln=(wc=Lt.getAttribute("initialization"))!=null?wc:"",ft=Lt.getAttribute("media"),Hr=(Rc=parseInt((kc=Lt.getAttribute("startNumber"))!=null?kc:"",10))!=null?Rc:1,dn=zt(ln,Mt);if(!ft)throw new ReferenceError("No media attribute in SegmentTemplate");let Ta=($c=Lt.querySelectorAll("SegmentTimeline S"))!=null?$c:[],jr=[],ar=0,pn="",hn=0;if(Ta.length){let Ia=Hr,_e=0;for(let sr of Ta){let Ge=parseInt((Lc=sr.getAttribute("d"))!=null?Lc:"",10),Dt=parseInt((Mc=sr.getAttribute("r"))!=null?Mc:"",10)||0,Ea=parseInt((Cc=sr.getAttribute("t"))!=null?Cc:"",10);_e=Number.isFinite(Ea)?Ea:_e;let fn=Ge/Ct*1e3,mn=_e/Ct*1e3;for(let xa=0;xa<Dt+1;xa++){let ov=zt(ft,V(k({},Mt),{segmentNumber:Ia.toString(10),segmentTime:(_e+xa*Ge).toString(10)})),_c=(mn!=null?mn:0)+xa*fn,uv=_c+fn;Ia++,jr.push({time:{from:_c,to:uv},url:ov})}_e+=(Dt+1)*Ge,ar+=(Dt+1)*fn}hn=_e/Ct*1e3,pn=zt(ft,V(k({},Mt),{segmentNumber:Ia.toString(10),segmentTime:_e.toString(10)}))}else if(wg(p)){let _e=parseInt((Dc=Lt.getAttribute("duration"))!=null?Dc:"",10)/Ct*1e3,sr=Math.ceil(p/_e),Ge=0;for(let Dt=1;Dt<sr;Dt++){let Ea=zt(ft,V(k({},Mt),{segmentNumber:Dt.toString(10),segmentTime:Ge.toString(10)}));jr.push({time:{from:Ge,to:Ge+_e},url:Ea}),Ge+=_e}hn=Ge,pn=zt(ft,V(k({},Mt),{segmentNumber:sr.toString(10),segmentTime:Ge.toString(10)}))}let nv={time:{from:hn,to:1/0},url:pn};un={type:"template",baseUrl:sn,segmentTemplateUrl:ft,initUrl:dn,totalSegmentsDurationMs:ar,segments:jr,nextSegmentBeyondManifest:nv,timescale:Ct}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!$t||!ir)continue;let cn={video:"video",audio:"audio",text:"text"}[$t];if(!cn)continue;Ur||(Ur=cn),nn={id:iv,kind:cn,segmentReference:un,profiles:av,duration:p,bitrate:Oc,mime:ir,codecs:ya,width:XS,height:Bc,fps:ev,quality:ZS}}ee.language||(ee.language=zS),ee.label||(ee.label=KS),ee.mime||(ee.mime=ir),ee.codecs||(ee.codecs=ya),ee.hdr||(ee.hdr=Ur==="video"&&_u(ya)),ee.representations.push(nn)}Ur&&i[Ur].push(ee)}return{dynamic:c,liveAvailabilityStartTime:d,duration:p,streams:i}};var Ji=Ye(Si(),1);import{videoSizeToQuality as eR}from"@vkontakte/videoplayer-shared";var Mg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?yt(s):void 0)!=null?o:eR({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},Cg=({id:a,bitrate:e})=>({id:a,bitrate:e}),Rs=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Ji.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Ji.default)(t,-1)},Dg=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),qu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Ji.default)(r.split("."),0),isDefault:i}),Uu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Ji.default)(i.split("."),0)}),$s=a=>"url"in a,ut=a=>a.type==="template",Xi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ea=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new Zi(0);this.onLastSegment$=new Zi(!1);this.fullyBuffered$=new Zi(!1);this.playingRepresentation$=new Zi(void 0);this.playingRepresentationInit$=new Zi(void 0);this.error$=new rR;this.gaps=[];this.subscription=new iR;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new nt;this.destroyAbortController=new nt;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=Cr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){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 Kb(this.sourceBuffer),this.subscription.add(Hu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Kt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Kt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Hu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Kt.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,$u(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=at(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);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=Cr(this.destroyAbortController.signal,function(e,t=!1){return te(this,null,function*(){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(Ve(s)||Ve(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();Gu(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=Cr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){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||!ut(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);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=!!(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 nt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;if(Ve(e)||Ve(this.downloadingRepresentationId)||Ve(this.playingRepresentationId)||Ve(this.sourceBuffer)||!Ve(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(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=at(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)&&$u(this.sourceBuffer.buffered)>=this.bufferLimit){let d=at(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,Dr.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&&at(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Dr.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;Gu(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||!ut(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>V(k({},p),{status:"none",size:void 0})),c=(i=this.segments.get(o.id))!=null?i:[],l=(n=(s=(0,Dr.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;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(!ut(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=zt(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,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&!$i(this.sourceBuffer.buffered,r))&&g&&T});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}loadSegments(e,t,r="auto"){return R(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return R(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Cr(o,function(){return te(this,null,function*(){let l=ju(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=yield 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=Lr(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&c?yield Promise.all(c):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Xi(l)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return R(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Cr(n,function(){return te(this,null,function*(){let u=ju(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),Hu(window,"online").pipe(tR()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Xi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(ut(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Dr.default)(e,0).byte.from,to:(0,Dr.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:Kt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ut(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:Kt.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)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Lr(o.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(c.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.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,S=b<i,T=g<=i;if(d.status==="downloading"&&S&&T){d.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+b,h),y=this.getCurrentPosition();Gu(y)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-y,this.bufferAccumulation.accumulated.push({segmentView:v,segmentProgress:l}),this.activeSegments.delete(l));let I=({segmentView:$,segmentProgress:G})=>this.sourceBufferTaskQueue.append($,s).then(O=>O&&!s.aborted?this.onSegmentFullyAppended(G,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(I),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||Ve(y))&&(I({segmentView:v,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&!T&&(l.loadedBytes=Math.min(h,i-b),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+b+l.feedingBytes,l.loadedBytes-l.feedingBytes),y=l.loadedBytes===h?v:Lr(o.mime).parseFeedableSegmentChunk(v);y!=null&&y.byteLength&&(d.status="partially_fed",l.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(I=>{if(s.aborted)n();else if(I)l.fedBytes+=y.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return R(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let c of this.activeSegments){let{segment:l}=c;if(c.representationId!==t)continue;if(s.aborted){n();continue}let d=l.byte.from-r,p=l.byte.to-r,h=p-d+1,f=d<i,b=p<=i;if(f){if(l.status==="downloading"&&b){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(g,s))&&!s.aborted?this.onSegmentFullyAppended(c,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(c.loadedBytes=Math.min(h,i-d),c.loadedBytes>c.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+c.feedingBytes,c.loadedBytes-c.feedingBytes),S=c.loadedBytes===h?g:Lr(u.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(l.status="partially_fed",c.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(c.fedBytes+=S.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,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",$s(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=wu(()=>(0,Bg.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return R(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Cr(this.destroyAbortController.signal,function(){return te(this,null,function*(){let o=ju(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Lr(e.mime),i)).then(o=>R(this,null,function*(){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&&ut(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:Kt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return R(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return R(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||Ve(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=$s(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?(yield Promise.all(i.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1})}pruneBufferOld(e,t,r=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||Ve(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=$s(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=wu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Kt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Ve(this.sourceBuffer)||Ve(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 ta=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Og=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 ra,assertNever as Vg,fromEvent as _g,merge as aR,now as ia,Subscription as sR,ValueSubject as Wu,flattenObject as Br}from"@vkontakte/videoplayer-shared";var Ls=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new Wu(void 0);this.lastConnectionReused$=new Wu(void 0);this.lastRequestFirstBytes$=new Wu(void 0);this.abortAllController=new nt;this.subscription=new sR;this.fetchManifest=ra(this.abortAllController.signal,function(e){return te(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ta(r));let i=yield st(r,{signal:this.abortAllController.signal}).catch(aa);return i?(t.log("success",Br({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Br({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=ra(this.abortAllController.signal,function(c){return te(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var L,F;let l=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(l,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),l=_.toString();break}default:Vg(t)}this.requestQuic&&(l=ta(l));let h=this.abortAllController.signal,f;if(n){let _=new nt;if(f=aR(_g(this.abortAllController.signal,"abort"),_g(n,"abort")).subscribe(()=>{try{_.abort()}catch(w){aa(w)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(w){aa(w)}h=_.signal}let b=ia();p.log("startRequest",Br({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield st(l,{priority:s,headers:d,signal:h}).catch(aa),S=ia();if(!g)return p.error("error",{message:"No response in request"}),p.end(),f==null||f.unsubscribe(),null;if((L=this.throughputEstimator)==null||L.addRawRtt(S-b),!g.ok||!g.body){f==null||f.unsubscribe();let _=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:_}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let _=ia(),w={requestStartedAt:b,requestEndedAt:_,duration:_-b};return p.log("endRequest",Br(w)),p.end(),g.arrayBuffer()}let[T,v]=g.body.tee(),y=T.getReader();o&&((F=this.throughputEstimator)==null||F.trackStream(v,u));let I=0,$=new Uint8Array(0),G=!1,O=_=>{f==null||f.unsubscribe(),G=!0,aa(_)},C=ra(h,function(x){return te(this,arguments,function*({done:_,value:w}){if(I===0&&this.lastRequestFirstBytes$.next(ia()-b),h.aborted){f==null||f.unsubscribe();return}if(!_&&w){let D=new Uint8Array($.length+w.length);D.set($),D.set(w,$.length),$=D,I+=w.byteLength,i==null||i(new DataView($.buffer),I),yield y==null?void 0:y.read().then(C,O)}})}.bind(this));yield y==null?void 0:y.read().then(C,O),f==null||f.unsubscribe();let H=ia(),N={failed:G,requestStartedAt:b,requestEndedAt:H,duration:H-b};return G?(p.error("endRequest",Br(N)),p.end(),null):(p.log("endRequest",Br(N)),p.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=ra(this.abortAllController.signal,function(e,t,r){return te(this,null,function*(){var S;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=(S=e.indexRange)!=null?S: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 T=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!T)return null;b=new DataView(T)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=ra(this.abortAllController.signal,function(e,t){return te(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>V(k({},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}=Og(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return R(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Vg(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},aa=a=>{if(!Xi(a))throw a};var Jt=(a,e,t)=>t*e+(1-t)*a,Yu=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Ng=(a,e,t,r)=>{let i=0,s=t,n=Yu(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 nR,ValueSubject as Fg}from"@vkontakte/videoplayer-shared";var It=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 Fg(e.initial),this.debounced$=new Fg(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ne(`raw_${t}`),this.smoothedSeries$=new ne(`smoothed_${t}`),this.reportedSeries$=new ne(`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+=We(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)&&(nR(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 Ms=class extends It{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Jt(this.slow,e,this.params.emaAlphaSlow),this.fast=Jt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Cs=class extends It{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Yu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Jt(this.emaSmoothed,e,this.params.emaAlpha);let r=Ng(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Ds=class extends It{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Jt(this.smoothed,t,this.params.emaAlpha):t}};var Xt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Ms({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Cs({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 Ds(k({initial:e,label:"liveEdgeDelay"},t))}};var Qu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var Wg=["timeupdate","progress","play","seeked","stalled","waiting"];var Vs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Gg;this.representationSubscription=new Gg;this.state$=new M("none");this.currentVideoRepresentation$=new oe(void 0);this.currentVideoRepresentationInit$=new oe(void 0);this.currentAudioRepresentation$=new oe(void 0);this.currentVideoSegmentLength$=new oe(0);this.currentAudioSegmentLength$=new oe(0);this.error$=new jg;this.lastConnectionType$=new oe(void 0);this.lastConnectionReused$=new oe(void 0);this.lastRequestFirstBytes$=new oe(void 0);this.isLive$=new oe(!1);this.liveDuration$=new oe(0);this.liveAvailabilityStartTime$=new oe(void 0);this.bufferLength$=new oe(0);this.liveLoadBufferLength$=new oe(0);this.livePositionFromPlayer$=new oe(0);this.timeInWaiting=0;this.isActiveLowLatency$=new oe(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new jg;this.gapWatchdogActive=!1;this.destroyController=new nt;this.initManifest=zu(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Et.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=zu(this.destroyController.signal,function(){return te(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Et.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t;try{t=Lg(e!=null?e:"",this.manifestUrlString)}catch(u){let c=(n=Gb(e))!=null?n:{id:"ManifestParsing",category:Et.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=ot())==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=jb(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);dR.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=V(k({},t),{streams:i});return this.tracer.log("updateManifestEnd",sa(s)),s})}.bind(this));this.initRepresentations=zu(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",sa({initialVideo:e,initialAudio:t,sourceHls:r})),Zt(this.manifest),Zt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Or(p,"error").pipe(Os(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Et.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Ab():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&vs())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 ea("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Hg(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new ea("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(Ku(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=nu(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Vr(...Wg.filter(p=>p!=="waiting").map(p=>Or(this.element,p))).pipe(Ju(p=>this.element?at(this.element.buffered,this.element.currentTime*1e3):0),Ug(),Os(p=>!!p),cR(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Ug()).subscribe(h=>Qu(this.element,1))),this.representationSubscription.add(Bs({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Os(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(Bs({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,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-b,v=1;Math.abs(T)>g&&(v=1+Math.sign(T)*S),Qu(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let S=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(v=>{var y,I;return(I=(y=v.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?I:S}))-S}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(Bs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(lR(1e3)).subscribe(b=>R(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(Zt(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,S=nu(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,$=isFinite(h)?h:f,G=this.isActiveLowLatency$.getValue(),O=T<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLowLatency$.next(G&&O);let C="none";if(G?C="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&O?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(H=>H.proceedLowLatencyLive()),C="active_low_latency"):S!==0&&$<v?C="live_forward_buffering":$<v+I&&(C="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),C==="live_forward_buffering"||C==="live_with_target_offset"){let H=p-(v+y),N=this.normolizeLiveOffset(Math.trunc(S+H/g)),L=Math.abs(N-S),F;!h||L<=this.tuning.dashCmafLive.offsetCalculationError?F=S:N>0&&L>this.tuning.dashCmafLive.offsetCalculationError?F=N:F=0,this.manifestUrlString=ae(this.manifestUrlString,F,2)}C!=="none"&&C!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=Vr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Ju(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Vr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Ju(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Vr(this.forceEnded$,Bs({allBuffersFull:u,someBufferEnded:c}).pipe(Os(({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:Et.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Vr(...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),ut(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/1e3,this.audioBufferManager&&Hg(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=Ku(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:Et.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 Ls({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=Xt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,k({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return R(this,null,function*(){var r,i,s,n;Zt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ae(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio))})}initBuffer(){Zt(this.element),this.state$.setState("running"),this.subscription.add(Vr(...Wg.map(e=>Or(this.element,e)),Or(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Et.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Or(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Or(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&$i(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=V(k({},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=V(k({},s),{position:u})}this.tracer.log("stallIntervalCallback",sa(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=Ku(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:Et.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return R(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u,c;Zt(this.element),Zt(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),$i(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",sa({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=pR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return R(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield 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=V(k({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",sa(t)))}}};var _s=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ns=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/We(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=k({},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*We(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 Yg=`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 OS=`#ifdef GL_ES
69
+ `;var Qg=`#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 Cs=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 $s(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ms(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(DS,this.gl.VERTEX_SHADER),r=this.createShader(OS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var zt=class{constructor(e){this.subscription=new fR;this.videoState=new M("stopped");this.elementSize$=new mR(void 0);this.textTracksManager=new Le;this.droppedFramesManager=new us;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new as;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 nR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Cs(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=pe(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(re(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ls({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=me(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(BS(l=>!!l.length),NS()).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(BS(cR),NS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(_S(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(We(this.video,t.isLooped,i)),this.subscription.add(fe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Re(this.video,t.playbackRate,r.playbackRateState$,i)),s(hR(this.video),this.elementSize$),s(Me(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(oR(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Ou(h));let f=[];for(let b of h.representations){let S=yS(b);f.push(S),this.audioTracksMap.set(S,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(Bu(p));let h=[];for(let f of p.representations){let b=vS(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 c.text)for(let h of p.representations){let f=TS(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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=l=>e.error$.next({id:"RepresentationSwitch",category:Wu.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(Ds(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$,lR(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 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),l==="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: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(Qu()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Bu(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Qu()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Ou(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(_S(({to:l})=>l==="ready"),Qu());this.subscription.add(Ds(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Ds(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Ds(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,pR(["init"])).pipe(uR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var C,$,B,U,L,A,H,W,k,x,N,G,Q,Z;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(C=e.videoTrack.getState())==null?void 0:C.id,n=[...this.videoTracksMap.keys()].find(({id:F})=>F===i),o=t.currentVideoTrack$.getValue(),u=((U=(B=e.videoStream.getState())!=null?B:n&&(($=this.videoTracksMap.get(n))==null?void 0:$.stream))!=null?U:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:F})=>F===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=rt(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=(L=e.audioStream.getState())!=null?L:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(A=[...this.audioStreamsMap.keys()].find(({id:F})=>F===(f==null?void 0:f.id)))!=null?A:this.audioStreamsMap.keys().next().value,S=0;if(b){if(n&&!r){let F=Is(n,c,(H=this.audioStreamsMap.get(b))!=null?H:[]);S=Math.max(S,(W=F==null?void 0:F.bitrate)!=null?W:-1/0)}if(o){let F=Is(o,c,(k=this.audioStreamsMap.get(b))!=null?k:[]);S=Math.max(S,(x=F==null?void 0:F.bitrate)!=null?x:-1/0)}}let g=vt(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,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&&(g=(N=c.filter(F=>!dR(F.quality)).sort((F,Kt)=>{var ut,V;return((ut=Kt.bitrate)!=null?ut:0)-((V=F.bitrate)!=null?V:0)}).filter(F=>VS(F.quality,g.quality)&&VS(F.quality,I))[0])!=null?N:g);let v=r?g!=null?g:n:n!=null?n:g,T=b&&Is(v,c,(G=this.audioStreamsMap.get(b))!=null?G:[]),y=(Q=this.videoTracksMap.get(v))==null?void 0:Q.representation,O=T&&((Z=this.audioTracksMap.get(T))==null?void 0:Z.representation);if(y&&O)return[y,O];if(y&&!O&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){be(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),he(this.video)}};var Zi=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 FS,interval as bR,map as SR}from"@vkontakte/videoplayer-shared";var ea=class extends zt{constructor(e){super(e),this.liveOffset=new et}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(FS({interval:bR(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(FS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(SR(({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 US=Ge(ts(),1);import{assertNever as ta,assertNonNullable as qS,debounce as gR,ErrorCategory as Os,filter as vR,isNonNullable as yR,isNullable as TR,map as Bs,merge as IR,Observable as ER,observableFrom as xR,Subscription as PR,videoSizeToQuality as AR}from"@vkontakte/videoplayer-shared";var Ue={};var Cr=(a,e)=>new ER(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),ra=class{constructor(e){this.subscription=new PR;this.videoState=new M("initializing");this.textTracksManager=new Le;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:ta(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ta(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ta(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:ta(e)}break;default:ta(t)}};this.video=pe(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(re(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),he(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Os.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,US.default)(import("hls.js").then(i=>{e||(Ue.Hls=i.default,Ue.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){qS(Ue.Hls,"hls.js not loaded"),this.hls=new Ue.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){qS(Ue.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Os.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=me(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(We(this.video,e.isLooped,r)),this.subscription.add(fe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Re(this.video,e.playbackRate,i.playbackRateState$,r)),s(Me(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Bs(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Cr(this.hls,Ue.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Os.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(Cr(this.hls,Ue.Events.MANIFEST_PARSED).pipe(Bs(({levels:l})=>l.reduce((c,d)=>{var I,v;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(v=St((I=d.attrs.QUALITY)!=null?I:""))!=null?v:AR({width:h,height:f});if(!b)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,g={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:S};return this.trackLevels.set(p,{track:g,level:d}),c.push(g),c},[]))),t.availableVideoTracks$),s(Cr(this.hls,Ue.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Cr(this.hls,Ue.Events.LEVEL_LOADING).pipe(Bs(({url:l})=>re(l))),t.hostname$),s(Cr(this.hls,Ue.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(ft(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=Cr(this.hls,Ue.Events.LEVEL_SWITCHED).pipe(Bs(({level:l})=>n(this.hls.levels[l])));o.pipe(vR(yR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(ft(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(TR(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=IR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xR(["init"])).pipe(gR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return w(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield be(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Os.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 HS="X-Playback-Duration",zu=a=>w(void 0,null,function*(){var i;let e=yield it(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(HS)?parseInt(e.headers.get(HS),10):void 0});import{assertNever as MR,combine as CR,debounce as DR,ErrorCategory as _s,filter as OR,filterChanged as BR,isNonNullable as GS,isNullable as Ns,map as YS,merge as VR,observableFrom as _R,Subscription as NR,ValueSubject as Xu,VideoQuality as FR}from"@vkontakte/videoplayer-shared";var Ju=Ge(mo(),1);import{videoSizeToQuality as wR,getExponentialDelay as kR}from"@vkontakte/videoplayer-shared";var RR=a=>{let e=null;if(a.QUALITY&&(e=St(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=wR({width:t,height:r})}return e!=null?e:null},LR=(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 d=(0,Ju.default)(l[1].split(",").map(I=>I.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=RR(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,S;if(d.RESOLUTION){let[I,v]=d.RESOLUTION.split("x").map(T=>parseInt(T,10));I&&v&&(S={width:I,height:v})}let g=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:g,bandwidth:f,size:S,fps:b})}if(c){let d=(0,Ju.default)(c[1].split(",").map(b=>b.split("=")).map(([b,S])=>[b,S.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},$R=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Ku=0,jS=(r,...i)=>w(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield it(a)).text();Ku+=1;try{let{qualityManifests:o,textTracks:u}=LR(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(Ku<=t.manifestRetryMaxCount)return yield $R(kR(Ku-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),jS(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Vs=jS;var ia=class{constructor(e){this.subscription=new NR;this.videoState=new M("stopped");this.textTracksManager=new Le;this.manifests$=new Xu([]);this.liveOffset=new et;this.manifestStartTime$=new Xu(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 MR(t)}};var t;this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:FR.INVARIANT,url:this.params.source.url},Vs(ae(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:_s.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_s.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(re(this.params.source.url)),this.maxSeekBackTime$=new Xu((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:_s.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=me(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(fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,i.playbackRateState$,r)),s(Me(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(BR(),YS(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&&GS(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(re(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(CR({startTime:this.manifestStartTime$.pipe(OR(GS)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(YS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=VR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,_R(["init"])).pipe(DR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),he(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Ns(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[d,p]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ae(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),zu(n).then(l=>{var c;if(!Ns(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Ns(d)||!isFinite(d))try{it(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();zu(b).then(S=>{Ns(S)||this.maxSeekBackTime$.next(S)})}})}catch(p){}}})}playIfAllowed(){be(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:_s.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 qR,debounce as UR,ErrorCategory as Zu,fromEvent as el,isNonNullable as HR,isNullable as jR,map as WS,merge as QS,observableFrom as zS,Subscription as GR,ValueSubject as YR,VideoQuality as WR,clientChecker as QR}from"@vkontakte/videoplayer-shared";var aa=class{constructor(e){this.subscription=new GR;this.videoState=new M("stopped");this.textTracksManager=new Le;this.manifests$=new YR([]);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:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?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 qR(t)}};this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:WR.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(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Vs(ae(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Zu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Zu.WTF,message:"HlsProvider internal logic error",thrown:o})},i=me(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(WS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(We(this.video,t.isLooped,r)),this.subscription.add(fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(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(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&HR(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(f=>f.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(re(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 S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(f),S.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(WS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!QR.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(QS(el(o,"addtrack"),el(o,"removetrack"),el(o,"change"),zS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=QS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,zS(["init"])).pipe(UR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),he(this.video)}prepare(){var s,n;let e=this.selectManifest();if(jR(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){be(this.video).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:Zu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as zR,assertNonNullable as KS,debounce as KR,ErrorCategory as JS,isHigher as JR,isHigherOrEqual as XR,isInvariantQuality as XS,isLowerOrEqual as ZR,isNonNullable as eL,merge as tL,observableFrom as rL,Subscription as iL,map as aL}from"@vkontakte/videoplayer-shared";var sa=class{constructor(e){this.subscription=new iL;this.videoState=new M("stopped");this.trackUrls={};this.textTracksManager=new Le;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:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?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 zR(e)}};this.params=e,this.video=pe(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:JS.WTF,message:"MpegProvider internal logic error",thrown:o})},i=me(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(aL(o=>o.to)),this.params.output.playbackState$),this.subscription.add(We(this.video,t.isLooped,r)),this.subscription.add(fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,i.playbackRateState$,r)),s(Me(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&&eL(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=tL(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,rL(["init"])).pipe(KR(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),he(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;KS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];KS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=zi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(re(t))}playIfAllowed(){be(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:JS.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=>!XS(d.track.quality)&&ZR(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&XR(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!XS(h.track.quality)&&JR(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(l=>l.track);t=vt(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 eg,debounce as uL,merge as tg,observableFrom as lL,Subscription as cL,map as rg,ValueSubject as dL,ErrorCategory as rl,VideoQuality as pL}from"@vkontakte/videoplayer-shared";import{ErrorCategory as sL}from"@vkontakte/videoplayer-shared";var ZS=["stun:videostun.mycdn.me:80"],nL=1e3,oL=3,tl=()=>null,Fs=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=tl;this.externalStopCallback=tl;this.externalErrorCallback=tl;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return w(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return w(this,null,function*(){try{let e={iceServers:[{urls:ZS}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return w(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return w(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:sL.WTF,message:e.message})}onPeerConnectionStream(e){return w(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return w(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),nL)}normalizeOptions(e={}){let t={stunServerList:ZS,maxRetryNumber:oL,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var na=class{constructor(e){this.videoState=new M("stopped");this.maxSeekBackTime$=new dL(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 eg(e)}};this.subscription=new cL,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=pe(e.container,e.tuning),this.liveStreamClient=new Fs(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),he(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:rl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};tg(this.videoState.stateChangeStarted$.pipe(rg(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(rg(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=me(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(Me(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(fe(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 eg(n.to)}},r)).add(tg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,lL(["init"])).pipe(uL(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(re(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:pL.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:rl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){be(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:rl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var oa=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 ca,assertNonNullable as It,ErrorCategory as Us,filter as vL,isNonNullable as ug,isNullable as yL,map as TL,merge as IL,once as EL,Subject as Ee,Subscription as lg,ValueSubject as D}from"@vkontakte/videoplayer-shared";import{Observable as hL,map as ig,Subscription as fL,Subject as mL}from"@vkontakte/videoplayer-shared";var ag=a=>new hL(e=>{let t=new fL,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(ig(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(ig(({type:l})=>l!==void 0)),n=new mL,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 sg,Subscription as bL,combine as SL,filter as ng,once as og}from"@vkontakte/videoplayer-shared";var ua=null,qs=null;function il(){return ua||(ua=new(window.AudioContext||window.webkitAudioContext)),qs||(qs=new GainNode(ua,{gain:1}),qs.connect(ua.destination)),{audioCtx:ua,gainNode:qs}}import{clientChecker as gL}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 bL;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe(ng(n=>!!n.type),og()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){gL.isSafari&&e!=="MPEG"||this.subscriptions.add(SL({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(ng(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),og()).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}=il(),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:sg.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:sg.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=il();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Dr.errorId="VolumeMultiplierManager";var la=Dr;var xL={chunkDuration:5e3,maxParallelRequests:5},da=class{constructor(e){this.current$=new D({type:void 0});this.providerError$=new Ee;this.noAvailableProvidersError$=new Ee;this.volumeMultiplierError$=new Ee;this.providerOutput={position$:new D(0),duration$:new D(1/0),volume$:new D({muted:!1,volume:1}),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableVideoTracks$:new D([]),currentVideoTrack$:new D(void 0),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0),isAudioAvailable$:new D(!0),autoVideoTrackLimitingAvailable$:new D(!1),autoVideoTrackLimits$:new D(void 0),currentBuffer$:new D(void 0),isBuffering$:new D(!0),error$:new Ee,warning$:new Ee,willSeekEvent$:new Ee,seekedEvent$:new Ee,loopedEvent$:new Ee,endedEvent$:new Ee,firstBytesEvent$:new Ee,loadedMetadataEvent$:new Ee,firstFrameEvent$:new Ee,canplay$:new Ee,isLive$:new D(void 0),isLowLatency$:new D(!1),canChangePlaybackSpeed$:new D(!0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),inPiP$:new D(!1),inFullscreen$:new D(!1),element$:new D(void 0),elementVisible$:new D(!0),availableSources$:new D(void 0),is3DVideo$:new D(!1),playbackState$:new D("")};this.subscription=new lg;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=kb([...Lb(this.params.tuning),...Rb(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>ug(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 oa(s);let n=[...yu(!0),...yu(!1)];this.chromecastFormatsIterator=new oa(n.filter(u=>ug(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new la(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(yL(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Us.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 ca(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 It(o),new Zi(q(R({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return It(o),new ea(q(R({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return It(o),xr||!this.params.tuning.useHlsJs?new aa(q(R({},n),{source:o})):new ra(q(R({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return It(o),new ia(q(R({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return It(o),new sa(q(R({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return It(o),new cb(q(R({},n),{source:o,config:q(R({},xL),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return It(o),new na({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 ca(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 It(o),new ci({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 ca(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ca(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 ca(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 q(R({},e),{url:r(e.url)})}return(0,cg.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new lg,t=!1,r=0;return e.add(IL(this.providerOutput.error$,ag({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(TL(i=>({id:`ProviderHangup:${i}`,category:Us.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(vL(({to:s})=>s==="playing"),EL()).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===Us.NETWORK,o=i.category===Us.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 Hs,once as PL,combine as AL,Subscription as dg,ValueSubject as al,map as wL,filter as kL,isNonNullable as js,now as xe,safeStorage as sl}from"@vkontakte/videoplayer-shared";var RL=5e3,pg="one_video_throughput",hg="one_video_rtt",nt=window.navigator.connection,fg=()=>{let a=nt==null?void 0:nt.downlink;if(js(a)&&a!==10)return a*1e3},mg=()=>{let a=nt==null?void 0:nt.rtt;if(js(a)&&a!==3e3)return a},bg=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},nl=class a{constructor(e){this.subscription=new dg;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(pg)||(e.useBrowserEstimation?fg():void 0)||RL,r=(s=(i=a.load(hg))!=null?i:e.useBrowserEstimation?mg():void 0)!=null?s:0;if(this.throughput$=new al(t),this.rtt$=new al(r),this.rttAdjustedThroughput$=new al(bg(t,r,e.rttPenaltyRequestSize)),this.throughput=Wt.getSmoothedValue(t,-1,e),this.rtt=Wt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=fg();u&&this.throughput.next(u);let l=mg();js(l)&&this.rtt.next(l)};nt&&"onchange"in nt&&this.subscription.add(Hs(nt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{sl.set(pg,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{sl.set(hg,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(AL({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(wL(({throughput:n,rtt:o})=>bg(n,o,e.rttPenaltyRequestSize)),kL(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=xe(),i=new dg;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Hs(e,"progress").pipe(PL()).subscribe(s=>{t=s.loaded,r=xe()}));break;case 1:case 0:i.add(Hs(e,"loadstart").subscribe(()=>{t=0,r=xe()}));break}i.add(Hs(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=xe(),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=xe(),n=0,o=xe(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>w(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,xe()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=xe();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=xe()}else n+=d.byteLength;o=xe()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&xe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,xe()-o,this.concurrentDownloads.size),n=0,o=xe());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=sl.get(e);if(js(t))return(r=parseInt(t,10))!=null?r:void 0}},Sg=nl;import{fillWithDefault as LL,VideoQuality as gg}from"@vkontakte/videoplayer-shared";var vg={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:gg.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:gg.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},yg=a=>{var e;return q(R({},LL(a,vg)),{configName:[...(e=a.configName)!=null?e:[],...vg.configName]})};import{assertNonNullable as Gs,combine as Ys,ErrorCategory as Ws,filter as pa,filterChanged as Oe,fromEvent as ul,isNonNullable as VL,isNullable as _L,Logger as NL,map as _,mapTo as xg,merge as Et,now as Qs,once as ot,Subject as Y,Subscription as Pg,tap as Ag,ValueSubject as P,isHigher as FL,isInvariantQuality as wg}from"@vkontakte/videoplayer-shared";import{merge as $L,map as ML,filter as Tg,isNonNullable as CL}from"@vkontakte/videoplayer-shared";var ol=({seekState:a,position$:e})=>$L(a.stateChangeEnded$.pipe(ML(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),Tg(CL)),e.pipe(Tg(()=>a.getState().state==="none")));import{assertNonNullable as DL}from"@vkontakte/videoplayer-shared";var Ig=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return DL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as OL,once as BL}from"@vkontakte/videoplayer-shared";var Eg=(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(OL(i=>i.length>0),BL()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var zs=class{constructor(e={configName:[]}){this.subscription=new Pg;this.logger=new NL;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 Y,ready$:new Y,started$:new Y,playing$:new Y,paused$:new Y,stopped$:new Y,willStart$:new Y,willResume$:new Y,willPause$:new Y,willStop$:new Y,willDestruct$:new Y,watchCoverageRecord$:new Y,watchCoverageLive$:new Y,managedError$:new Y,fatalError$:new Y,ended$:new Y,looped$:new Y,seeked$:new Y,willSeek$:new Y,firstBytes$:new Y,loadedMetadata$:new Y,firstFrame$:new Y,canplay$:new Y,log$:new Y};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Km};if(this.initLogs(),this.tuning=yg(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ya({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Sg(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(d=>JSON.stringify(d,(p,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:Ws.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,i;return this.config=e,this.domContainer=Ig(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new da({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&&!vi()?ul(document,"visibilitychange").pipe(ot()).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){Gs(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(pa(r=>r.length>0),ot()).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;Gs(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=>R({type:"external"},t))),this}selectTextTrack(e){var t;return Eg(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(_L(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return VL(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(Et(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(pa(({from:e})=>e==="stopped"),ot()).subscribe(()=>{this.initedAt=Qs(),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(q(R({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Ws.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(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),Oe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(_(n=>n.map(({quality:o})=>o).sort((o,u)=>wg(o)?1:wg(u)?-1:FL(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(Oe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Oe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Oe()).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(_(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(Ys({hasLiveOffsetByPaused:Et(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(n=>n.to),Oe(),_(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(Ys({atLiveEdge:Ys({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:ol({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(_(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),Oe(),Ag(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(_(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ys({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(_(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Oe(),Ag(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),Oe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),Oe()).subscribe(this.info.volume$)).add(ol({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Et(e.providerOutput.endedEvent$.pipe(xg(!0)),e.providerOutput.seekedEvent$.pipe(xg(!1))).pipe(Oe()).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(_(n=>({id:n?`No${n}`:"NoProviders",category:Ws.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(ot(),_(n=>n!=null?n:Qs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ot(),_(()=>Qs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ot(),_(()=>Qs()-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(pa(({to:n})=>n==="playing"),ot()).subscribe(()=>r.next(!1)));let i=0,s=Et(e.providerOutput.isBuffering$,t,r).pipe(_(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),Oe());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(Et(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(Et(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(_(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 Pg;this.subscription.add(t),this.subscription.add(e.current$.pipe(Oe((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(pa(r=>r.length>0),ot()).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=vt(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(Et(this.desiredState.videoTrack.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(_(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;Gs(this.providerContainer),Gs(e),zm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Qm(r)),this.providerContainer.current$.subscribe(({type:r})=>fi("provider",r)),e.duration$.subscribe(r=>fi("duration",r)),e.availableVideoTracks$.pipe(pa(r=>!!r.length),ot()).subscribe(r=>fi("tracks",r)),this.events.fatalError$.subscribe(new ne("fatalError")),this.events.managedError$.subscribe(new ne("managedError")),e.position$.subscribe(new ne("position")),e.currentVideoTrack$.pipe(_(r=>r==null?void 0:r.quality)).subscribe(new ne("quality")),this.info.currentBuffer$.subscribe(new ne("buffer")),e.isBuffering$.subscribe(new ne("isBuffering"))].forEach(r=>this.subscription.add(r)),fi("codecs",wb())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>w(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Ws.DOM,message:String(i)})})});this.subscription.add(Et(ul(document,"visibilitychange"),ul(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 NG,Observable as FG,Subject as qG,ValueSubject as UG,VideoQuality as HG}from"@vkontakte/videoplayer-shared";var jG=`@vkontakte/videoplayer-core@${Bl}`;export{ga as ChromecastState,dn as HttpConnectionType,FG as Observable,ce as PlaybackState,zs as Player,jG as SDK_VERSION,qG as Subject,NG as Subscription,pn as Surface,Bl as VERSION,UG as ValueSubject,pt as VideoFormat,HG as VideoQuality};
112
+ `;var Fs=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 _s(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ns(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(Yg,this.gl.VERTEX_SHADER),r=this.createShader(Qg,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 er=class{constructor(e){this.subscription=new xR;this.videoState=new M("stopped");this.elementSize$=new PR(void 0);this.textTracksManager=new Ce;this.droppedFramesManager=new ms;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yi;this.audioTrackSwitchHistory=new yi;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 gR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Fs(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=fe(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(re(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Vs({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=ge(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Xu.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(zg(c=>!!c.length),Jg()).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(zg(TR),Jg()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Kg(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ze(this.video,t.isLooped,i)),this.subscription.add(be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Me(this.video,t.playbackRate,r.playbackRateState$,i)),s(ER(this.video),this.elementSize$),s(Be(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(SR(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of l.audio){p.push(qu(h));let f=[];for(let b of h.representations){let g=Cg(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(Uu(p));let h=[];for(let f of p.representations){let b=Mg(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=Dg(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:Xu.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(qs(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$,yR(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(Zu()).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(Uu(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Zu()).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(qu(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(Kg(({to:c})=>c==="ready"),Zu());this.subscription.add(qs(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(qs(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=qs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,IR(["init"])).pipe(vR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var $,G,O,C,H,N,L,F,_,w,x,D,W,Q,X,ce,kt,dt;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=($=e.videoTrack.getState())==null?void 0:$.id,n=[...this.videoTracksMap.keys()].find(({id:A})=>A===i),o=t.currentVideoTrack$.getValue(),u=((C=(O=e.videoStream.getState())!=null?O:n&&((G=this.videoTracksMap.get(n))==null?void 0:G.stream))!=null?C: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=at(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=(H=e.audioStream.getState())!=null?H:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(N=[...this.audioStreamsMap.keys()].find(({id:A})=>A===(f==null?void 0:f.id)))!=null?N:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let A=ds(n,l,(L=this.audioStreamsMap.get(b))!=null?L:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(F=A==null?void 0:A.bitrate)!=null?F:-1/0)}else{let A=Rs(n,l,(_=this.audioStreamsMap.get(b))!=null?_:[]);g=Math.max(g,(w=A==null?void 0:A.bitrate)!=null?w:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let A=ds(o,l,(x=this.audioStreamsMap.get(b))!=null?x:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(D=A==null?void 0:A.bitrate)!=null?D:-1/0)}else{let A=Rs(o,l,(W=this.audioStreamsMap.get(b))!=null?W:[]);g=Math.max(g,(Q=A==null?void 0:A.bitrate)!=null?Q:-1/0)}}let S=Tt(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}),T=r?S!=null?S:n:n!=null?n:S,v;this.params.tuning.useSeparateAudioVideoABR?v=b&&pb(T,l,(X=this.audioStreamsMap.get(b))!=null?X:[],{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}):v=b&&Rs(T,l,(ce=this.audioStreamsMap.get(b))!=null?ce:[]);let y=(kt=this.videoTracksMap.get(T))==null?void 0:kt.representation,I=v&&((dt=this.audioTracksMap.get(v))==null?void 0:dt.representation);if(y&&I)return[y,I];if(y&&!I&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ve(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:Xu.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),me(this.video),this.tracer.end()}};var oa=class extends er{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 Xg,interval as AR,map as wR}from"@vkontakte/videoplayer-shared";var ua=class extends er{constructor(e){super(e),this.liveOffset=new rt}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(Xg({interval:AR(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(Xg({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(wR(({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 eS=Ye(us(),1);import{assertNever as ca,assertNonNullable as Zg,debounce as kR,ErrorCategory as Us,filter as RR,isNonNullable as $R,isNullable as LR,map as Hs,merge as MR,Observable as CR,observableFrom as DR,Subscription as BR,videoSizeToQuality as OR}from"@vkontakte/videoplayer-shared";var je={};var _r=(a,e)=>new CR(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),la=class{constructor(e){this.subscription=new BR;this.videoState=new M("initializing");this.textTracksManager=new Ce;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:ca(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ca(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ca(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:ca(e)}break;default:ca(t)}};this.video=fe(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(re(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),me(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Us.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,eS.default)(import("hls.js").then(i=>{e||(je.Hls=i.default,je.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Zg(je.Hls,"hls.js not loaded"),this.hls=new je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Zg(je.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=c=>{t.error$.next({id:"HlsJsProvider",category:Us.WTF,message:"HlsJsProvider internal logic error",thrown:c})},i=ge(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(ze(this.video,e.isLooped,r)),this.subscription.add(be(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Me(this.video,e.playbackRate,i.playbackRateState$,r)),s(Be(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Hs(c=>c.to)),this.params.output.playbackState$),this.subscription.add(_r(this.hls,je.Events.ERROR).subscribe(c=>{var l;c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:Us.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(_r(this.hls,je.Events.MANIFEST_PARSED).pipe(Hs(({levels:c})=>c.reduce((l,d)=>{var T,v;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(v=yt((T=d.attrs.QUALITY)!=null?T:""))!=null?v:OR({width:h,height:f});if(!b)return l;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:S,level:d}),l.push(S),l},[]))),t.availableVideoTracks$),s(_r(this.hls,je.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(_r(this.hls,je.Events.LEVEL_LOADING).pipe(Hs(({url:c})=>re(c))),t.hostname$),s(_r(this.hls,je.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(gt(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=_r(this.hls,je.Events.LEVEL_SWITCHED).pipe(Hs(({level:c})=>n(this.hls.levels[c])));o.pipe(RR($R)).subscribe(t.currentVideoTrack$,r),this.subscription.add(gt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),c=>{var f;if(LR(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=MR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,DR(["init"])).pipe(kR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return R(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield ve(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Us.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 tS="X-Playback-Duration",ec=a=>R(void 0,null,function*(){var i;let e=yield st(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(tS)?parseInt(e.headers.get(tS),10):void 0});import{assertNever as UR,combine as HR,debounce as jR,ErrorCategory as Gs,filter as GR,filterChanged as WR,isNonNullable as iS,isNullable as Ws,map as aS,merge as YR,observableFrom as QR,Subscription as zR,ValueSubject as ic,VideoQuality as KR}from"@vkontakte/videoplayer-shared";var rc=Ye(To(),1);import{videoSizeToQuality as VR,getExponentialDelay as _R}from"@vkontakte/videoplayer-shared";var NR=a=>{let e=null;if(a.QUALITY&&(e=yt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=VR({width:t,height:r})}return e!=null?e:null},FR=(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,rc.default)(c[1].split(",").map(T=>T.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=NR(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[T,v]=d.RESOLUTION.split("x").map(y=>parseInt(y,10));T&&v&&(g={width:T,height:v})}let S=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:S,bandwidth:f,size:g,fps:b})}if(l){let d=(0,rc.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}},qR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),tc=0,rS=(r,...i)=>R(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield st(a)).text();tc+=1;try{let{qualityManifests:o,textTracks:u}=FR(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(tc<=t.manifestRetryMaxCount)return yield qR(_R(tc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),rS(a,e,t)}return{qualityManifests:[],textTracks:[]}}),js=rS;var da=class{constructor(e){this.subscription=new zR;this.videoState=new M("stopped");this.textTracksManager=new Ce;this.manifests$=new ic([]);this.liveOffset=new rt;this.manifestStartTime$=new ic(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 UR(t)}};var t;this.params=e,this.video=fe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:KR.INVARIANT,url:this.params.source.url},js(ae(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Gs.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Gs.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(re(this.params.source.url)),this.maxSeekBackTime$=new ic((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:Gs.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=ge(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(be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Me(this.video,t.playbackRate,i.playbackRateState$,r)),s(Be(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(WR(),aS(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&&iS(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(re(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(HR({startTime:this.manifestStartTime$.pipe(GR(iS)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(aS(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=YR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,QR(["init"])).pipe(jR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),me(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Ws(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=ae(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ec(n).then(c=>{var l;if(!Ws(c))this.maxSeekBackTime$.next(c);else{let d=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();if(Ws(d)||!isFinite(d))try{st(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();ec(b).then(g=>{Ws(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){ve(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:Gs.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 JR,debounce as XR,ErrorCategory as ac,fromEvent as sc,isNonNullable as ZR,isNullable as e$,map as sS,merge as nS,observableFrom as oS,Subscription as t$,ValueSubject as r$,VideoQuality as i$,clientChecker as a$}from"@vkontakte/videoplayer-shared";var pa=class{constructor(e){this.subscription=new t$;this.videoState=new M("stopped");this.textTracksManager=new Ce;this.manifests$=new r$([]);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 JR(t)}};this.params=e,this.video=fe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:i$.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(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),js(ae(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:ac.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:ac.WTF,message:"HlsProvider internal logic error",thrown:o})},i=ge(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(sS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,r)),this.subscription.add(be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Me(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&&ZR(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(re(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(sS(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)),!a$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(nS(sc(o,"addtrack"),sc(o,"removetrack"),sc(o,"change"),oS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=nS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,oS(["init"])).pipe(XR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),me(this.video)}prepare(){var s,n;let e=this.selectManifest();if(e$(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(){ve(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:ac.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as s$,assertNonNullable as uS,debounce as n$,ErrorCategory as cS,isHigher as o$,isHigherOrEqual as u$,isInvariantQuality as lS,isLowerOrEqual as c$,isNonNullable as l$,merge as d$,observableFrom as p$,Subscription as h$,map as f$}from"@vkontakte/videoplayer-shared";var ha=class{constructor(e){this.subscription=new h$;this.videoState=new M("stopped");this.trackUrls={};this.textTracksManager=new Ce;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 s$(e)}};this.params=e,this.video=fe(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:cS.WTF,message:"MpegProvider internal logic error",thrown:o})},i=ge(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(f$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,r)),this.subscription.add(be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Me(this.video,t.playbackRate,i.playbackRateState$,r)),s(Be(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&&l$(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=d$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,p$(["init"])).pipe(n$(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),me(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;uS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];uS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ta(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(re(t))}playIfAllowed(){ve(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:cS.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=>!lS(d.track.quality)&&c$(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&&u$(l.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!lS(h.track.quality)&&o$(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=Tt(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 pS,debounce as S$,merge as hS,observableFrom as v$,Subscription as y$,map as fS,ValueSubject as T$,ErrorCategory as oc,VideoQuality as I$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as m$}from"@vkontakte/videoplayer-shared";var dS=["stun:videostun.mycdn.me:80"],b$=1e3,g$=3,nc=()=>null,Ys=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=nc;this.externalStopCallback=nc;this.externalErrorCallback=nc;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return R(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return R(this,null,function*(){try{let e={iceServers:[{urls:dS}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return R(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return R(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:m$.WTF,message:e.message})}onPeerConnectionStream(e){return R(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return R(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),b$)}normalizeOptions(e={}){let t={stunServerList:dS,maxRetryNumber:g$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var fa=class{constructor(e){this.videoState=new M("stopped");this.maxSeekBackTime$=new T$(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 pS(e)}};this.subscription=new y$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=fe(e.container,e.tuning),this.liveStreamClient=new Ys(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),me(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:oc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};hS(this.videoState.stateChangeStarted$.pipe(fS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(fS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=ge(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(Be(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(be(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 pS(n.to)}},r)).add(hS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,v$(["init"])).pipe(S$(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(re(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:I$.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:oc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ve(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:oc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ma=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 xt,ErrorCategory as zs,filter as R$,isNonNullable as yS,isNullable as $$,map as L$,merge as M$,once as C$,Subject as Ae,Subscription as TS,ValueSubject as B,flattenObject as IS}from"@vkontakte/videoplayer-shared";import{Observable as E$,map as mS,Subscription as x$,Subject as P$}from"@vkontakte/videoplayer-shared";var bS=a=>new E$(e=>{let t=new x$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(mS(({from:c,to:l})=>`${c}-${l}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(mS(({type:c})=>c!==void 0)),n=new P$,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 gS,Subscription as A$,combine as w$,filter as SS,once as vS}from"@vkontakte/videoplayer-shared";var ba=null,Qs=null;function uc(){return ba||(ba=new(window.AudioContext||window.webkitAudioContext)),Qs||(Qs=new GainNode(ba,{gain:1}),Qs.connect(ba.destination)),{audioCtx:ba,gainNode:Qs}}import{clientChecker as k$}from"@vkontakte/videoplayer-shared";var Nr=class Nr{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new A$;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe(SS(n=>!!n.type),vS()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){k$.isSafari&&e!=="MPEG"||this.subscriptions.add(w$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(SS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),vS()).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}=uc(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Nr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Nr.errorId,category:gS.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:Nr.errorId,category:gS.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=uc();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Nr.errorId="VolumeMultiplierManager";var ga=Nr;var D$={chunkDuration:5e3,maxParallelRequests:5},va=class{constructor(e){this.current$=new B({type:void 0});this.providerError$=new Ae;this.noAvailableProvidersError$=new Ae;this.volumeMultiplierError$=new Ae;this.providerOutput={position$:new B(0),duration$:new B(1/0),volume$:new B({muted:!1,volume:1}),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableVideoTracks$:new B([]),currentVideoTrack$:new B(void 0),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0),isAudioAvailable$:new B(!0),autoVideoTrackLimitingAvailable$:new B(!1),autoVideoTrackLimits$:new B(void 0),currentBuffer$:new B(void 0),isBuffering$:new B(!0),error$:new Ae,warning$:new Ae,willSeekEvent$:new Ae,seekedEvent$:new Ae,loopedEvent$:new Ae,endedEvent$:new Ae,firstBytesEvent$:new Ae,loadedMetadataEvent$:new Ae,firstFrameEvent$:new Ae,canplay$:new Ae,isLive$:new B(void 0),isLowLatency$:new B(!1),canChangePlaybackSpeed$:new B(!0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),inPiP$:new B(!1),inFullscreen$:new B(!1),element$:new B(void 0),elementVisible$:new B(!0),availableSources$:new B(void 0),is3DVideo$:new B(!1),playbackState$:new B("")};this.subscription=new TS;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=qb([...Hb(this.params.tuning),...Ub(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>yS(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",IS(s)),this.screenFormatsIterator=new ma(s);let n=[...Au(!0),...Au(!1)];this.chromecastFormatsIterator=new ma(n.filter(u=>yS(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new ga(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($$(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:zs.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 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 xt(o),new oa(V(k({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return xt(o),new ua(V(k({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return xt(o),kr||!this.params.tuning.useHlsJs?new pa(V(k({},n),{source:o})):new la(V(k({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return xt(o),new da(V(k({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return xt(o),new ha(V(k({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return xt(o),new Eb(V(k({},n),{source:o,config:V(k({},D$),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return xt(o),new fa({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 xt(o),new mi({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 V(k({},e),{url:r(e.url)})}return(0,ES.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new TS,t=!1,r=0;return e.add(M$(this.providerOutput.error$,bS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(L$(i=>({id:`ProviderHangup:${i}`,category:zs.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(R$(({to:s})=>s==="playing"),C$()).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===zs.NETWORK,u=i.category===zs.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=V(k({},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",IS(n))})),e}};import{fromEvent as Ks,once as B$,combine as O$,Subscription as xS,ValueSubject as cc,map as V$,filter as _$,isNonNullable as Js,now as we,safeStorage as lc}from"@vkontakte/videoplayer-shared";var N$=5e3,PS="one_video_throughput",AS="one_video_rtt",ct=window.navigator.connection,wS=()=>{let a=ct==null?void 0:ct.downlink;if(Js(a)&&a!==10)return a*1e3},kS=()=>{let a=ct==null?void 0:ct.rtt;if(Js(a)&&a!==3e3)return a},RS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},dc=class a{constructor(e){this.subscription=new xS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(PS)||(e.useBrowserEstimation?wS():void 0)||N$,r=(s=(i=a.load(AS))!=null?i:e.useBrowserEstimation?kS():void 0)!=null?s:0;if(this.throughput$=new cc(t),this.rtt$=new cc(r),this.rttAdjustedThroughput$=new cc(RS(t,r,e.rttPenaltyRequestSize)),this.throughput=Xt.getSmoothedValue(t,-1,e),this.rtt=Xt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=wS();u&&this.throughput.next(u);let c=kS();Js(c)&&this.rtt.next(c)};ct&&"onchange"in ct&&this.subscription.add(Ks(ct,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{lc.set(PS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{lc.set(AS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(O$({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(V$(({throughput:n,rtt:o})=>RS(n,o,e.rttPenaltyRequestSize)),_$(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=we(),i=new xS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Ks(e,"progress").pipe(B$()).subscribe(s=>{t=s.loaded,r=we()}));break;case 1:case 0:i.add(Ks(e,"loadstart").subscribe(()=>{t=0,r=we()}));break}i.add(Ks(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=we(),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=we(),n=0,o=we(),u=l=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},c=p=>R(this,[p],function*({done:l,value:d}){if(l)!t&&this.addRawSpeed(i,we()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=we();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=we()}else n+=d.byteLength;o=we()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&we()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,we()-o,this.concurrentDownloads.size),n=0,o=we());yield 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=lc.get(e);if(Js(t))return(r=parseInt(t,10))!=null?r:void 0}},$S=dc;import{fillWithDefault as F$,VideoQuality as LS}from"@vkontakte/videoplayer-shared";var MS={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:LS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:LS.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},CS=a=>{var e;return V(k({},F$(a,MS)),{configName:[...(e=a.configName)!=null?e:[],...MS.configName]})};import{assertNonNullable as Xs,combine as Pt,ErrorCategory as Zs,filter as ue,filterChanged as U,fromEvent as hc,isNonNullable as Y$,isNullable as Q$,Logger as z$,map as q,mapTo as VS,merge as At,now as en,once as lt,Subject as Y,Subscription as _S,tap as NS,ValueSubject as P,isHigher as K$,isInvariantQuality as FS,flattenObject as wt,throttle as fc,getTraceSubscriptionMethod as qS}from"@vkontakte/videoplayer-shared";import{merge as q$,map as U$,filter as DS,isNonNullable as H$}from"@vkontakte/videoplayer-shared";var pc=({seekState:a,position$:e})=>q$(a.stateChangeEnded$.pipe(U$(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),DS(H$)),e.pipe(DS(()=>a.getState().state==="none")));import{assertNonNullable as j$}from"@vkontakte/videoplayer-shared";var BS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return j$(e,`Wrong container or containerId {${a.container}}`),e};import{filter as G$,once as W$}from"@vkontakte/videoplayer-shared";var OS=(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(G$(i=>i.length>0),W$()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var tn=class{constructor(e={configName:[]},t){this.subscription=new _S;this.logger=new z$;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 Y,ready$:new Y,started$:new Y,playing$:new Y,paused$:new Y,stopped$:new Y,willStart$:new Y,willResume$:new Y,willPause$:new Y,willStop$:new Y,willDestruct$:new Y,watchCoverageRecord$:new Y,watchCoverageLive$:new Y,managedError$:new Y,fatalError$:new Y,ended$:new Y,looped$:new Y,seeked$:new Y,willSeek$:new Y,firstBytes$:new Y,loadedMetadata$:new Y,firstFrame$:new Y,canplay$:new Y,log$:new Y};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:rb};if(this.initLogs(),this.tuning=CS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new wa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new $S(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:Zs.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var t,r,i;return this.config=e,this.tracer.log("initVideo",wt(e)),this.domContainer=BS(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new va({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&&!Pi()?(this.tracer.log("request play from hidden tab"),hc(document,"visibilitychange").pipe(lt()).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){Xs(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(ue(r=>r.length>0),lt()).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",wt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Xs(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",wt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>k({type:"external"},t))),this}selectTextTrack(e){var t;return OS(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",k({},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(Q$(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return Y$(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(At(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(q(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ue(({from:e})=>e==="stopped"),lt()).subscribe(()=>{this.initedAt=en(),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",wt(n)),n.state==="requested"?this.desiredState.seekState.setState(V(k({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Zs.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",wt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(q(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(q(n=>n.destination),U()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(q(n=>n.map(({quality:o})=>o).sort((o,u)=>FS(o)?1:FS(u)?-1:K$(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(U()).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(U((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(U((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(U()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(U()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(U()).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(q(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(Pt({hasLiveOffsetByPaused:At(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(q(n=>n.to),U(),q(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(Pt({atLiveEdge:Pt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:pc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(q(({isLive:n,position:o,isLowLatency:u})=>{let c=this.getActiveLiveDelay(u);return n&&Math.abs(o)<c/1e3}),U(),NS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(q(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Pt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(q(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),U(),NS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(q(n=>n.muted),U()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(q(n=>n.volume),U()).subscribe(this.info.volume$)).add(pc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(At(e.providerOutput.endedEvent$.pipe(VS(!0)),e.providerOutput.seekedEvent$.pipe(VS(!1))).pipe(U()).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(q(n=>({id:n?`No${n}`:"NoProviders",category:Zs.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(lt(),q(n=>n!=null?n:en()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(lt(),q(()=>en()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(lt(),q(()=>en()-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(ue(({to:n})=>n==="playing"),lt()).subscribe(()=>r.next(!1)));let i=0,s=At(e.providerOutput.isBuffering$,t,r).pipe(q(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),U());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(At(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(At(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(q(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(U((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ue(r=>r.length>0),lt()).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=Tt(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(At(this.desiredState.videoTrack.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(q(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;Xs(this.providerContainer),Xs(e),tb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>eb(r)),this.providerContainer.current$.subscribe(({type:r})=>vi("provider",r)),e.duration$.subscribe(r=>vi("duration",r)),e.availableVideoTracks$.pipe(ue(r=>!!r.length),lt()).subscribe(r=>vi("tracks",r)),this.events.fatalError$.subscribe(new ne("fatalError")),this.events.managedError$.subscribe(new ne("managedError")),e.position$.subscribe(new ne("position")),e.currentVideoTrack$.pipe(q(r=>r==null?void 0:r.quality)).subscribe(new ne("quality")),this.info.currentBuffer$.subscribe(new ne("buffer")),e.isBuffering$.subscribe(new ne("isBuffering"))].forEach(r=>this.subscription.add(r)),vi("codecs",Fb())}initTracerSubscription(){let e=qS(this.tracer.log.bind(this.tracer)),t=qS(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(U()).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(Pt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ue(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),U((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ue(r=>r>0),U()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ue(r=>r>0),U()).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(Pt({currentBuffer:this.info.currentBuffer$.pipe(ue(r=>r.end>0),U((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(U())}).pipe(fc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(U()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(U()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(U()).subscribe(e("canChangePlaybackSpeed"))).add(Pt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ue(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),fc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(U(),ue(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(U(),ue(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(U()).subscribe(e("muted"))).add(this.info.volume$.pipe(U()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(U(),ue(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Pt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ue(({throughputEstimation:r,rtt:i})=>!!r&&!!i),fc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(U(),ue(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=()=>R(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Zs.DOM,message:String(i)})})});this.subscription.add(At(hc(document,"visibilitychange"),hc(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",wt({quality:t,availableTracks:wt(e),track:wt(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 tW,Observable as rW,Subject as iW,ValueSubject as aW,VideoQuality as sW}from"@vkontakte/videoplayer-shared";var nW=`@vkontakte/videoplayer-core@${Uc}`;export{Pa as ChromecastState,gn as HttpConnectionType,rW as Observable,pe as PlaybackState,tn as Player,nW as SDK_VERSION,iW as Subject,tW as Subscription,Sn as Surface,Uc as VERSION,aW as ValueSubject,mt as VideoFormat,sW as VideoQuality};