@vkontakte/videoplayer-core 2.0.108-dev.7ca5c32c.0 → 2.0.108-dev.9969cb23.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.7ca5c32c.0
3
- * Wed, 04 Sep 2024 14:00:32 GMT
2
+ * @vkontakte/videoplayer-core v2.0.108-dev.9969cb23.0
3
+ * Mon, 09 Sep 2024 08:50:20 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-108/doc/
5
5
  */
6
- var tv=Object.create;var fn=Object.defineProperty,rv=Object.defineProperties,iv=Object.getOwnPropertyDescriptor,av=Object.getOwnPropertyDescriptors,sv=Object.getOwnPropertyNames,Bl=Object.getOwnPropertySymbols,nv=Object.getPrototypeOf,_l=Object.prototype.hasOwnProperty,ov=Object.prototype.propertyIsEnumerable;var uv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var Ge=Math.pow,Vl=(a,e,t)=>e in a?fn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,w=(a,e)=>{for(var t in e||(e={}))_l.call(e,t)&&Vl(a,t,e[t]);if(Bl)for(var t of Bl(e))ov.call(e,t)&&Vl(a,t,e[t]);return a},B=(a,e)=>rv(a,av(e));var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var lv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of sv(e))!_l.call(a,i)&&i!==t&&fn(a,i,{get:()=>e[i],enumerable:!(r=iv(e,i))||r.enumerable});return a};var We=(a,e,t)=>(t=a!=null?tv(nv(a)):{},lv(e||!a||!a.__esModule?fn(t,"default",{value:a,enumerable:!0}):t,a));var k=(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())}),cv=function(a,e){this[0]=a,this[1]=e},re=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof cv,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[uv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var Ie=m((uL,Wl)=>{"use strict";Wl.exports=function(a){try{return!!a()}catch(e){return!0}}});var jr=m((lL,Yl)=>{"use strict";var Sv=Ie();Yl.exports=!Sv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var he=m((cL,Kl)=>{"use strict";var Ql=jr(),zl=Function.prototype,vn=zl.call,vv=Ql&&zl.bind.bind(vn,vn);Kl.exports=Ql?vv:function(a){return function(){return vn.apply(a,arguments)}}});var sr=m((dL,Xl)=>{"use strict";var Jl=he(),yv=Jl({}.toString),Tv=Jl("".slice);Xl.exports=function(a){return Tv(yv(a),8,-1)}});var ec=m((pL,Zl)=>{"use strict";var Iv=he(),Ev=Ie(),xv=sr(),yn=Object,Pv=Iv("".split);Zl.exports=Ev(function(){return!yn("z").propertyIsEnumerable(0)})?function(a){return xv(a)==="String"?Pv(a,""):yn(a)}:yn});var nr=m((hL,tc)=>{"use strict";tc.exports=function(a){return a==null}});var Gr=m((fL,rc)=>{"use strict";var Av=nr(),wv=TypeError;rc.exports=function(a){if(Av(a))throw new wv("Can't call method on "+a);return a}});var or=m((mL,ic)=>{"use strict";var kv=ec(),Rv=Gr();ic.exports=function(a){return kv(Rv(a))}});var Tn=m((bL,ac)=>{"use strict";ac.exports=function(){}});var Ct=m((gL,sc)=>{"use strict";sc.exports={}});var J=m((In,nc)=>{"use strict";var Wr=function(a){return a&&a.Math===Math&&a};nc.exports=Wr(typeof globalThis=="object"&&globalThis)||Wr(typeof window=="object"&&window)||Wr(typeof self=="object"&&self)||Wr(typeof global=="object"&&global)||Wr(typeof In=="object"&&In)||function(){return this}()||Function("return this")()});var K=m((SL,oc)=>{"use strict";var En=typeof document=="object"&&document.all;oc.exports=typeof En=="undefined"&&En!==void 0?function(a){return typeof a=="function"||a===En}:function(a){return typeof a=="function"}});var cc=m((vL,lc)=>{"use strict";var $v=J(),Lv=K(),uc=$v.WeakMap;lc.exports=Lv(uc)&&/native code/.test(String(uc))});var ke=m((yL,dc)=>{"use strict";var Mv=K();dc.exports=function(a){return typeof a=="object"?a!==null:Mv(a)}});var Re=m((TL,pc)=>{"use strict";var Cv=Ie();pc.exports=!Cv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Aa=m((IL,fc)=>{"use strict";var Dv=J(),hc=ke(),xn=Dv.document,Ov=hc(xn)&&hc(xn.createElement);fc.exports=function(a){return Ov?xn.createElement(a):{}}});var Pn=m((EL,mc)=>{"use strict";var Bv=Re(),Vv=Ie(),_v=Aa();mc.exports=!Bv&&!Vv(function(){return Object.defineProperty(_v("div"),"a",{get:function(){return 7}}).a!==7})});var An=m((xL,bc)=>{"use strict";var Nv=Re(),Fv=Ie();bc.exports=Nv&&Fv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ye=m((PL,gc)=>{"use strict";var qv=ke(),Uv=String,Hv=TypeError;gc.exports=function(a){if(qv(a))return a;throw new Hv(Uv(a)+" is not an object")}});var Ee=m((AL,Sc)=>{"use strict";var jv=jr(),wa=Function.prototype.call;Sc.exports=jv?wa.bind(wa):function(){return wa.apply(wa,arguments)}});var ka=m((wL,vc)=>{"use strict";vc.exports={}});var Je=m((kL,Tc)=>{"use strict";var wn=ka(),kn=J(),Gv=K(),yc=function(a){return Gv(a)?a:void 0};Tc.exports=function(a,e){return arguments.length<2?yc(wn[a])||yc(kn[a]):wn[a]&&wn[a][e]||kn[a]&&kn[a][e]}});var Yr=m((RL,Ic)=>{"use strict";var Wv=he();Ic.exports=Wv({}.isPrototypeOf)});var ur=m(($L,Pc)=>{"use strict";var Yv=J(),Ec=Yv.navigator,xc=Ec&&Ec.userAgent;Pc.exports=xc?String(xc):""});var $n=m((LL,Lc)=>{"use strict";var $c=J(),Rn=ur(),Ac=$c.process,wc=$c.Deno,kc=Ac&&Ac.versions||wc&&wc.version,Rc=kc&&kc.v8,Ve,Ra;Rc&&(Ve=Rc.split("."),Ra=Ve[0]>0&&Ve[0]<4?1:+(Ve[0]+Ve[1]));!Ra&&Rn&&(Ve=Rn.match(/Edge\/(\d+)/),(!Ve||Ve[1]>=74)&&(Ve=Rn.match(/Chrome\/(\d+)/),Ve&&(Ra=+Ve[1])));Lc.exports=Ra});var Ln=m((ML,Cc)=>{"use strict";var Mc=$n(),Qv=Ie(),zv=J(),Kv=zv.String;Cc.exports=!!Object.getOwnPropertySymbols&&!Qv(function(){var a=Symbol("symbol detection");return!Kv(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Mc&&Mc<41})});var Mn=m((CL,Dc)=>{"use strict";var Jv=Ln();Dc.exports=Jv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Cn=m((DL,Oc)=>{"use strict";var Xv=Je(),Zv=K(),ey=Yr(),ty=Mn(),ry=Object;Oc.exports=ty?function(a){return typeof a=="symbol"}:function(a){var e=Xv("Symbol");return Zv(e)&&ey(e.prototype,ry(a))}});var Qr=m((OL,Bc)=>{"use strict";var iy=String;Bc.exports=function(a){try{return iy(a)}catch(e){return"Object"}}});var Xe=m((BL,Vc)=>{"use strict";var ay=K(),sy=Qr(),ny=TypeError;Vc.exports=function(a){if(ay(a))return a;throw new ny(sy(a)+" is not a function")}});var zr=m((VL,_c)=>{"use strict";var oy=Xe(),uy=nr();_c.exports=function(a,e){var t=a[e];return uy(t)?void 0:oy(t)}});var Fc=m((_L,Nc)=>{"use strict";var Dn=Ee(),On=K(),Bn=ke(),ly=TypeError;Nc.exports=function(a,e){var t,r;if(e==="string"&&On(t=a.toString)&&!Bn(r=Dn(t,a))||On(t=a.valueOf)&&!Bn(r=Dn(t,a))||e!=="string"&&On(t=a.toString)&&!Bn(r=Dn(t,a)))return r;throw new ly("Can't convert object to primitive value")}});var _e=m((NL,qc)=>{"use strict";qc.exports=!0});var jc=m((FL,Hc)=>{"use strict";var Uc=J(),cy=Object.defineProperty;Hc.exports=function(a,e){try{cy(Uc,a,{value:e,configurable:!0,writable:!0})}catch(t){Uc[a]=e}return e}});var Kr=m((qL,Yc)=>{"use strict";var dy=_e(),py=J(),hy=jc(),Gc="__core-js_shared__",Wc=Yc.exports=py[Gc]||hy(Gc,{});(Wc.versions||(Wc.versions=[])).push({version:"3.38.0",mode:dy?"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 Vn=m((UL,zc)=>{"use strict";var Qc=Kr();zc.exports=function(a,e){return Qc[a]||(Qc[a]=e||{})}});var Jr=m((HL,Kc)=>{"use strict";var fy=Gr(),my=Object;Kc.exports=function(a){return my(fy(a))}});var Ne=m((jL,Jc)=>{"use strict";var by=he(),gy=Jr(),Sy=by({}.hasOwnProperty);Jc.exports=Object.hasOwn||function(e,t){return Sy(gy(e),t)}});var _n=m((GL,Xc)=>{"use strict";var vy=he(),yy=0,Ty=Math.random(),Iy=vy(1 .toString);Xc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Iy(++yy+Ty,36)}});var ne=m((WL,ed)=>{"use strict";var Ey=J(),xy=Vn(),Zc=Ne(),Py=_n(),Ay=Ln(),wy=Mn(),lr=Ey.Symbol,Nn=xy("wks"),ky=wy?lr.for||lr:lr&&lr.withoutSetter||Py;ed.exports=function(a){return Zc(Nn,a)||(Nn[a]=Ay&&Zc(lr,a)?lr[a]:ky("Symbol."+a)),Nn[a]}});var ad=m((YL,id)=>{"use strict";var Ry=Ee(),td=ke(),rd=Cn(),$y=zr(),Ly=Fc(),My=ne(),Cy=TypeError,Dy=My("toPrimitive");id.exports=function(a,e){if(!td(a)||rd(a))return a;var t=$y(a,Dy),r;if(t){if(e===void 0&&(e="default"),r=Ry(t,a,e),!td(r)||rd(r))return r;throw new Cy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ly(a,e)}});var Fn=m((QL,sd)=>{"use strict";var Oy=ad(),By=Cn();sd.exports=function(a){var e=Oy(a,"string");return By(e)?e:e+""}});var Dt=m(od=>{"use strict";var Vy=Re(),_y=Pn(),Ny=An(),$a=Ye(),nd=Fn(),Fy=TypeError,qn=Object.defineProperty,qy=Object.getOwnPropertyDescriptor,Un="enumerable",Hn="configurable",jn="writable";od.f=Vy?Ny?function(e,t,r){if($a(e),t=nd(t),$a(r),typeof e=="function"&&t==="prototype"&&"value"in r&&jn in r&&!r[jn]){var i=qy(e,t);i&&i[jn]&&(e[t]=r.value,r={configurable:Hn in r?r[Hn]:i[Hn],enumerable:Un in r?r[Un]:i[Un],writable:!1})}return qn(e,t,r)}:qn:function(e,t,r){if($a(e),t=nd(t),$a(r),_y)try{return qn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Fy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Xr=m((KL,ud)=>{"use strict";ud.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var cr=m((JL,ld)=>{"use strict";var Uy=Re(),Hy=Dt(),jy=Xr();ld.exports=Uy?function(a,e,t){return Hy.f(a,e,jy(1,t))}:function(a,e,t){return a[e]=t,a}});var La=m((XL,dd)=>{"use strict";var Gy=Vn(),Wy=_n(),cd=Gy("keys");dd.exports=function(a){return cd[a]||(cd[a]=Wy(a))}});var Ma=m((ZL,pd)=>{"use strict";pd.exports={}});var Qn=m((eM,md)=>{"use strict";var Yy=cc(),fd=J(),Qy=ke(),zy=cr(),Gn=Ne(),Wn=Kr(),Ky=La(),Jy=Ma(),hd="Object already initialized",Yn=fd.TypeError,Xy=fd.WeakMap,Ca,Zr,Da,Zy=function(a){return Da(a)?Zr(a):Ca(a,{})},eT=function(a){return function(e){var t;if(!Qy(e)||(t=Zr(e)).type!==a)throw new Yn("Incompatible receiver, "+a+" required");return t}};Yy||Wn.state?(Fe=Wn.state||(Wn.state=new Xy),Fe.get=Fe.get,Fe.has=Fe.has,Fe.set=Fe.set,Ca=function(a,e){if(Fe.has(a))throw new Yn(hd);return e.facade=a,Fe.set(a,e),e},Zr=function(a){return Fe.get(a)||{}},Da=function(a){return Fe.has(a)}):(Ot=Ky("state"),Jy[Ot]=!0,Ca=function(a,e){if(Gn(a,Ot))throw new Yn(hd);return e.facade=a,zy(a,Ot,e),e},Zr=function(a){return Gn(a,Ot)?a[Ot]:{}},Da=function(a){return Gn(a,Ot)});var Fe,Ot;md.exports={set:Ca,get:Zr,has:Da,enforce:Zy,getterFor:eT}});var zn=m((tM,vd)=>{"use strict";var tT=jr(),Sd=Function.prototype,bd=Sd.apply,gd=Sd.call;vd.exports=typeof Reflect=="object"&&Reflect.apply||(tT?gd.bind(bd):function(){return gd.apply(bd,arguments)})});var Kn=m((rM,yd)=>{"use strict";var rT=sr(),iT=he();yd.exports=function(a){if(rT(a)==="Function")return iT(a)}});var xd=m(Ed=>{"use strict";var Td={}.propertyIsEnumerable,Id=Object.getOwnPropertyDescriptor,aT=Id&&!Td.call({1:2},1);Ed.f=aT?function(e){var t=Id(this,e);return!!t&&t.enumerable}:Td});var wd=m(Ad=>{"use strict";var sT=Re(),nT=Ee(),oT=xd(),uT=Xr(),lT=or(),cT=Fn(),dT=Ne(),pT=Pn(),Pd=Object.getOwnPropertyDescriptor;Ad.f=sT?Pd:function(e,t){if(e=lT(e),t=cT(t),pT)try{return Pd(e,t)}catch(r){}if(dT(e,t))return uT(!nT(oT.f,e,t),e[t])}});var Jn=m((sM,kd)=>{"use strict";var hT=Ie(),fT=K(),mT=/#|\.prototype\./,ei=function(a,e){var t=gT[bT(a)];return t===vT?!0:t===ST?!1:fT(e)?hT(e):!!e},bT=ei.normalize=function(a){return String(a).replace(mT,".").toLowerCase()},gT=ei.data={},ST=ei.NATIVE="N",vT=ei.POLYFILL="P";kd.exports=ei});var ti=m((nM,$d)=>{"use strict";var Rd=Kn(),yT=Xe(),TT=jr(),IT=Rd(Rd.bind);$d.exports=function(a,e){return yT(a),e===void 0?a:TT?IT(a,e):function(){return a.apply(e,arguments)}}});var $e=m((oM,Md)=>{"use strict";var ri=J(),ET=zn(),xT=Kn(),PT=K(),AT=wd().f,wT=Jn(),dr=ka(),kT=ti(),pr=cr(),Ld=Ne();Kr();var RT=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 ET(a,this,arguments)};return e.prototype=a.prototype,e};Md.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?ri:i?ri[t]:ri[t]&&ri[t].prototype,o=r?dr:dr[t]||pr(dr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,S;for(p in e)l=wT(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Ld(n,p),f=o[p],c&&(a.dontCallGetSet?(S=AT(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=kT(h,ri):a.wrap&&c?g=RT(h):s&&PT(h)?g=xT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&pr(g,"sham",!0),pr(o,p,g),s&&(d=t+"Prototype",Ld(dr,d)||pr(dr,d,{}),pr(dr[d],p,h),a.real&&u&&(l||!u[p])&&pr(u,p,h)))}});var Od=m((uM,Dd)=>{"use strict";var Xn=Re(),$T=Ne(),Cd=Function.prototype,LT=Xn&&Object.getOwnPropertyDescriptor,Zn=$T(Cd,"name"),MT=Zn&&function(){}.name==="something",CT=Zn&&(!Xn||Xn&&LT(Cd,"name").configurable);Dd.exports={EXISTS:Zn,PROPER:MT,CONFIGURABLE:CT}});var Vd=m((lM,Bd)=>{"use strict";var DT=Math.ceil,OT=Math.floor;Bd.exports=Math.trunc||function(e){var t=+e;return(t>0?OT:DT)(t)}});var Oa=m((cM,_d)=>{"use strict";var BT=Vd();_d.exports=function(a){var e=+a;return e!==e||e===0?0:BT(e)}});var Fd=m((dM,Nd)=>{"use strict";var VT=Oa(),_T=Math.max,NT=Math.min;Nd.exports=function(a,e){var t=VT(a);return t<0?_T(t+e,0):NT(t,e)}});var Ud=m((pM,qd)=>{"use strict";var FT=Oa(),qT=Math.min;qd.exports=function(a){var e=FT(a);return e>0?qT(e,9007199254740991):0}});var Ba=m((hM,Hd)=>{"use strict";var UT=Ud();Hd.exports=function(a){return UT(a.length)}});var Wd=m((fM,Gd)=>{"use strict";var HT=or(),jT=Fd(),GT=Ba(),jd=function(a){return function(e,t,r){var i=HT(e),s=GT(i);if(s===0)return!a&&-1;var n=jT(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Gd.exports={includes:jd(!0),indexOf:jd(!1)}});var zd=m((mM,Qd)=>{"use strict";var WT=he(),eo=Ne(),YT=or(),QT=Wd().indexOf,zT=Ma(),Yd=WT([].push);Qd.exports=function(a,e){var t=YT(a),r=0,i=[],s;for(s in t)!eo(zT,s)&&eo(t,s)&&Yd(i,s);for(;e.length>r;)eo(t,s=e[r++])&&(~QT(i,s)||Yd(i,s));return i}});var to=m((bM,Kd)=>{"use strict";Kd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Xd=m((gM,Jd)=>{"use strict";var KT=zd(),JT=to();Jd.exports=Object.keys||function(e){return KT(e,JT)}});var ep=m(Zd=>{"use strict";var XT=Re(),ZT=An(),eI=Dt(),tI=Ye(),rI=or(),iI=Xd();Zd.f=XT&&!ZT?Object.defineProperties:function(e,t){tI(e);for(var r=rI(t),i=iI(t),s=i.length,n=0,o;s>n;)eI.f(e,o=i[n++],r[o]);return e}});var ro=m((vM,tp)=>{"use strict";var aI=Je();tp.exports=aI("document","documentElement")});var no=m((yM,up)=>{"use strict";var sI=Ye(),nI=ep(),rp=to(),oI=Ma(),uI=ro(),lI=Aa(),cI=La(),ip=">",ap="<",ao="prototype",so="script",np=cI("IE_PROTO"),io=function(){},op=function(a){return ap+so+ip+a+ap+"/"+so+ip},sp=function(a){a.write(op("")),a.close();var e=a.parentWindow.Object;return a=null,e},dI=function(){var a=lI("iframe"),e="java"+so+":",t;return a.style.display="none",uI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(op("document.F=Object")),t.close(),t.F},Va,_a=function(){try{Va=new ActiveXObject("htmlfile")}catch(e){}_a=typeof document!="undefined"?document.domain&&Va?sp(Va):dI():sp(Va);for(var a=rp.length;a--;)delete _a[ao][rp[a]];return _a()};oI[np]=!0;up.exports=Object.create||function(e,t){var r;return e!==null?(io[ao]=sI(e),r=new io,io[ao]=null,r[np]=e):r=_a(),t===void 0?r:nI.f(r,t)}});var cp=m((TM,lp)=>{"use strict";var pI=Ie();lp.exports=!pI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var uo=m((IM,pp)=>{"use strict";var hI=Ne(),fI=K(),mI=Jr(),bI=La(),gI=cp(),dp=bI("IE_PROTO"),oo=Object,SI=oo.prototype;pp.exports=gI?oo.getPrototypeOf:function(a){var e=mI(a);if(hI(e,dp))return e[dp];var t=e.constructor;return fI(t)&&e instanceof t?t.prototype:e instanceof oo?SI:null}});var hr=m((EM,hp)=>{"use strict";var vI=cr();hp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:vI(a,e,t),a}});var ho=m((xM,bp)=>{"use strict";var yI=Ie(),TI=K(),II=ke(),EI=no(),fp=uo(),xI=hr(),PI=ne(),AI=_e(),po=PI("iterator"),mp=!1,Ze,lo,co;[].keys&&(co=[].keys(),"next"in co?(lo=fp(fp(co)),lo!==Object.prototype&&(Ze=lo)):mp=!0);var wI=!II(Ze)||yI(function(){var a={};return Ze[po].call(a)!==a});wI?Ze={}:AI&&(Ze=EI(Ze));TI(Ze[po])||xI(Ze,po,function(){return this});bp.exports={IteratorPrototype:Ze,BUGGY_SAFARI_ITERATORS:mp}});var Na=m((PM,Sp)=>{"use strict";var kI=ne(),RI=kI("toStringTag"),gp={};gp[RI]="z";Sp.exports=String(gp)==="[object z]"});var ii=m((AM,vp)=>{"use strict";var $I=Na(),LI=K(),Fa=sr(),MI=ne(),CI=MI("toStringTag"),DI=Object,OI=Fa(function(){return arguments}())==="Arguments",BI=function(a,e){try{return a[e]}catch(t){}};vp.exports=$I?Fa:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=BI(e=DI(a),CI))=="string"?t:OI?Fa(e):(r=Fa(e))==="Object"&&LI(e.callee)?"Arguments":r}});var Tp=m((wM,yp)=>{"use strict";var VI=Na(),_I=ii();yp.exports=VI?{}.toString:function(){return"[object "+_I(this)+"]"}});var ai=m((kM,Ep)=>{"use strict";var NI=Na(),FI=Dt().f,qI=cr(),UI=Ne(),HI=Tp(),jI=ne(),Ip=jI("toStringTag");Ep.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(UI(i,Ip)||FI(i,Ip,{configurable:!0,value:e}),r&&!NI&&qI(i,"toString",HI))}});var Pp=m((RM,xp)=>{"use strict";var GI=ho().IteratorPrototype,WI=no(),YI=Xr(),QI=ai(),zI=Ct(),KI=function(){return this};xp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=WI(GI,{next:YI(+!r,t)}),QI(a,i,!1,!0),zI[i]=KI,a}});var wp=m(($M,Ap)=>{"use strict";var JI=he(),XI=Xe();Ap.exports=function(a,e,t){try{return JI(XI(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Rp=m((LM,kp)=>{"use strict";var ZI=ke();kp.exports=function(a){return ZI(a)||a===null}});var Lp=m((MM,$p)=>{"use strict";var eE=Rp(),tE=String,rE=TypeError;$p.exports=function(a){if(eE(a))return a;throw new rE("Can't set "+tE(a)+" as a prototype")}});var fo=m((CM,Mp)=>{"use strict";var iE=wp(),aE=ke(),sE=Gr(),nE=Lp();Mp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=iE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return sE(i),nE(s),aE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Hp=m((DM,Up)=>{"use strict";var oE=$e(),uE=Ee(),qa=_e(),Fp=Od(),lE=K(),cE=Pp(),Cp=uo(),Dp=fo(),dE=ai(),pE=cr(),mo=hr(),hE=ne(),Op=Ct(),qp=ho(),fE=Fp.PROPER,mE=Fp.CONFIGURABLE,Bp=qp.IteratorPrototype,Ua=qp.BUGGY_SAFARI_ITERATORS,si=hE("iterator"),Vp="keys",ni="values",_p="entries",Np=function(){return this};Up.exports=function(a,e,t,r,i,s,n){cE(t,e,r);var o=function(S){if(S===i&&p)return p;if(!Ua&&S&&S in c)return c[S];switch(S){case Vp:return function(){return new t(this,S)};case ni:return function(){return new t(this,S)};case _p:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[si]||c["@@iterator"]||i&&c[i],p=!Ua&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=Cp(h.call(new a)),f!==Object.prototype&&f.next&&(!qa&&Cp(f)!==Bp&&(Dp?Dp(f,Bp):lE(f[si])||mo(f,si,Np)),dE(f,u,!0,!0),qa&&(Op[u]=Np))),fE&&i===ni&&d&&d.name!==ni&&(!qa&&mE?pE(c,"name",ni):(l=!0,p=function(){return uE(d,this)})),i)if(b={values:o(ni),keys:s?p:o(Vp),entries:o(_p)},n)for(g in b)(Ua||l||!(g in c))&&mo(c,g,b[g]);else oE({target:e,proto:!0,forced:Ua||l},b);return(!qa||n)&&c[si]!==p&&mo(c,si,p,{name:i}),Op[e]=p,b}});var Gp=m((OM,jp)=>{"use strict";jp.exports=function(a,e){return{value:a,done:e}}});var go=m((BM,Kp)=>{"use strict";var bE=or(),bo=Tn(),Wp=Ct(),Qp=Qn(),gE=Dt().f,SE=Hp(),Ha=Gp(),vE=_e(),yE=Re(),zp="Array Iterator",TE=Qp.set,IE=Qp.getterFor(zp);Kp.exports=SE(Array,"Array",function(a,e){TE(this,{type:zp,target:bE(a),index:0,kind:e})},function(){var a=IE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ha(void 0,!0);switch(a.kind){case"keys":return Ha(t,!1);case"values":return Ha(e[t],!1)}return Ha([t,e[t]],!1)},"values");var Yp=Wp.Arguments=Wp.Array;bo("keys");bo("values");bo("entries");if(!vE&&yE&&Yp.name!=="values")try{gE(Yp,"name",{value:"values"})}catch(a){}});var Xp=m((VM,Jp)=>{"use strict";var EE=ne(),xE=Ct(),PE=EE("iterator"),AE=Array.prototype;Jp.exports=function(a){return a!==void 0&&(xE.Array===a||AE[PE]===a)}});var So=m((_M,eh)=>{"use strict";var wE=ii(),Zp=zr(),kE=nr(),RE=Ct(),$E=ne(),LE=$E("iterator");eh.exports=function(a){if(!kE(a))return Zp(a,LE)||Zp(a,"@@iterator")||RE[wE(a)]}});var rh=m((NM,th)=>{"use strict";var ME=Ee(),CE=Xe(),DE=Ye(),OE=Qr(),BE=So(),VE=TypeError;th.exports=function(a,e){var t=arguments.length<2?BE(a):e;if(CE(t))return DE(ME(t,a));throw new VE(OE(a)+" is not iterable")}});var sh=m((FM,ah)=>{"use strict";var _E=Ee(),ih=Ye(),NE=zr();ah.exports=function(a,e,t){var r,i;ih(a);try{if(r=NE(a,"return"),!r){if(e==="throw")throw t;return t}r=_E(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return ih(r),t}});var Ga=m((qM,lh)=>{"use strict";var FE=ti(),qE=Ee(),UE=Ye(),HE=Qr(),jE=Xp(),GE=Ba(),nh=Yr(),WE=rh(),YE=So(),oh=sh(),QE=TypeError,ja=function(a,e){this.stopped=a,this.result=e},uh=ja.prototype;lh.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=FE(e,r),l,c,d,p,h,f,b,g=function(I){return l&&oh(l,"normal",I),new ja(!0,I)},S=function(I){return i?(UE(I),o?u(I[0],I[1],g):u(I[0],I[1])):o?u(I,g):u(I)};if(s)l=a.iterator;else if(n)l=a;else{if(c=YE(a),!c)throw new QE(HE(a)+" is not iterable");if(jE(c)){for(d=0,p=GE(a);p>d;d++)if(h=S(a[d]),h&&nh(uh,h))return h;return new ja(!1)}l=WE(a,c)}for(f=s?a.next:l.next;!(b=qE(f,l)).done;){try{h=S(b.value)}catch(I){oh(l,"throw",I)}if(typeof h=="object"&&h&&nh(uh,h))return h}return new ja(!1)}});var dh=m((UM,ch)=>{"use strict";var zE=Re(),KE=Dt(),JE=Xr();ch.exports=function(a,e,t){zE?KE.f(a,e,JE(0,t)):a[e]=t}});var ph=m(()=>{"use strict";var XE=$e(),ZE=Ga(),ex=dh();XE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return ZE(e,function(r,i){ex(t,r,i)},{AS_ENTRIES:!0}),t}})});var fh=m((GM,hh)=>{"use strict";go();ph();var tx=ka();hh.exports=tx.Object.fromEntries});var bh=m((WM,mh)=>{"use strict";mh.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 Sh=m(()=>{"use strict";go();var rx=bh(),ix=J(),ax=ai(),gh=Ct();for(Wa in rx)ax(ix[Wa],Wa),gh[Wa]=gh.Array;var Wa});var yh=m((zM,vh)=>{"use strict";var sx=fh();Sh();vh.exports=sx});var vo=m((KM,Th)=>{"use strict";var nx=yh();Th.exports=nx});var Ih=m(()=>{"use strict"});var yo=m((ZM,Eh)=>{"use strict";var oi=J(),ox=ur(),ux=sr(),Ya=function(a){return ox.slice(0,a.length)===a};Eh.exports=function(){return Ya("Bun/")?"BUN":Ya("Cloudflare-Workers")?"CLOUDFLARE":Ya("Deno/")?"DENO":Ya("Node.js/")?"NODE":oi.Bun&&typeof Bun.version=="string"?"BUN":oi.Deno&&typeof Deno.version=="object"?"DENO":ux(oi.process)==="process"?"NODE":oi.window&&oi.document?"BROWSER":"REST"}()});var Qa=m((eC,xh)=>{"use strict";var lx=yo();xh.exports=lx==="NODE"});var Ah=m((tC,Ph)=>{"use strict";var cx=Dt();Ph.exports=function(a,e,t){return cx.f(a,e,t)}});var Rh=m((rC,kh)=>{"use strict";var dx=Je(),px=Ah(),hx=ne(),fx=Re(),wh=hx("species");kh.exports=function(a){var e=dx(a);fx&&e&&!e[wh]&&px(e,wh,{configurable:!0,get:function(){return this}})}});var Lh=m((iC,$h)=>{"use strict";var mx=Yr(),bx=TypeError;$h.exports=function(a,e){if(mx(e,a))return a;throw new bx("Incorrect invocation")}});var Io=m((aC,Mh)=>{"use strict";var gx=he(),Sx=K(),To=Kr(),vx=gx(Function.toString);Sx(To.inspectSource)||(To.inspectSource=function(a){return vx(a)});Mh.exports=To.inspectSource});var _h=m((sC,Vh)=>{"use strict";var yx=he(),Tx=Ie(),Ch=K(),Ix=ii(),Ex=Je(),xx=Io(),Dh=function(){},Oh=Ex("Reflect","construct"),Eo=/^\s*(?:class|function)\b/,Px=yx(Eo.exec),Ax=!Eo.test(Dh),ui=function(e){if(!Ch(e))return!1;try{return Oh(Dh,[],e),!0}catch(t){return!1}},Bh=function(e){if(!Ch(e))return!1;switch(Ix(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ax||!!Px(Eo,xx(e))}catch(t){return!0}};Bh.sham=!0;Vh.exports=!Oh||Tx(function(){var a;return ui(ui.call)||!ui(Object)||!ui(function(){a=!0})||a})?Bh:ui});var Fh=m((nC,Nh)=>{"use strict";var wx=_h(),kx=Qr(),Rx=TypeError;Nh.exports=function(a){if(wx(a))return a;throw new Rx(kx(a)+" is not a constructor")}});var xo=m((oC,Uh)=>{"use strict";var qh=Ye(),$x=Fh(),Lx=nr(),Mx=ne(),Cx=Mx("species");Uh.exports=function(a,e){var t=qh(a).constructor,r;return t===void 0||Lx(r=qh(t)[Cx])?e:$x(r)}});var jh=m((uC,Hh)=>{"use strict";var Dx=he();Hh.exports=Dx([].slice)});var Wh=m((lC,Gh)=>{"use strict";var Ox=TypeError;Gh.exports=function(a,e){if(a<e)throw new Ox("Not enough arguments");return a}});var Po=m((cC,Yh)=>{"use strict";var Bx=ur();Yh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Bx)});var Do=m((dC,rf)=>{"use strict";var xe=J(),Vx=zn(),_x=ti(),Qh=K(),Nx=Ne(),tf=Ie(),zh=ro(),Fx=jh(),Kh=Aa(),qx=Wh(),Ux=Po(),Hx=Qa(),Lo=xe.setImmediate,Mo=xe.clearImmediate,jx=xe.process,Ao=xe.Dispatch,Gx=xe.Function,Jh=xe.MessageChannel,Wx=xe.String,wo=0,li={},Xh="onreadystatechange",ci,Bt,ko,Ro;tf(function(){ci=xe.location});var Co=function(a){if(Nx(li,a)){var e=li[a];delete li[a],e()}},$o=function(a){return function(){Co(a)}},Zh=function(a){Co(a.data)},ef=function(a){xe.postMessage(Wx(a),ci.protocol+"//"+ci.host)};(!Lo||!Mo)&&(Lo=function(e){qx(arguments.length,1);var t=Qh(e)?e:Gx(e),r=Fx(arguments,1);return li[++wo]=function(){Vx(t,void 0,r)},Bt(wo),wo},Mo=function(e){delete li[e]},Hx?Bt=function(a){jx.nextTick($o(a))}:Ao&&Ao.now?Bt=function(a){Ao.now($o(a))}:Jh&&!Ux?(ko=new Jh,Ro=ko.port2,ko.port1.onmessage=Zh,Bt=_x(Ro.postMessage,Ro)):xe.addEventListener&&Qh(xe.postMessage)&&!xe.importScripts&&ci&&ci.protocol!=="file:"&&!tf(ef)?(Bt=ef,xe.addEventListener("message",Zh,!1)):Xh in Kh("script")?Bt=function(a){zh.appendChild(Kh("script"))[Xh]=function(){zh.removeChild(this),Co(a)}}:Bt=function(a){setTimeout($o(a),0)});rf.exports={set:Lo,clear:Mo}});var nf=m((pC,sf)=>{"use strict";var af=J(),Yx=Re(),Qx=Object.getOwnPropertyDescriptor;sf.exports=function(a){if(!Yx)return af[a];var e=Qx(af,a);return e&&e.value}});var Oo=m((hC,uf)=>{"use strict";var of=function(){this.head=null,this.tail=null};of.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};uf.exports=of});var cf=m((fC,lf)=>{"use strict";var zx=ur();lf.exports=/ipad|iphone|ipod/i.test(zx)&&typeof Pebble!="undefined"});var pf=m((mC,df)=>{"use strict";var Kx=ur();df.exports=/web0s(?!.*chrome)/i.test(Kx)});var vf=m((bC,Sf)=>{"use strict";var mr=J(),Jx=nf(),hf=ti(),Bo=Do().set,Xx=Oo(),Zx=Po(),eP=cf(),tP=pf(),Vo=Qa(),ff=mr.MutationObserver||mr.WebKitMutationObserver,mf=mr.document,bf=mr.process,za=mr.Promise,Fo=Jx("queueMicrotask"),fr,_o,No,Ka,gf;Fo||(di=new Xx,pi=function(){var a,e;for(Vo&&(a=bf.domain)&&a.exit();e=di.get();)try{e()}catch(t){throw di.head&&fr(),t}a&&a.enter()},!Zx&&!Vo&&!tP&&ff&&mf?(_o=!0,No=mf.createTextNode(""),new ff(pi).observe(No,{characterData:!0}),fr=function(){No.data=_o=!_o}):!eP&&za&&za.resolve?(Ka=za.resolve(void 0),Ka.constructor=za,gf=hf(Ka.then,Ka),fr=function(){gf(pi)}):Vo?fr=function(){bf.nextTick(pi)}:(Bo=hf(Bo,mr),fr=function(){Bo(pi)}),Fo=function(a){di.head||fr(),di.add(a)});var di,pi;Sf.exports=Fo});var Tf=m((gC,yf)=>{"use strict";yf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ja=m((SC,If)=>{"use strict";If.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Vt=m((vC,Ef)=>{"use strict";var rP=J();Ef.exports=rP.Promise});var br=m((yC,wf)=>{"use strict";var iP=J(),hi=Vt(),aP=K(),sP=Jn(),nP=Io(),oP=ne(),xf=yo(),uP=_e(),qo=$n(),Pf=hi&&hi.prototype,lP=oP("species"),Uo=!1,Af=aP(iP.PromiseRejectionEvent),cP=sP("Promise",function(){var a=nP(hi),e=a!==String(hi);if(!e&&qo===66||uP&&!(Pf.catch&&Pf.finally))return!0;if(!qo||qo<51||!/native code/.test(a)){var t=new hi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[lP]=r,Uo=t.then(function(){})instanceof r,!Uo)return!0}return!e&&(xf==="BROWSER"||xf==="DENO")&&!Af});wf.exports={CONSTRUCTOR:cP,REJECTION_EVENT:Af,SUBCLASSING:Uo}});var gr=m((TC,Rf)=>{"use strict";var kf=Xe(),dP=TypeError,pP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new dP("Bad Promise constructor");e=r,t=i}),this.resolve=kf(e),this.reject=kf(t)};Rf.exports.f=function(a){return new pP(a)}});var Qf=m(()=>{"use strict";var hP=$e(),fP=_e(),ts=Qa(),ft=J(),Tr=Ee(),$f=hr(),Lf=fo(),mP=ai(),bP=Rh(),gP=Xe(),es=K(),SP=ke(),vP=Lh(),yP=xo(),Bf=Do().set,Yo=vf(),TP=Tf(),IP=Ja(),EP=Oo(),Vf=Qn(),rs=Vt(),Qo=br(),_f=gr(),is="Promise",Nf=Qo.CONSTRUCTOR,xP=Qo.REJECTION_EVENT,PP=Qo.SUBCLASSING,Ho=Vf.getterFor(is),AP=Vf.set,Sr=rs&&rs.prototype,_t=rs,Xa=Sr,Ff=ft.TypeError,jo=ft.document,zo=ft.process,Go=_f.f,wP=Go,kP=!!(jo&&jo.createEvent&&ft.dispatchEvent),qf="unhandledrejection",RP="rejectionhandled",Mf=0,Uf=1,$P=2,Ko=1,Hf=2,Za,Cf,LP,Df,jf=function(a){var e;return SP(a)&&es(e=a.then)?e:!1},Gf=function(a,e){var t=e.value,r=e.state===Uf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Hf&&CP(e),e.rejection=Ko),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Ff("Promise-chain cycle")):(l=jf(u))?Tr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Wf=function(a,e){a.notified||(a.notified=!0,Yo(function(){for(var t=a.reactions,r;r=t.get();)Gf(r,a);a.notified=!1,e&&!a.rejection&&MP(a)}))},Yf=function(a,e,t){var r,i;kP?(r=jo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),ft.dispatchEvent(r)):r={promise:e,reason:t},!xP&&(i=ft["on"+a])?i(r):a===qf&&TP("Unhandled promise rejection",t)},MP=function(a){Tr(Bf,ft,function(){var e=a.facade,t=a.value,r=Of(a),i;if(r&&(i=IP(function(){ts?zo.emit("unhandledRejection",t,e):Yf(qf,e,t)}),a.rejection=ts||Of(a)?Hf:Ko,i.error))throw i.value})},Of=function(a){return a.rejection!==Ko&&!a.parent},CP=function(a){Tr(Bf,ft,function(){var e=a.facade;ts?zo.emit("rejectionHandled",e):Yf(RP,e,a.value)})},vr=function(a,e,t){return function(r){a(e,r,t)}},yr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=$P,Wf(a,!0))},Wo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Ff("Promise can't be resolved itself");var r=jf(e);r?Yo(function(){var i={done:!1};try{Tr(r,e,vr(Wo,i,a),vr(yr,i,a))}catch(s){yr(i,s,a)}}):(a.value=e,a.state=Uf,Wf(a,!1))}catch(i){yr({done:!1},i,a)}}};if(Nf&&(_t=function(e){vP(this,Xa),gP(e),Tr(Za,this);var t=Ho(this);try{e(vr(Wo,t),vr(yr,t))}catch(r){yr(t,r)}},Xa=_t.prototype,Za=function(e){AP(this,{type:is,done:!1,notified:!1,parent:!1,reactions:new EP,rejection:!1,state:Mf,value:void 0})},Za.prototype=$f(Xa,"then",function(e,t){var r=Ho(this),i=Go(yP(this,_t));return r.parent=!0,i.ok=es(e)?e:!0,i.fail=es(t)&&t,i.domain=ts?zo.domain:void 0,r.state===Mf?r.reactions.add(i):Yo(function(){Gf(i,r)}),i.promise}),Cf=function(){var a=new Za,e=Ho(a);this.promise=a,this.resolve=vr(Wo,e),this.reject=vr(yr,e)},_f.f=Go=function(a){return a===_t||a===LP?new Cf(a):wP(a)},!fP&&es(rs)&&Sr!==Object.prototype)){Df=Sr.then,PP||$f(Sr,"then",function(e,t){var r=this;return new _t(function(i,s){Tr(Df,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Sr.constructor}catch(a){}Lf&&Lf(Sr,Xa)}hP({global:!0,constructor:!0,wrap:!0,forced:Nf},{Promise:_t});mP(_t,is,!1,!0);bP(is)});var Zf=m((xC,Xf)=>{"use strict";var DP=ne(),Kf=DP("iterator"),Jf=!1;try{zf=0,Jo={next:function(){return{done:!!zf++}},return:function(){Jf=!0}},Jo[Kf]=function(){return this},Array.from(Jo,function(){throw 2})}catch(a){}var zf,Jo;Xf.exports=function(a,e){try{if(!e&&!Jf)return!1}catch(i){return!1}var t=!1;try{var r={};r[Kf]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Xo=m((PC,em)=>{"use strict";var OP=Vt(),BP=Zf(),VP=br().CONSTRUCTOR;em.exports=VP||!BP(function(a){OP.all(a).then(void 0,function(){})})});var tm=m(()=>{"use strict";var _P=$e(),NP=Ee(),FP=Xe(),qP=gr(),UP=Ja(),HP=Ga(),jP=Xo();_P({target:"Promise",stat:!0,forced:jP},{all:function(e){var t=this,r=qP.f(t),i=r.resolve,s=r.reject,n=UP(function(){var o=FP(t.resolve),u=[],l=0,c=1;HP(e,function(d){var p=l++,h=!1;c++,NP(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 im=m(()=>{"use strict";var GP=$e(),WP=_e(),YP=br().CONSTRUCTOR,eu=Vt(),QP=Je(),zP=K(),KP=hr(),rm=eu&&eu.prototype;GP({target:"Promise",proto:!0,forced:YP,real:!0},{catch:function(a){return this.then(void 0,a)}});!WP&&zP(eu)&&(Zo=QP("Promise").prototype.catch,rm.catch!==Zo&&KP(rm,"catch",Zo,{unsafe:!0}));var Zo});var am=m(()=>{"use strict";var JP=$e(),XP=Ee(),ZP=Xe(),eA=gr(),tA=Ja(),rA=Ga(),iA=Xo();JP({target:"Promise",stat:!0,forced:iA},{race:function(e){var t=this,r=eA.f(t),i=r.reject,s=tA(function(){var n=ZP(t.resolve);rA(e,function(o){XP(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var sm=m(()=>{"use strict";var aA=$e(),sA=gr(),nA=br().CONSTRUCTOR;aA({target:"Promise",stat:!0,forced:nA},{reject:function(e){var t=sA.f(this),r=t.reject;return r(e),t.promise}})});var tu=m((DC,nm)=>{"use strict";var oA=Ye(),uA=ke(),lA=gr();nm.exports=function(a,e){if(oA(a),uA(e)&&e.constructor===a)return e;var t=lA.f(a),r=t.resolve;return r(e),t.promise}});var lm=m(()=>{"use strict";var cA=$e(),dA=Je(),om=_e(),pA=Vt(),um=br().CONSTRUCTOR,hA=tu(),fA=dA("Promise"),mA=om&&!um;cA({target:"Promise",stat:!0,forced:om||um},{resolve:function(e){return hA(mA&&this===fA?pA:this,e)}})});var cm=m(()=>{"use strict";Qf();tm();im();am();sm();lm()});var fm=m(()=>{"use strict";var bA=$e(),gA=_e(),as=Vt(),SA=Ie(),pm=Je(),hm=K(),vA=xo(),dm=tu(),yA=hr(),iu=as&&as.prototype,TA=!!as&&SA(function(){iu.finally.call({then:function(){}},function(){})});bA({target:"Promise",proto:!0,real:!0,forced:TA},{finally:function(a){var e=vA(this,pm("Promise")),t=hm(a);return this.then(t?function(r){return dm(e,a()).then(function(){return r})}:a,t?function(r){return dm(e,a()).then(function(){throw r})}:a)}});!gA&&hm(as)&&(ru=pm("Promise").prototype.finally,iu.finally!==ru&&yA(iu,"finally",ru,{unsafe:!0}));var ru});var ss=m((qC,mm)=>{"use strict";var IA=Je();mm.exports=IA});var gm=m((UC,bm)=>{"use strict";Ih();cm();fm();var EA=ss();bm.exports=EA("Promise","finally")});var vm=m((HC,Sm)=>{"use strict";var xA=gm();Sm.exports=xA});var ns=m((jC,ym)=>{"use strict";var PA=vm();ym.exports=PA});var Gm=m(()=>{"use strict";var ew=$e(),tw=Jr(),rw=Ba(),iw=Oa(),aw=Tn();ew({target:"Array",proto:!0},{at:function(e){var t=tw(this),r=rw(t),i=iw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});aw("at")});var Ym=m((ZD,Wm)=>{"use strict";Gm();var sw=ss();Wm.exports=sw("Array","at")});var zm=m((e0,Qm)=>{"use strict";var nw=Ym();Qm.exports=nw});var gi=m((t0,Km)=>{"use strict";var ow=zm();Km.exports=ow});var Qb=m(()=>{"use strict"});var zb=m(()=>{"use strict"});var Jb=m((u_,Kb)=>{"use strict";var gk=ke(),Sk=sr(),vk=ne(),yk=vk("match");Kb.exports=function(a){var e;return gk(a)&&((e=a[yk])!==void 0?!!e:Sk(a)==="RegExp")}});var Zb=m((l_,Xb)=>{"use strict";var Tk=ii(),Ik=String;Xb.exports=function(a){if(Tk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Ik(a)}});var tg=m((c_,eg)=>{"use strict";var Ek=Ye();eg.exports=function(){var a=Ek(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 ag=m((d_,ig)=>{"use strict";var xk=Ee(),Pk=Ne(),Ak=Yr(),wk=tg(),rg=RegExp.prototype;ig.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in rg)&&!Pk(a,"flags")&&Ak(rg,a)?xk(wk,a):e}});var ng=m((p_,sg)=>{"use strict";var Cu=he(),kk=Jr(),Rk=Math.floor,Lu=Cu("".charAt),$k=Cu("".replace),Mu=Cu("".slice),Lk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Mk=/\$([$&'`]|\d{1,2})/g;sg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=Mk;return i!==void 0&&(i=kk(i),u=Lk),$k(s,u,function(l,c){var d;switch(Lu(c,0)){case"$":return"$";case"&":return a;case"`":return Mu(e,0,t);case"'":return Mu(e,n);case"<":d=i[Mu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=Rk(p/10);return h===0?l:h<=o?r[h-1]===void 0?Lu(c,1):r[h-1]+Lu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var lg=m(()=>{"use strict";var Ck=$e(),Dk=Ee(),Ou=he(),og=Gr(),Ok=K(),Bk=nr(),Vk=Jb(),Lr=Zb(),_k=zr(),Nk=ag(),Fk=ng(),qk=ne(),Uk=_e(),Hk=qk("replace"),jk=TypeError,Du=Ou("".indexOf),Gk=Ou("".replace),ug=Ou("".slice),Wk=Math.max;Ck({target:"String",proto:!0},{replaceAll:function(e,t){var r=og(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!Bk(e)){if(i=Vk(e),i&&(s=Lr(og(Nk(e))),!~Du(s,"g")))throw new jk("`.replaceAll` does not allow non-global regexes");if(n=_k(e,Hk),n)return Dk(n,e,r,t);if(Uk&&i)return Gk(Lr(r),e,t)}for(o=Lr(r),u=Lr(e),l=Ok(t),l||(t=Lr(t)),c=u.length,d=Wk(1,c),p=Du(o,u);p!==-1;)h=l?Lr(t(u,p,o)):Fk(u,o,p,[],void 0,t),b+=ug(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Du(o,u,p+d);return f<o.length&&(b+=ug(o,f)),b}})});var dg=m((m_,cg)=>{"use strict";Qb();zb();lg();var Yk=ss();cg.exports=Yk("String","replaceAll")});var hg=m((b_,pg)=>{"use strict";var Qk=dg();pg.exports=Qk});var mg=m((g_,fg)=>{"use strict";var zk=hg();fg.exports=zk});var Nl="2.0.108-dev.7ca5c32c.0";var pe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(pe||{}),ht=(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))(ht||{});var Ea=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Ea||{}),mn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(mn||{});var bn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(bn||{});import{assertNever as Gl,assertNonNullable as dv,isNonNullable as xa,ValueSubject as gn,Subject as pv,Subscription as hv,merge as fv,observableFrom as mv,fromEvent as ql,map as Ul,tap as Hl,filterChanged as bv,isNullable as Sn,ErrorCategory as jl}from"@vkontakte/videoplayer-shared";var Fl=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 Pa=class{constructor(e){this.connection$=new gn(void 0);this.castState$=new gn("NOT_AVAILABLE");this.errorEvent$=new pv;this.realCastState$=new gn("NOT_AVAILABLE");this.subscription=new hv;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=xa((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Fl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:jl.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(){xa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Sn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Sn(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(ql(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 Gl(i.sessionState)}})).add(fv(ql(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Hl(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Ul(i=>i.castState)),mv([r.getCastState()])).pipe(bv(),Ul(gv),Hl(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o;let s=i==="CONNECTED",n=xa(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();dv(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;(Sn(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"?xa(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:jl.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},gv=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 Gl(a)}};var mS=We(vo(),1);var $m=We(ns(),1);import{assertNever as Tm}from"@vkontakte/videoplayer-shared";var se=(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:Tm(t)}return a},au=(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:Tm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as AA,Subject as os,merge as Im}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new os;this.transitionEnded$=new os;this.transitionUpdated$=new os;this.forceChanged$=new os;this.stateChangeStarted$=Im(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Im(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||AA(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 wA}from"@vkontakte/videoplayer-shared";var Em=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 wA(a)}};import{assertNever as Ir,assertNonNullable as Nt,debounce as xm,ErrorCategory as Pm,fromEvent as Ft,isNonNullable as Am,map as wm,merge as km,observableFrom as kA,Subject as RA,Subscription as su,timeout as $A,getHighestQuality as LA}from"@vkontakte/videoplayer-shared";var MA=5,CA=5,DA=500,Rm=7e3,fi=class{constructor(e){this.subscription=new su;this.loadMediaTimeoutSubscription=new su;this.videoState=new L("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:Ir(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:Ir(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:Ir(e)}break}default:Ir(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Em(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 su;this.subscription.add(e),this.subscription.add(km(this.videoState.stateChangeStarted$.pipe(wm(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(wm(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 RA;e.add(i.pipe(xm(DA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Ft(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)>MA)&&i.next(o),s=o})),e.add(Ft(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Ft(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ft(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ft(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<CA&&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:Ir(n)}}),t(Ft(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Ft(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=km(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,kA(["init"])).pipe(xm(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];Nt(c);let d=LA(Object.keys(c));Nt(d);let p=c[d];Nt(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Nt(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];Nt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Nt(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];Nt(c),r=se(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:Pm.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ir(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 Am(o)&&(n.metadata.title=o),Am(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(Rm).subscribe(()=>s(`timeout(${Rm})`)))});(0,$m.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:Pm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Mm}from"@vkontakte/videoplayer-shared";import{clearVideoElement as OA}from"@vkontakte/videoplayer-shared";var Lm=a=>{try{a.pause(),a.playbackRate=0,OA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as BA,Subscription as VA}from"@vkontakte/videoplayer-shared";var nu=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)}},ou=window.WeakMap?new WeakMap:new nu,uu=window.WeakMap?new WeakMap:new Map,_A=(a,e=20)=>{let t=0;return BA(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?Mm(t):(t=document.createElement("video"),a.appendChild(t)),ou.set(t,r);let i=new VA;return i.add(_A(t,e)),uu.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=uu.get(a);e==null||e.unsubscribe(),uu.delete(a);let t=ou.get(a);ou.delete(a),t?Mm(a):Lm(a)};import{assertNonNullable as mi,isNonNullable as ze,isNullable as qA,fromEvent as Er,merge as Cm,observableFrom as Dm,filterChanged as Om,map as bi,Subject as Bm,Subscription as UA,ValueSubject as HA,ErrorCategory as jA}from"@vkontakte/videoplayer-shared";import{isNonNullable as lu,isNullable as NA,Subscription as FA}from"@vkontakte/videoplayer-shared";var us=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=NA(i),l=new FA;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},Qe=(a,e,t)=>us(e,()=>a.loop,r=>{lu(r)&&(a.loop=r)},{onError:t}),be=(a,e,t,r)=>us(e,()=>({muted:a.muted,volume:a.volume}),i=>{lu(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}),Le=(a,e,t,r)=>us(e,()=>a.playbackRate,i=>{lu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),mt=us;var GA=a=>["__",a.language,a.label].join("|"),WA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},cu=class a{constructor(){this.available$=new Bm;this.current$=new HA(void 0);this.error$=new Bm;this.subscription=new UA;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:jA.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(mt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{ze(s)&&this.setInternal(s)},{equal:(s,n)=>ze(s)&&ze(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(bi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(mt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{ze(s)&&this.setExternal(s)},{equal:(s,n)=>ze(s)&&ze(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(bi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(mt(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(mt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){mi(this.video);let{textTracks:e}=this.video;this.subscription.add(Er(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Cm(Er(e,"addtrack"),Er(e,"removetrack"),Dm(["init"])).pipe(bi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Om((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Cm(Er(e,"change"),Dm(["init"])).pipe(bi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),bi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Om()).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(Er(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(Er(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;ze(t.align)&&(i.align=t.align),ze(t.position)&&(i.position=t.position),ze(t.size)&&(i.size=t.size),ze(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){mi(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:GA(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){mi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(qA(e)||!WA(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){mi(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){mi(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)}},Me=cu;var tt=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 Vm=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},du=a=>{let e=Vm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},_m=a=>{let e=Vm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ce,map as bt,merge as Fm,filterChanged as QA,isNonNullable as qm,Subject as zA,filter as Um,mapTo as Hm,combine as KA,once as JA,ErrorCategory as XA,ValueSubject as jm,clientChecker as ZA}from"@vkontakte/videoplayer-shared";var YA=3,Nm=(a,e,t=YA)=>{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=>Ce(a,v).pipe(Hm(void 0)),r=Fm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>Ce(a,v))).pipe(bt(v=>v.type==="ended"?a.readyState<2:a.readyState<3),QA()),i=Fm(Ce(a,"progress"),Ce(a,"timeupdate")).pipe(bt(()=>Nm(a.buffered,a.currentTime))),s=ZA.isSafari?KA({play:e("play").pipe(JA()),playing:e("playing")}).pipe(Hm(void 0)):e("playing"),n=Ce(a,"volumechange").pipe(bt(()=>({muted:a.muted,volume:a.volume}))),o=Ce(a,"ratechange").pipe(bt(()=>a.playbackRate)),u=Ce(a,"error").pipe(Um(()=>!!(a.error||a.played.length)),bt(()=>{var y;let v=a.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:XA.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(y=a.error)!=null?y:void 0}})),l=Ce(a,"timeupdate").pipe(bt(()=>a.currentTime)),c=new zA,d=.3,p;l.subscribe(v=>{a.loop&&qm(p)&&qm(v)&&p>=a.duration-d&&v<=d&&c.next(p),p=v});let h=e("pause").pipe(Um(()=>!a.error&&p!==a.duration)),f=Ce(a,"enterpictureinpicture"),b=Ce(a,"leavepictureinpicture"),g=new jm(_m(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new jm(du(a));return Ce(a,"fullscreenchange").pipe(bt(()=>du(a))).subscribe(S),{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$:Ce(a,"durationchange").pipe(bt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S}};import{VideoQuality as gt}from"@vkontakte/videoplayer-shared";var St=a=>{switch(a){case"mobile":return gt.Q_144P;case"lowest":return gt.Q_240P;case"low":return gt.Q_360P;case"sd":case"medium":return gt.Q_480P;case"hd":case"high":return gt.Q_720P;case"fullhd":case"full":return gt.Q_1080P;case"quadhd":case"quad":return gt.Q_1440P;case"ultrahd":case"ultra":return gt.Q_2160P}};var bu=We(gi(),1);import{isNonNullable as vt,isNullable as hu,now as rb,isHigher as fu,isHigherOrEqual as eb,isInvariantQuality as tb,isLower as mu,isLowerOrEqual as uw,videoSizeToQuality as lw,assertNotEmptyArray as cw}from"@vkontakte/videoplayer-shared";var pu=!1,rt={},Jm=a=>{pu=a},Xm=()=>{rt={}},Zm=a=>{a(rt)},Si=(a,e)=>{var t;pu&&(rt.meta=(t=rt.meta)!=null?t:{},rt.meta[a]=e)},oe=class{constructor(e){this.name=e}next(e){var r,i;if(!pu)return;rt.series=(r=rt.series)!=null?r:{};let t=(i=rt.series[this.name])!=null?i:[];t.push([Date.now(),e]),rt.series[this.name]=t}};var dw=new oe("best_bitrate"),pw=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t,ls=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=rb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},hw='Assertion "ABR Tracks is empty array" failed',fw=(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 G,N,R,F,_;cw(a,hw);let p=r.usePixelRatio&&(G=window.devicePixelRatio)!=null?G: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&&lw(h),b=r.considerPlaybackRate&&vt(o)?o:1,g=a.filter(P=>!tb(P.quality)).sort((P,x)=>fu(P.quality,x.quality)?-1:1),S=(N=(0,bu.default)(g,-1))==null?void 0:N.quality,I=(R=(0,bu.default)(g,0))==null?void 0:R.quality,v=hu(i)||vt(i.min)&&vt(i.max)&&mu(i.max,i.min)||vt(i.min)&&I&&fu(i.min,I)||vt(i.max)&&S&&mu(i.max,S),y=b*pw(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),T={},C=g.filter(P=>(f?mu(P.quality,f):!0)?(vt(t)&&isFinite(t)&&vt(P.bitrate)?t-s>=P.bitrate*y:!0)?r.lazyQualitySwitch&&vt(r.minBufferToSwitchUp)&&u&&!tb(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&fu(P.quality,u.quality)?(T[P.quality]="Buffer",!1):!!c&&eb(P.quality,c)?(T[P.quality]="DroppedFramesLimit",!1):v||(hu(i.max)||uw(P.quality,i.max))&&(hu(i.min)||eb(P.quality,i.min))?!0:(T[P.quality]="FitsQualityLimits",!1):(T[P.quality]="FitsThroughput",!1):(T[P.quality]="FitsContainer",!1))[0];C&&C.bitrate&&dw.next(C.bitrate);let $=(F=C!=null?C:g[Math.ceil((g.length-1)/2)])!=null?F:a[0];$.quality!==((_=l==null?void 0:l.last)==null?void 0:_.quality)&&d({message:`
7
- [available tracks]
8
- ${a.map(P=>`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate} }`).join(`
6
+ var Iv=Object.create;var $n=Object.defineProperty,Ev=Object.defineProperties,xv=Object.getOwnPropertyDescriptor,Av=Object.getOwnPropertyDescriptors,Pv=Object.getOwnPropertyNames,Ga=Object.getOwnPropertySymbols,wv=Object.getPrototypeOf,Ln=Object.prototype.hasOwnProperty,cl=Object.prototype.propertyIsEnumerable;var kv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var Je=Math.pow,ul=(a,e,t)=>e in a?$n(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,A=(a,e)=>{for(var t in e||(e={}))Ln.call(e,t)&&ul(a,t,e[t]);if(Ga)for(var t of Ga(e))cl.call(e,t)&&ul(a,t,e[t]);return a},M=(a,e)=>Ev(a,Av(e));var ll=(a,e)=>{var t={};for(var r in a)Ln.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&Ga)for(var r of Ga(a))e.indexOf(r)<0&&cl.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Rv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Pv(e))!Ln.call(a,i)&&i!==t&&$n(a,i,{get:()=>e[i],enumerable:!(r=xv(e,i))||r.enumerable});return a};var Xe=(a,e,t)=>(t=a!=null?Iv(wv(a)):{},Rv(e||!a||!a.__esModule?$n(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())}),$v=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 $v,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[kv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var xe=m((PL,Sl)=>{"use strict";Sl.exports=function(a){try{return!!a()}catch(e){return!0}}});var ii=m((wL,vl)=>{"use strict";var _v=xe();vl.exports=!_v(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var fe=m((kL,Il)=>{"use strict";var yl=ii(),Tl=Function.prototype,On=Tl.call,Nv=yl&&Tl.bind.bind(On,On);Il.exports=yl?Nv:function(a){return function(){return On.apply(a,arguments)}}});var gr=m((RL,xl)=>{"use strict";var El=fe(),Fv=El({}.toString),qv=El("".slice);xl.exports=function(a){return qv(Fv(a),8,-1)}});var Pl=m(($L,Al)=>{"use strict";var Uv=fe(),Hv=xe(),jv=gr(),Vn=Object,Gv=Uv("".split);Al.exports=Hv(function(){return!Vn("z").propertyIsEnumerable(0)})?function(a){return jv(a)==="String"?Gv(a,""):Vn(a)}:Vn});var Sr=m((LL,wl)=>{"use strict";wl.exports=function(a){return a==null}});var ai=m((ML,kl)=>{"use strict";var Wv=Sr(),Yv=TypeError;kl.exports=function(a){if(Wv(a))throw new Yv("Can't call method on "+a);return a}});var vr=m((CL,Rl)=>{"use strict";var Qv=Pl(),zv=ai();Rl.exports=function(a){return Qv(zv(a))}});var _n=m((DL,$l)=>{"use strict";$l.exports=function(){}});var Ht=m((BL,Ll)=>{"use strict";Ll.exports={}});var J=m((Nn,Ml)=>{"use strict";var si=function(a){return a&&a.Math===Math&&a};Ml.exports=si(typeof globalThis=="object"&&globalThis)||si(typeof window=="object"&&window)||si(typeof self=="object"&&self)||si(typeof global=="object"&&global)||si(typeof Nn=="object"&&Nn)||function(){return this}()||Function("return this")()});var K=m((OL,Cl)=>{"use strict";var Fn=typeof document=="object"&&document.all;Cl.exports=typeof Fn=="undefined"&&Fn!==void 0?function(a){return typeof a=="function"||a===Fn}:function(a){return typeof a=="function"}});var Ol=m((VL,Bl)=>{"use strict";var Kv=J(),Jv=K(),Dl=Kv.WeakMap;Bl.exports=Jv(Dl)&&/native code/.test(String(Dl))});var Le=m((_L,Vl)=>{"use strict";var Xv=K();Vl.exports=function(a){return typeof a=="object"?a!==null:Xv(a)}});var Me=m((NL,_l)=>{"use strict";var Zv=xe();_l.exports=!Zv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var za=m((FL,Fl)=>{"use strict";var ey=J(),Nl=Le(),qn=ey.document,ty=Nl(qn)&&Nl(qn.createElement);Fl.exports=function(a){return ty?qn.createElement(a):{}}});var Un=m((qL,ql)=>{"use strict";var ry=Me(),iy=xe(),ay=za();ql.exports=!ry&&!iy(function(){return Object.defineProperty(ay("div"),"a",{get:function(){return 7}}).a!==7})});var Hn=m((UL,Ul)=>{"use strict";var sy=Me(),ny=xe();Ul.exports=sy&&ny(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ze=m((HL,Hl)=>{"use strict";var oy=Le(),uy=String,cy=TypeError;Hl.exports=function(a){if(oy(a))return a;throw new cy(uy(a)+" is not an object")}});var Ae=m((jL,jl)=>{"use strict";var ly=ii(),Ka=Function.prototype.call;jl.exports=ly?Ka.bind(Ka):function(){return Ka.apply(Ka,arguments)}});var Ja=m((GL,Gl)=>{"use strict";Gl.exports={}});var at=m((WL,Yl)=>{"use strict";var jn=Ja(),Gn=J(),dy=K(),Wl=function(a){return dy(a)?a:void 0};Yl.exports=function(a,e){return arguments.length<2?Wl(jn[a])||Wl(Gn[a]):jn[a]&&jn[a][e]||Gn[a]&&Gn[a][e]}});var ni=m((YL,Ql)=>{"use strict";var py=fe();Ql.exports=py({}.isPrototypeOf)});var yr=m((QL,Jl)=>{"use strict";var hy=J(),zl=hy.navigator,Kl=zl&&zl.userAgent;Jl.exports=Kl?String(Kl):""});var Yn=m((zL,id)=>{"use strict";var rd=J(),Wn=yr(),Xl=rd.process,Zl=rd.Deno,ed=Xl&&Xl.versions||Zl&&Zl.version,td=ed&&ed.v8,Ue,Xa;td&&(Ue=td.split("."),Xa=Ue[0]>0&&Ue[0]<4?1:+(Ue[0]+Ue[1]));!Xa&&Wn&&(Ue=Wn.match(/Edge\/(\d+)/),(!Ue||Ue[1]>=74)&&(Ue=Wn.match(/Chrome\/(\d+)/),Ue&&(Xa=+Ue[1])));id.exports=Xa});var Qn=m((KL,sd)=>{"use strict";var ad=Yn(),fy=xe(),my=J(),by=my.String;sd.exports=!!Object.getOwnPropertySymbols&&!fy(function(){var a=Symbol("symbol detection");return!by(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&ad&&ad<41})});var zn=m((JL,nd)=>{"use strict";var gy=Qn();nd.exports=gy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Kn=m((XL,od)=>{"use strict";var Sy=at(),vy=K(),yy=ni(),Ty=zn(),Iy=Object;od.exports=Ty?function(a){return typeof a=="symbol"}:function(a){var e=Sy("Symbol");return vy(e)&&yy(e.prototype,Iy(a))}});var oi=m((ZL,ud)=>{"use strict";var Ey=String;ud.exports=function(a){try{return Ey(a)}catch(e){return"Object"}}});var st=m((eM,cd)=>{"use strict";var xy=K(),Ay=oi(),Py=TypeError;cd.exports=function(a){if(xy(a))return a;throw new Py(Ay(a)+" is not a function")}});var ui=m((tM,ld)=>{"use strict";var wy=st(),ky=Sr();ld.exports=function(a,e){var t=a[e];return ky(t)?void 0:wy(t)}});var pd=m((rM,dd)=>{"use strict";var Jn=Ae(),Xn=K(),Zn=Le(),Ry=TypeError;dd.exports=function(a,e){var t,r;if(e==="string"&&Xn(t=a.toString)&&!Zn(r=Jn(t,a))||Xn(t=a.valueOf)&&!Zn(r=Jn(t,a))||e!=="string"&&Xn(t=a.toString)&&!Zn(r=Jn(t,a)))return r;throw new Ry("Can't convert object to primitive value")}});var He=m((iM,hd)=>{"use strict";hd.exports=!0});var bd=m((aM,md)=>{"use strict";var fd=J(),$y=Object.defineProperty;md.exports=function(a,e){try{$y(fd,a,{value:e,configurable:!0,writable:!0})}catch(t){fd[a]=e}return e}});var ci=m((sM,vd)=>{"use strict";var Ly=He(),My=J(),Cy=bd(),gd="__core-js_shared__",Sd=vd.exports=My[gd]||Cy(gd,{});(Sd.versions||(Sd.versions=[])).push({version:"3.38.0",mode:Ly?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var eo=m((nM,Td)=>{"use strict";var yd=ci();Td.exports=function(a,e){return yd[a]||(yd[a]=e||{})}});var li=m((oM,Id)=>{"use strict";var Dy=ai(),By=Object;Id.exports=function(a){return By(Dy(a))}});var je=m((uM,Ed)=>{"use strict";var Oy=fe(),Vy=li(),_y=Oy({}.hasOwnProperty);Ed.exports=Object.hasOwn||function(e,t){return _y(Vy(e),t)}});var to=m((cM,xd)=>{"use strict";var Ny=fe(),Fy=0,qy=Math.random(),Uy=Ny(1 .toString);xd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Uy(++Fy+qy,36)}});var oe=m((lM,Pd)=>{"use strict";var Hy=J(),jy=eo(),Ad=je(),Gy=to(),Wy=Qn(),Yy=zn(),Tr=Hy.Symbol,ro=jy("wks"),Qy=Yy?Tr.for||Tr:Tr&&Tr.withoutSetter||Gy;Pd.exports=function(a){return Ad(ro,a)||(ro[a]=Wy&&Ad(Tr,a)?Tr[a]:Qy("Symbol."+a)),ro[a]}});var $d=m((dM,Rd)=>{"use strict";var zy=Ae(),wd=Le(),kd=Kn(),Ky=ui(),Jy=pd(),Xy=oe(),Zy=TypeError,eT=Xy("toPrimitive");Rd.exports=function(a,e){if(!wd(a)||kd(a))return a;var t=Ky(a,eT),r;if(t){if(e===void 0&&(e="default"),r=zy(t,a,e),!wd(r)||kd(r))return r;throw new Zy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Jy(a,e)}});var io=m((pM,Ld)=>{"use strict";var tT=$d(),rT=Kn();Ld.exports=function(a){var e=tT(a,"string");return rT(e)?e:e+""}});var jt=m(Cd=>{"use strict";var iT=Me(),aT=Un(),sT=Hn(),Za=Ze(),Md=io(),nT=TypeError,ao=Object.defineProperty,oT=Object.getOwnPropertyDescriptor,so="enumerable",no="configurable",oo="writable";Cd.f=iT?sT?function(e,t,r){if(Za(e),t=Md(t),Za(r),typeof e=="function"&&t==="prototype"&&"value"in r&&oo in r&&!r[oo]){var i=oT(e,t);i&&i[oo]&&(e[t]=r.value,r={configurable:no in r?r[no]:i[no],enumerable:so in r?r[so]:i[so],writable:!1})}return ao(e,t,r)}:ao:function(e,t,r){if(Za(e),t=Md(t),Za(r),aT)try{return ao(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new nT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var di=m((fM,Dd)=>{"use strict";Dd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Ir=m((mM,Bd)=>{"use strict";var uT=Me(),cT=jt(),lT=di();Bd.exports=uT?function(a,e,t){return cT.f(a,e,lT(1,t))}:function(a,e,t){return a[e]=t,a}});var es=m((bM,Vd)=>{"use strict";var dT=eo(),pT=to(),Od=dT("keys");Vd.exports=function(a){return Od[a]||(Od[a]=pT(a))}});var ts=m((gM,_d)=>{"use strict";_d.exports={}});var po=m((SM,qd)=>{"use strict";var hT=Ol(),Fd=J(),fT=Le(),mT=Ir(),uo=je(),co=ci(),bT=es(),gT=ts(),Nd="Object already initialized",lo=Fd.TypeError,ST=Fd.WeakMap,rs,pi,is,vT=function(a){return is(a)?pi(a):rs(a,{})},yT=function(a){return function(e){var t;if(!fT(e)||(t=pi(e)).type!==a)throw new lo("Incompatible receiver, "+a+" required");return t}};hT||co.state?(Ge=co.state||(co.state=new ST),Ge.get=Ge.get,Ge.has=Ge.has,Ge.set=Ge.set,rs=function(a,e){if(Ge.has(a))throw new lo(Nd);return e.facade=a,Ge.set(a,e),e},pi=function(a){return Ge.get(a)||{}},is=function(a){return Ge.has(a)}):(Gt=bT("state"),gT[Gt]=!0,rs=function(a,e){if(uo(a,Gt))throw new lo(Nd);return e.facade=a,mT(a,Gt,e),e},pi=function(a){return uo(a,Gt)?a[Gt]:{}},is=function(a){return uo(a,Gt)});var Ge,Gt;qd.exports={set:rs,get:pi,has:is,enforce:vT,getterFor:yT}});var ho=m((vM,Gd)=>{"use strict";var TT=ii(),jd=Function.prototype,Ud=jd.apply,Hd=jd.call;Gd.exports=typeof Reflect=="object"&&Reflect.apply||(TT?Hd.bind(Ud):function(){return Hd.apply(Ud,arguments)})});var fo=m((yM,Wd)=>{"use strict";var IT=gr(),ET=fe();Wd.exports=function(a){if(IT(a)==="Function")return ET(a)}});var Kd=m(zd=>{"use strict";var Yd={}.propertyIsEnumerable,Qd=Object.getOwnPropertyDescriptor,xT=Qd&&!Yd.call({1:2},1);zd.f=xT?function(e){var t=Qd(this,e);return!!t&&t.enumerable}:Yd});var Zd=m(Xd=>{"use strict";var AT=Me(),PT=Ae(),wT=Kd(),kT=di(),RT=vr(),$T=io(),LT=je(),MT=Un(),Jd=Object.getOwnPropertyDescriptor;Xd.f=AT?Jd:function(e,t){if(e=RT(e),t=$T(t),MT)try{return Jd(e,t)}catch(r){}if(LT(e,t))return kT(!PT(wT.f,e,t),e[t])}});var mo=m((EM,ep)=>{"use strict";var CT=xe(),DT=K(),BT=/#|\.prototype\./,hi=function(a,e){var t=VT[OT(a)];return t===NT?!0:t===_T?!1:DT(e)?CT(e):!!e},OT=hi.normalize=function(a){return String(a).replace(BT,".").toLowerCase()},VT=hi.data={},_T=hi.NATIVE="N",NT=hi.POLYFILL="P";ep.exports=hi});var fi=m((xM,rp)=>{"use strict";var tp=fo(),FT=st(),qT=ii(),UT=tp(tp.bind);rp.exports=function(a,e){return FT(a),e===void 0?a:qT?UT(a,e):function(){return a.apply(e,arguments)}}});var Ce=m((AM,ap)=>{"use strict";var mi=J(),HT=ho(),jT=fo(),GT=K(),WT=Zd().f,YT=mo(),Er=Ja(),QT=fi(),xr=Ir(),ip=je();ci();var zT=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 HT(a,this,arguments)};return e.prototype=a.prototype,e};ap.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?mi:i?mi[t]:mi[t]&&mi[t].prototype,o=r?Er:Er[t]||xr(Er,t,{})[t],u=o.prototype,c,l,d,p,h,f,b,g,S;for(p in e)c=YT(r?p:t+(i?".":"#")+p,a.forced),l=!c&&n&&ip(n,p),f=o[p],l&&(a.dontCallGetSet?(S=WT(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=QT(h,mi):a.wrap&&l?g=zT(h):s&&GT(h)?g=jT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&xr(g,"sham",!0),xr(o,p,g),s&&(d=t+"Prototype",ip(Er,d)||xr(Er,d,{}),xr(Er[d],p,h),a.real&&u&&(c||!u[p])&&xr(u,p,h)))}});var op=m((PM,np)=>{"use strict";var bo=Me(),KT=je(),sp=Function.prototype,JT=bo&&Object.getOwnPropertyDescriptor,go=KT(sp,"name"),XT=go&&function(){}.name==="something",ZT=go&&(!bo||bo&&JT(sp,"name").configurable);np.exports={EXISTS:go,PROPER:XT,CONFIGURABLE:ZT}});var cp=m((wM,up)=>{"use strict";var eI=Math.ceil,tI=Math.floor;up.exports=Math.trunc||function(e){var t=+e;return(t>0?tI:eI)(t)}});var as=m((kM,lp)=>{"use strict";var rI=cp();lp.exports=function(a){var e=+a;return e!==e||e===0?0:rI(e)}});var pp=m((RM,dp)=>{"use strict";var iI=as(),aI=Math.max,sI=Math.min;dp.exports=function(a,e){var t=iI(a);return t<0?aI(t+e,0):sI(t,e)}});var fp=m(($M,hp)=>{"use strict";var nI=as(),oI=Math.min;hp.exports=function(a){var e=nI(a);return e>0?oI(e,9007199254740991):0}});var ss=m((LM,mp)=>{"use strict";var uI=fp();mp.exports=function(a){return uI(a.length)}});var Sp=m((MM,gp)=>{"use strict";var cI=vr(),lI=pp(),dI=ss(),bp=function(a){return function(e,t,r){var i=cI(e),s=dI(i);if(s===0)return!a&&-1;var n=lI(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}};gp.exports={includes:bp(!0),indexOf:bp(!1)}});var Tp=m((CM,yp)=>{"use strict";var pI=fe(),So=je(),hI=vr(),fI=Sp().indexOf,mI=ts(),vp=pI([].push);yp.exports=function(a,e){var t=hI(a),r=0,i=[],s;for(s in t)!So(mI,s)&&So(t,s)&&vp(i,s);for(;e.length>r;)So(t,s=e[r++])&&(~fI(i,s)||vp(i,s));return i}});var vo=m((DM,Ip)=>{"use strict";Ip.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var xp=m((BM,Ep)=>{"use strict";var bI=Tp(),gI=vo();Ep.exports=Object.keys||function(e){return bI(e,gI)}});var Pp=m(Ap=>{"use strict";var SI=Me(),vI=Hn(),yI=jt(),TI=Ze(),II=vr(),EI=xp();Ap.f=SI&&!vI?Object.defineProperties:function(e,t){TI(e);for(var r=II(t),i=EI(t),s=i.length,n=0,o;s>n;)yI.f(e,o=i[n++],r[o]);return e}});var yo=m((VM,wp)=>{"use strict";var xI=at();wp.exports=xI("document","documentElement")});var xo=m((_M,Dp)=>{"use strict";var AI=Ze(),PI=Pp(),kp=vo(),wI=ts(),kI=yo(),RI=za(),$I=es(),Rp=">",$p="<",Io="prototype",Eo="script",Mp=$I("IE_PROTO"),To=function(){},Cp=function(a){return $p+Eo+Rp+a+$p+"/"+Eo+Rp},Lp=function(a){a.write(Cp("")),a.close();var e=a.parentWindow.Object;return a=null,e},LI=function(){var a=RI("iframe"),e="java"+Eo+":",t;return a.style.display="none",kI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Cp("document.F=Object")),t.close(),t.F},ns,os=function(){try{ns=new ActiveXObject("htmlfile")}catch(e){}os=typeof document!="undefined"?document.domain&&ns?Lp(ns):LI():Lp(ns);for(var a=kp.length;a--;)delete os[Io][kp[a]];return os()};wI[Mp]=!0;Dp.exports=Object.create||function(e,t){var r;return e!==null?(To[Io]=AI(e),r=new To,To[Io]=null,r[Mp]=e):r=os(),t===void 0?r:PI.f(r,t)}});var Op=m((NM,Bp)=>{"use strict";var MI=xe();Bp.exports=!MI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Po=m((FM,_p)=>{"use strict";var CI=je(),DI=K(),BI=li(),OI=es(),VI=Op(),Vp=OI("IE_PROTO"),Ao=Object,_I=Ao.prototype;_p.exports=VI?Ao.getPrototypeOf:function(a){var e=BI(a);if(CI(e,Vp))return e[Vp];var t=e.constructor;return DI(t)&&e instanceof t?t.prototype:e instanceof Ao?_I:null}});var Ar=m((qM,Np)=>{"use strict";var NI=Ir();Np.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:NI(a,e,t),a}});var $o=m((UM,Up)=>{"use strict";var FI=xe(),qI=K(),UI=Le(),HI=xo(),Fp=Po(),jI=Ar(),GI=oe(),WI=He(),Ro=GI("iterator"),qp=!1,nt,wo,ko;[].keys&&(ko=[].keys(),"next"in ko?(wo=Fp(Fp(ko)),wo!==Object.prototype&&(nt=wo)):qp=!0);var YI=!UI(nt)||FI(function(){var a={};return nt[Ro].call(a)!==a});YI?nt={}:WI&&(nt=HI(nt));qI(nt[Ro])||jI(nt,Ro,function(){return this});Up.exports={IteratorPrototype:nt,BUGGY_SAFARI_ITERATORS:qp}});var us=m((HM,jp)=>{"use strict";var QI=oe(),zI=QI("toStringTag"),Hp={};Hp[zI]="z";jp.exports=String(Hp)==="[object z]"});var bi=m((jM,Gp)=>{"use strict";var KI=us(),JI=K(),cs=gr(),XI=oe(),ZI=XI("toStringTag"),eE=Object,tE=cs(function(){return arguments}())==="Arguments",rE=function(a,e){try{return a[e]}catch(t){}};Gp.exports=KI?cs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=rE(e=eE(a),ZI))=="string"?t:tE?cs(e):(r=cs(e))==="Object"&&JI(e.callee)?"Arguments":r}});var Yp=m((GM,Wp)=>{"use strict";var iE=us(),aE=bi();Wp.exports=iE?{}.toString:function(){return"[object "+aE(this)+"]"}});var gi=m((WM,zp)=>{"use strict";var sE=us(),nE=jt().f,oE=Ir(),uE=je(),cE=Yp(),lE=oe(),Qp=lE("toStringTag");zp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(uE(i,Qp)||nE(i,Qp,{configurable:!0,value:e}),r&&!sE&&oE(i,"toString",cE))}});var Jp=m((YM,Kp)=>{"use strict";var dE=$o().IteratorPrototype,pE=xo(),hE=di(),fE=gi(),mE=Ht(),bE=function(){return this};Kp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=pE(dE,{next:hE(+!r,t)}),fE(a,i,!1,!0),mE[i]=bE,a}});var Zp=m((QM,Xp)=>{"use strict";var gE=fe(),SE=st();Xp.exports=function(a,e,t){try{return gE(SE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var th=m((zM,eh)=>{"use strict";var vE=Le();eh.exports=function(a){return vE(a)||a===null}});var ih=m((KM,rh)=>{"use strict";var yE=th(),TE=String,IE=TypeError;rh.exports=function(a){if(yE(a))return a;throw new IE("Can't set "+TE(a)+" as a prototype")}});var Lo=m((JM,ah)=>{"use strict";var EE=Zp(),xE=Le(),AE=ai(),PE=ih();ah.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=EE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return AE(i),PE(s),xE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var mh=m((XM,fh)=>{"use strict";var wE=Ce(),kE=Ae(),ls=He(),ph=op(),RE=K(),$E=Jp(),sh=Po(),nh=Lo(),LE=gi(),ME=Ir(),Mo=Ar(),CE=oe(),oh=Ht(),hh=$o(),DE=ph.PROPER,BE=ph.CONFIGURABLE,uh=hh.IteratorPrototype,ds=hh.BUGGY_SAFARI_ITERATORS,Si=CE("iterator"),ch="keys",vi="values",lh="entries",dh=function(){return this};fh.exports=function(a,e,t,r,i,s,n){$E(t,e,r);var o=function(S){if(S===i&&p)return p;if(!ds&&S&&S in l)return l[S];switch(S){case ch:return function(){return new t(this,S)};case vi:return function(){return new t(this,S)};case lh:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[Si]||l["@@iterator"]||i&&l[i],p=!ds&&d||o(i),h=e==="Array"&&l.entries||d,f,b,g;if(h&&(f=sh(h.call(new a)),f!==Object.prototype&&f.next&&(!ls&&sh(f)!==uh&&(nh?nh(f,uh):RE(f[Si])||Mo(f,Si,dh)),LE(f,u,!0,!0),ls&&(oh[u]=dh))),DE&&i===vi&&d&&d.name!==vi&&(!ls&&BE?ME(l,"name",vi):(c=!0,p=function(){return kE(d,this)})),i)if(b={values:o(vi),keys:s?p:o(ch),entries:o(lh)},n)for(g in b)(ds||c||!(g in l))&&Mo(l,g,b[g]);else wE({target:e,proto:!0,forced:ds||c},b);return(!ls||n)&&l[Si]!==p&&Mo(l,Si,p,{name:i}),oh[e]=p,b}});var gh=m((ZM,bh)=>{"use strict";bh.exports=function(a,e){return{value:a,done:e}}});var Do=m((eC,Ih)=>{"use strict";var OE=vr(),Co=_n(),Sh=Ht(),yh=po(),VE=jt().f,_E=mh(),ps=gh(),NE=He(),FE=Me(),Th="Array Iterator",qE=yh.set,UE=yh.getterFor(Th);Ih.exports=_E(Array,"Array",function(a,e){qE(this,{type:Th,target:OE(a),index:0,kind:e})},function(){var a=UE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ps(void 0,!0);switch(a.kind){case"keys":return ps(t,!1);case"values":return ps(e[t],!1)}return ps([t,e[t]],!1)},"values");var vh=Sh.Arguments=Sh.Array;Co("keys");Co("values");Co("entries");if(!NE&&FE&&vh.name!=="values")try{VE(vh,"name",{value:"values"})}catch(a){}});var xh=m((tC,Eh)=>{"use strict";var HE=oe(),jE=Ht(),GE=HE("iterator"),WE=Array.prototype;Eh.exports=function(a){return a!==void 0&&(jE.Array===a||WE[GE]===a)}});var Bo=m((rC,Ph)=>{"use strict";var YE=bi(),Ah=ui(),QE=Sr(),zE=Ht(),KE=oe(),JE=KE("iterator");Ph.exports=function(a){if(!QE(a))return Ah(a,JE)||Ah(a,"@@iterator")||zE[YE(a)]}});var kh=m((iC,wh)=>{"use strict";var XE=Ae(),ZE=st(),ex=Ze(),tx=oi(),rx=Bo(),ix=TypeError;wh.exports=function(a,e){var t=arguments.length<2?rx(a):e;if(ZE(t))return ex(XE(t,a));throw new ix(tx(a)+" is not iterable")}});var Lh=m((aC,$h)=>{"use strict";var ax=Ae(),Rh=Ze(),sx=ui();$h.exports=function(a,e,t){var r,i;Rh(a);try{if(r=sx(a,"return"),!r){if(e==="throw")throw t;return t}r=ax(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Rh(r),t}});var fs=m((sC,Bh)=>{"use strict";var nx=fi(),ox=Ae(),ux=Ze(),cx=oi(),lx=xh(),dx=ss(),Mh=ni(),px=kh(),hx=Bo(),Ch=Lh(),fx=TypeError,hs=function(a,e){this.stopped=a,this.result=e},Dh=hs.prototype;Bh.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=nx(e,r),c,l,d,p,h,f,b,g=function(T){return c&&Ch(c,"normal",T),new hs(!0,T)},S=function(T){return i?(ux(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=hx(a),!l)throw new fx(cx(a)+" is not iterable");if(lx(l)){for(d=0,p=dx(a);p>d;d++)if(h=S(a[d]),h&&Mh(Dh,h))return h;return new hs(!1)}c=px(a,l)}for(f=s?a.next:c.next;!(b=ox(f,c)).done;){try{h=S(b.value)}catch(T){Ch(c,"throw",T)}if(typeof h=="object"&&h&&Mh(Dh,h))return h}return new hs(!1)}});var Vh=m((nC,Oh)=>{"use strict";var mx=Me(),bx=jt(),gx=di();Oh.exports=function(a,e,t){mx?bx.f(a,e,gx(0,t)):a[e]=t}});var _h=m(()=>{"use strict";var Sx=Ce(),vx=fs(),yx=Vh();Sx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return vx(e,function(r,i){yx(t,r,i)},{AS_ENTRIES:!0}),t}})});var Fh=m((cC,Nh)=>{"use strict";Do();_h();var Tx=Ja();Nh.exports=Tx.Object.fromEntries});var Uh=m((lC,qh)=>{"use strict";qh.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var jh=m(()=>{"use strict";Do();var Ix=Uh(),Ex=J(),xx=gi(),Hh=Ht();for(ms in Ix)xx(Ex[ms],ms),Hh[ms]=Hh.Array;var ms});var Wh=m((hC,Gh)=>{"use strict";var Ax=Fh();jh();Gh.exports=Ax});var Oo=m((fC,Yh)=>{"use strict";var Px=Wh();Yh.exports=Px});var Qh=m(()=>{"use strict"});var Vo=m((gC,zh)=>{"use strict";var yi=J(),wx=yr(),kx=gr(),bs=function(a){return wx.slice(0,a.length)===a};zh.exports=function(){return bs("Bun/")?"BUN":bs("Cloudflare-Workers")?"CLOUDFLARE":bs("Deno/")?"DENO":bs("Node.js/")?"NODE":yi.Bun&&typeof Bun.version=="string"?"BUN":yi.Deno&&typeof Deno.version=="object"?"DENO":kx(yi.process)==="process"?"NODE":yi.window&&yi.document?"BROWSER":"REST"}()});var gs=m((SC,Kh)=>{"use strict";var Rx=Vo();Kh.exports=Rx==="NODE"});var Xh=m((vC,Jh)=>{"use strict";var $x=jt();Jh.exports=function(a,e,t){return $x.f(a,e,t)}});var tf=m((yC,ef)=>{"use strict";var Lx=at(),Mx=Xh(),Cx=oe(),Dx=Me(),Zh=Cx("species");ef.exports=function(a){var e=Lx(a);Dx&&e&&!e[Zh]&&Mx(e,Zh,{configurable:!0,get:function(){return this}})}});var af=m((TC,rf)=>{"use strict";var Bx=ni(),Ox=TypeError;rf.exports=function(a,e){if(Bx(e,a))return a;throw new Ox("Incorrect invocation")}});var No=m((IC,sf)=>{"use strict";var Vx=fe(),_x=K(),_o=ci(),Nx=Vx(Function.toString);_x(_o.inspectSource)||(_o.inspectSource=function(a){return Nx(a)});sf.exports=_o.inspectSource});var df=m((EC,lf)=>{"use strict";var Fx=fe(),qx=xe(),nf=K(),Ux=bi(),Hx=at(),jx=No(),of=function(){},uf=Hx("Reflect","construct"),Fo=/^\s*(?:class|function)\b/,Gx=Fx(Fo.exec),Wx=!Fo.test(of),Ti=function(e){if(!nf(e))return!1;try{return uf(of,[],e),!0}catch(t){return!1}},cf=function(e){if(!nf(e))return!1;switch(Ux(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Wx||!!Gx(Fo,jx(e))}catch(t){return!0}};cf.sham=!0;lf.exports=!uf||qx(function(){var a;return Ti(Ti.call)||!Ti(Object)||!Ti(function(){a=!0})||a})?cf:Ti});var hf=m((xC,pf)=>{"use strict";var Yx=df(),Qx=oi(),zx=TypeError;pf.exports=function(a){if(Yx(a))return a;throw new zx(Qx(a)+" is not a constructor")}});var qo=m((AC,mf)=>{"use strict";var ff=Ze(),Kx=hf(),Jx=Sr(),Xx=oe(),Zx=Xx("species");mf.exports=function(a,e){var t=ff(a).constructor,r;return t===void 0||Jx(r=ff(t)[Zx])?e:Kx(r)}});var gf=m((PC,bf)=>{"use strict";var eA=fe();bf.exports=eA([].slice)});var vf=m((wC,Sf)=>{"use strict";var tA=TypeError;Sf.exports=function(a,e){if(a<e)throw new tA("Not enough arguments");return a}});var Uo=m((kC,yf)=>{"use strict";var rA=yr();yf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(rA)});var Jo=m((RC,Rf)=>{"use strict";var Pe=J(),iA=ho(),aA=fi(),Tf=K(),sA=je(),kf=xe(),If=yo(),nA=gf(),Ef=za(),oA=vf(),uA=Uo(),cA=gs(),Qo=Pe.setImmediate,zo=Pe.clearImmediate,lA=Pe.process,Ho=Pe.Dispatch,dA=Pe.Function,xf=Pe.MessageChannel,pA=Pe.String,jo=0,Ii={},Af="onreadystatechange",Ei,Wt,Go,Wo;kf(function(){Ei=Pe.location});var Ko=function(a){if(sA(Ii,a)){var e=Ii[a];delete Ii[a],e()}},Yo=function(a){return function(){Ko(a)}},Pf=function(a){Ko(a.data)},wf=function(a){Pe.postMessage(pA(a),Ei.protocol+"//"+Ei.host)};(!Qo||!zo)&&(Qo=function(e){oA(arguments.length,1);var t=Tf(e)?e:dA(e),r=nA(arguments,1);return Ii[++jo]=function(){iA(t,void 0,r)},Wt(jo),jo},zo=function(e){delete Ii[e]},cA?Wt=function(a){lA.nextTick(Yo(a))}:Ho&&Ho.now?Wt=function(a){Ho.now(Yo(a))}:xf&&!uA?(Go=new xf,Wo=Go.port2,Go.port1.onmessage=Pf,Wt=aA(Wo.postMessage,Wo)):Pe.addEventListener&&Tf(Pe.postMessage)&&!Pe.importScripts&&Ei&&Ei.protocol!=="file:"&&!kf(wf)?(Wt=wf,Pe.addEventListener("message",Pf,!1)):Af in Ef("script")?Wt=function(a){If.appendChild(Ef("script"))[Af]=function(){If.removeChild(this),Ko(a)}}:Wt=function(a){setTimeout(Yo(a),0)});Rf.exports={set:Qo,clear:zo}});var Mf=m(($C,Lf)=>{"use strict";var $f=J(),hA=Me(),fA=Object.getOwnPropertyDescriptor;Lf.exports=function(a){if(!hA)return $f[a];var e=fA($f,a);return e&&e.value}});var Xo=m((LC,Df)=>{"use strict";var Cf=function(){this.head=null,this.tail=null};Cf.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=Cf});var Of=m((MC,Bf)=>{"use strict";var mA=yr();Bf.exports=/ipad|iphone|ipod/i.test(mA)&&typeof Pebble!="undefined"});var _f=m((CC,Vf)=>{"use strict";var bA=yr();Vf.exports=/web0s(?!.*chrome)/i.test(bA)});var Gf=m((DC,jf)=>{"use strict";var wr=J(),gA=Mf(),Nf=fi(),Zo=Jo().set,SA=Xo(),vA=Uo(),yA=Of(),TA=_f(),eu=gs(),Ff=wr.MutationObserver||wr.WebKitMutationObserver,qf=wr.document,Uf=wr.process,Ss=wr.Promise,iu=gA("queueMicrotask"),Pr,tu,ru,vs,Hf;iu||(xi=new SA,Ai=function(){var a,e;for(eu&&(a=Uf.domain)&&a.exit();e=xi.get();)try{e()}catch(t){throw xi.head&&Pr(),t}a&&a.enter()},!vA&&!eu&&!TA&&Ff&&qf?(tu=!0,ru=qf.createTextNode(""),new Ff(Ai).observe(ru,{characterData:!0}),Pr=function(){ru.data=tu=!tu}):!yA&&Ss&&Ss.resolve?(vs=Ss.resolve(void 0),vs.constructor=Ss,Hf=Nf(vs.then,vs),Pr=function(){Hf(Ai)}):eu?Pr=function(){Uf.nextTick(Ai)}:(Zo=Nf(Zo,wr),Pr=function(){Zo(Ai)}),iu=function(a){xi.head||Pr(),xi.add(a)});var xi,Ai;jf.exports=iu});var Yf=m((BC,Wf)=>{"use strict";Wf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var ys=m((OC,Qf)=>{"use strict";Qf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Yt=m((VC,zf)=>{"use strict";var IA=J();zf.exports=IA.Promise});var kr=m((_C,Zf)=>{"use strict";var EA=J(),Pi=Yt(),xA=K(),AA=mo(),PA=No(),wA=oe(),Kf=Vo(),kA=He(),au=Yn(),Jf=Pi&&Pi.prototype,RA=wA("species"),su=!1,Xf=xA(EA.PromiseRejectionEvent),$A=AA("Promise",function(){var a=PA(Pi),e=a!==String(Pi);if(!e&&au===66||kA&&!(Jf.catch&&Jf.finally))return!0;if(!au||au<51||!/native code/.test(a)){var t=new Pi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[RA]=r,su=t.then(function(){})instanceof r,!su)return!0}return!e&&(Kf==="BROWSER"||Kf==="DENO")&&!Xf});Zf.exports={CONSTRUCTOR:$A,REJECTION_EVENT:Xf,SUBCLASSING:su}});var Rr=m((NC,tm)=>{"use strict";var em=st(),LA=TypeError,MA=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new LA("Bad Promise constructor");e=r,t=i}),this.resolve=em(e),this.reject=em(t)};tm.exports.f=function(a){return new MA(a)}});var ym=m(()=>{"use strict";var CA=Ce(),DA=He(),xs=gs(),xt=J(),Cr=Ae(),rm=Ar(),im=Lo(),BA=gi(),OA=tf(),VA=st(),Es=K(),_A=Le(),NA=af(),FA=qo(),um=Jo().set,lu=Gf(),qA=Yf(),UA=ys(),HA=Xo(),cm=po(),As=Yt(),du=kr(),lm=Rr(),Ps="Promise",dm=du.CONSTRUCTOR,jA=du.REJECTION_EVENT,GA=du.SUBCLASSING,nu=cm.getterFor(Ps),WA=cm.set,$r=As&&As.prototype,Qt=As,Ts=$r,pm=xt.TypeError,ou=xt.document,pu=xt.process,uu=lm.f,YA=uu,QA=!!(ou&&ou.createEvent&&xt.dispatchEvent),hm="unhandledrejection",zA="rejectionhandled",am=0,fm=1,KA=2,hu=1,mm=2,Is,sm,JA,nm,bm=function(a){var e;return _A(a)&&Es(e=a.then)?e:!1},gm=function(a,e){var t=e.value,r=e.state===fm,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{i?(r||(e.rejection===mm&&ZA(e),e.rejection=hu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),l=!0)),u===a.promise?n(new pm("Promise-chain cycle")):(c=bm(u))?Cr(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},Sm=function(a,e){a.notified||(a.notified=!0,lu(function(){for(var t=a.reactions,r;r=t.get();)gm(r,a);a.notified=!1,e&&!a.rejection&&XA(a)}))},vm=function(a,e,t){var r,i;QA?(r=ou.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),xt.dispatchEvent(r)):r={promise:e,reason:t},!jA&&(i=xt["on"+a])?i(r):a===hm&&qA("Unhandled promise rejection",t)},XA=function(a){Cr(um,xt,function(){var e=a.facade,t=a.value,r=om(a),i;if(r&&(i=UA(function(){xs?pu.emit("unhandledRejection",t,e):vm(hm,e,t)}),a.rejection=xs||om(a)?mm:hu,i.error))throw i.value})},om=function(a){return a.rejection!==hu&&!a.parent},ZA=function(a){Cr(um,xt,function(){var e=a.facade;xs?pu.emit("rejectionHandled",e):vm(zA,e,a.value)})},Lr=function(a,e,t){return function(r){a(e,r,t)}},Mr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=KA,Sm(a,!0))},cu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new pm("Promise can't be resolved itself");var r=bm(e);r?lu(function(){var i={done:!1};try{Cr(r,e,Lr(cu,i,a),Lr(Mr,i,a))}catch(s){Mr(i,s,a)}}):(a.value=e,a.state=fm,Sm(a,!1))}catch(i){Mr({done:!1},i,a)}}};if(dm&&(Qt=function(e){NA(this,Ts),VA(e),Cr(Is,this);var t=nu(this);try{e(Lr(cu,t),Lr(Mr,t))}catch(r){Mr(t,r)}},Ts=Qt.prototype,Is=function(e){WA(this,{type:Ps,done:!1,notified:!1,parent:!1,reactions:new HA,rejection:!1,state:am,value:void 0})},Is.prototype=rm(Ts,"then",function(e,t){var r=nu(this),i=uu(FA(this,Qt));return r.parent=!0,i.ok=Es(e)?e:!0,i.fail=Es(t)&&t,i.domain=xs?pu.domain:void 0,r.state===am?r.reactions.add(i):lu(function(){gm(i,r)}),i.promise}),sm=function(){var a=new Is,e=nu(a);this.promise=a,this.resolve=Lr(cu,e),this.reject=Lr(Mr,e)},lm.f=uu=function(a){return a===Qt||a===JA?new sm(a):YA(a)},!DA&&Es(As)&&$r!==Object.prototype)){nm=$r.then,GA||rm($r,"then",function(e,t){var r=this;return new Qt(function(i,s){Cr(nm,r,i,s)}).then(e,t)},{unsafe:!0});try{delete $r.constructor}catch(a){}im&&im($r,Ts)}CA({global:!0,constructor:!0,wrap:!0,forced:dm},{Promise:Qt});BA(Qt,Ps,!1,!0);OA(Ps)});var Am=m((UC,xm)=>{"use strict";var eP=oe(),Im=eP("iterator"),Em=!1;try{Tm=0,fu={next:function(){return{done:!!Tm++}},return:function(){Em=!0}},fu[Im]=function(){return this},Array.from(fu,function(){throw 2})}catch(a){}var Tm,fu;xm.exports=function(a,e){try{if(!e&&!Em)return!1}catch(i){return!1}var t=!1;try{var r={};r[Im]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var mu=m((HC,Pm)=>{"use strict";var tP=Yt(),rP=Am(),iP=kr().CONSTRUCTOR;Pm.exports=iP||!rP(function(a){tP.all(a).then(void 0,function(){})})});var wm=m(()=>{"use strict";var aP=Ce(),sP=Ae(),nP=st(),oP=Rr(),uP=ys(),cP=fs(),lP=mu();aP({target:"Promise",stat:!0,forced:lP},{all:function(e){var t=this,r=oP.f(t),i=r.resolve,s=r.reject,n=uP(function(){var o=nP(t.resolve),u=[],c=0,l=1;cP(e,function(d){var p=c++,h=!1;l++,sP(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 Rm=m(()=>{"use strict";var dP=Ce(),pP=He(),hP=kr().CONSTRUCTOR,gu=Yt(),fP=at(),mP=K(),bP=Ar(),km=gu&&gu.prototype;dP({target:"Promise",proto:!0,forced:hP,real:!0},{catch:function(a){return this.then(void 0,a)}});!pP&&mP(gu)&&(bu=fP("Promise").prototype.catch,km.catch!==bu&&bP(km,"catch",bu,{unsafe:!0}));var bu});var $m=m(()=>{"use strict";var gP=Ce(),SP=Ae(),vP=st(),yP=Rr(),TP=ys(),IP=fs(),EP=mu();gP({target:"Promise",stat:!0,forced:EP},{race:function(e){var t=this,r=yP.f(t),i=r.reject,s=TP(function(){var n=vP(t.resolve);IP(e,function(o){SP(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Lm=m(()=>{"use strict";var xP=Ce(),AP=Rr(),PP=kr().CONSTRUCTOR;xP({target:"Promise",stat:!0,forced:PP},{reject:function(e){var t=AP.f(this),r=t.reject;return r(e),t.promise}})});var Su=m((XC,Mm)=>{"use strict";var wP=Ze(),kP=Le(),RP=Rr();Mm.exports=function(a,e){if(wP(a),kP(e)&&e.constructor===a)return e;var t=RP.f(a),r=t.resolve;return r(e),t.promise}});var Bm=m(()=>{"use strict";var $P=Ce(),LP=at(),Cm=He(),MP=Yt(),Dm=kr().CONSTRUCTOR,CP=Su(),DP=LP("Promise"),BP=Cm&&!Dm;$P({target:"Promise",stat:!0,forced:Cm||Dm},{resolve:function(e){return CP(BP&&this===DP?MP:this,e)}})});var Om=m(()=>{"use strict";ym();wm();Rm();$m();Lm();Bm()});var Fm=m(()=>{"use strict";var OP=Ce(),VP=He(),ws=Yt(),_P=xe(),_m=at(),Nm=K(),NP=qo(),Vm=Su(),FP=Ar(),yu=ws&&ws.prototype,qP=!!ws&&_P(function(){yu.finally.call({then:function(){}},function(){})});OP({target:"Promise",proto:!0,real:!0,forced:qP},{finally:function(a){var e=NP(this,_m("Promise")),t=Nm(a);return this.then(t?function(r){return Vm(e,a()).then(function(){return r})}:a,t?function(r){return Vm(e,a()).then(function(){throw r})}:a)}});!VP&&Nm(ws)&&(vu=_m("Promise").prototype.finally,yu.finally!==vu&&FP(yu,"finally",vu,{unsafe:!0}));var vu});var ks=m((sD,qm)=>{"use strict";var UP=at();qm.exports=UP});var Hm=m((nD,Um)=>{"use strict";Qh();Om();Fm();var HP=ks();Um.exports=HP("Promise","finally")});var Gm=m((oD,jm)=>{"use strict";var jP=Hm();jm.exports=jP});var Rs=m((uD,Wm)=>{"use strict";var GP=Gm();Wm.exports=GP});var gb=m(()=>{"use strict";var yw=Ce(),Tw=li(),Iw=ss(),Ew=as(),xw=_n();yw({target:"Array",proto:!0},{at:function(e){var t=Tw(this),r=Iw(t),i=Ew(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});xw("at")});var vb=m((g0,Sb)=>{"use strict";gb();var Aw=ks();Sb.exports=Aw("Array","at")});var Tb=m((S0,yb)=>{"use strict";var Pw=vb();yb.exports=Pw});var $i=m((v0,Ib)=>{"use strict";var ww=Tb();Ib.exports=ww});var wg=m(()=>{"use strict"});var kg=m(()=>{"use strict"});var $g=m((P_,Rg)=>{"use strict";var Ck=Le(),Dk=gr(),Bk=oe(),Ok=Bk("match");Rg.exports=function(a){var e;return Ck(a)&&((e=a[Ok])!==void 0?!!e:Dk(a)==="RegExp")}});var Mg=m((w_,Lg)=>{"use strict";var Vk=bi(),_k=String;Lg.exports=function(a){if(Vk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return _k(a)}});var Dg=m((k_,Cg)=>{"use strict";var Nk=Ze();Cg.exports=function(){var a=Nk(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 Vg=m((R_,Og)=>{"use strict";var Fk=Ae(),qk=je(),Uk=ni(),Hk=Dg(),Bg=RegExp.prototype;Og.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Bg)&&!qk(a,"flags")&&Uk(Bg,a)?Fk(Hk,a):e}});var Ng=m(($_,_g)=>{"use strict";var Ku=fe(),jk=li(),Gk=Math.floor,Qu=Ku("".charAt),Wk=Ku("".replace),zu=Ku("".slice),Yk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Qk=/\$([$&'`]|\d{1,2})/g;_g.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=Qk;return i!==void 0&&(i=jk(i),u=Yk),Wk(s,u,function(c,l){var d;switch(Qu(l,0)){case"$":return"$";case"&":return a;case"`":return zu(e,0,t);case"'":return zu(e,n);case"<":d=i[zu(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=Gk(p/10);return h===0?c:h<=o?r[h-1]===void 0?Qu(l,1):r[h-1]+Qu(l,1):c}d=r[p-1]}return d===void 0?"":d})}});var Ug=m(()=>{"use strict";var zk=Ce(),Kk=Ae(),Xu=fe(),Fg=ai(),Jk=K(),Xk=Sr(),Zk=$g(),Hr=Mg(),eR=ui(),tR=Vg(),rR=Ng(),iR=oe(),aR=He(),sR=iR("replace"),nR=TypeError,Ju=Xu("".indexOf),oR=Xu("".replace),qg=Xu("".slice),uR=Math.max;zk({target:"String",proto:!0},{replaceAll:function(e,t){var r=Fg(this),i,s,n,o,u,c,l,d,p,h,f=0,b="";if(!Xk(e)){if(i=Zk(e),i&&(s=Hr(Fg(tR(e))),!~Ju(s,"g")))throw new nR("`.replaceAll` does not allow non-global regexes");if(n=eR(e,sR),n)return Kk(n,e,r,t);if(aR&&i)return oR(Hr(r),e,t)}for(o=Hr(r),u=Hr(e),c=Jk(t),c||(t=Hr(t)),l=u.length,d=uR(1,l),p=Ju(o,u);p!==-1;)h=c?Hr(t(u,p,o)):rR(u,o,p,[],void 0,t),b+=qg(o,f,p)+h,f=p+l,p=p+d>o.length?-1:Ju(o,u,p+d);return f<o.length&&(b+=qg(o,f)),b}})});var jg=m((C_,Hg)=>{"use strict";wg();kg();Ug();var cR=ks();Hg.exports=cR("String","replaceAll")});var Wg=m((D_,Gg)=>{"use strict";var lR=jg();Gg.exports=lR});var Qg=m((B_,Yg)=>{"use strict";var dR=Wg();Yg.exports=dR});var dl="2.0.108-dev.9969cb23.0";var he=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(he||{}),Et=(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))(Et||{});var Wa=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Wa||{}),Mn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Mn||{});var Cn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Cn||{});import{assertNever as gl,assertNonNullable as Lv,isNonNullable as Ya,ValueSubject as Dn,Subject as Mv,Subscription as Cv,merge as Dv,observableFrom as Bv,fromEvent as hl,map as fl,tap as ml,filterChanged as Ov,isNullable as Bn,ErrorCategory as bl}from"@vkontakte/videoplayer-shared";var pl=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 Qa=class{constructor(e){this.connection$=new Dn(void 0);this.castState$=new Dn("NOT_AVAILABLE");this.errorEvent$=new Mv;this.realCastState$=new Dn("NOT_AVAILABLE");this.subscription=new Cv;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=Ya((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||pl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:bl.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(){Ya(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Bn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Bn(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(hl(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 gl(i.sessionState)}})).add(Dv(hl(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ml(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),fl(i=>i.castState)),Bv([r.getCastState()])).pipe(Ov(),fl(Vv),ml(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Ya(this.connection$.getValue());if(s&&!n){let c=r.getCurrentSession();Lv(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Bn(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"?Ya(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:bl.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Vv=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 gl(a)}};var jS=Xe(Oo(),1);var rb=Xe(Rs(),1);import{assertNever as Ym}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:Ym(t)}return a},Tu=(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:Ym(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as WP,Subject as $s,merge as Qm}from"@vkontakte/videoplayer-shared";var C=class{constructor(e){this.transitionStarted$=new $s;this.transitionEnded$=new $s;this.transitionUpdated$=new $s;this.forceChanged$=new $s;this.stateChangeStarted$=Qm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Qm(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||WP(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 YP}from"@vkontakte/videoplayer-shared";var zm=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return YP(a)}};import{assertNever as Dr,assertNonNullable as zt,debounce as Km,ErrorCategory as Jm,fromEvent as Kt,isNonNullable as Xm,map as Zm,merge as eb,observableFrom as QP,Subject as zP,Subscription as Iu,timeout as KP,getHighestQuality as JP}from"@vkontakte/videoplayer-shared";var XP=5,ZP=5,ew=500,tb=7e3,wi=class{constructor(e){this.subscription=new Iu;this.loadMediaTimeoutSubscription=new Iu;this.videoState=new C("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:Dr(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:Dr(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:Dr(e)}break}default:Dr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(zm(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Iu;this.subscription.add(e),this.subscription.add(eb(this.videoState.stateChangeStarted$.pipe(Zm(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Zm(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 zP;e.add(i.pipe(Km(ew)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Kt(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)>XP)&&i.next(o),s=o})),e.add(Kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Kt(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<ZP&&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:Dr(n)}}),t(Kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=eb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,QP(["init"])).pipe(Km(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];zt(l);let d=JP(Object.keys(l));zt(d);let p=l[d];zt(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];zt(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];zt(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];zt(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];zt(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:Jm.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Dr(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 Xm(o)&&(n.metadata.title=o),Xm(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(KP(tb).subscribe(()=>s(`timeout(${tb})`)))});(0,rb.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Jm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as ab}from"@vkontakte/videoplayer-shared";import{clearVideoElement as tw}from"@vkontakte/videoplayer-shared";var ib=a=>{try{a.pause(),a.playbackRate=0,tw(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as rw,Subscription as iw}from"@vkontakte/videoplayer-shared";var Eu=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},xu=window.WeakMap?new WeakMap:new Eu,Au=window.WeakMap?new WeakMap:new Map,aw=(a,e=20)=>{let t=0;return rw(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},me=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?ab(t):(t=document.createElement("video"),a.appendChild(t)),xu.set(t,r);let i=new iw;return i.add(aw(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},be=a=>{let e=Au.get(a);e==null||e.unsubscribe(),Au.delete(a);let t=xu.get(a);xu.delete(a),t?ab(a):ib(a)};import{assertNonNullable as ki,isNonNullable as tt,isNullable as ow,fromEvent as Br,merge as sb,observableFrom as nb,filterChanged as ob,map as Ri,Subject as ub,Subscription as uw,ValueSubject as cw,ErrorCategory as lw}from"@vkontakte/videoplayer-shared";import{isNonNullable as Pu,isNullable as sw,Subscription as nw}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=sw(i),c=new nw;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},et=(a,e,t)=>Ls(e,()=>a.loop,r=>{Pu(r)&&(a.loop=r)},{onError:t}),ge=(a,e,t,r)=>Ls(e,()=>({muted:a.muted,volume:a.volume}),i=>{Pu(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}),De=(a,e,t,r)=>Ls(e,()=>a.playbackRate,i=>{Pu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),At=Ls;var dw=a=>["__",a.language,a.label].join("|"),pw=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},wu=class a{constructor(){this.available$=new ub;this.current$=new cw(void 0);this.error$=new ub;this.subscription=new uw;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:lw.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(At(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{tt(s)&&this.setInternal(s)},{equal:(s,n)=>tt(s)&&tt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ri(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(At(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{tt(s)&&this.setExternal(s)},{equal:(s,n)=>tt(s)&&tt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ri(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(At(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(At(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ki(this.video);let{textTracks:e}=this.video;this.subscription.add(Br(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(sb(Br(e,"addtrack"),Br(e,"removetrack"),nb(["init"])).pipe(Ri(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),ob((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(sb(Br(e,"change"),nb(["init"])).pipe(Ri(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ri(r=>r&&this.htmlTextTrackToITextTrack(r).id),ob()).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(Br(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(Br(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;tt(t.align)&&(i.align=t.align),tt(t.position)&&(i.position=t.position),tt(t.size)&&(i.size=t.size),tt(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){ki(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:dw(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){ki(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(ow(e)||!pw(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){ki(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){ki(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)}},Be=wu;var ut=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 cb=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},ku=a=>{let e=cb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},lb=a=>{let e=cb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Oe,map as Pt,merge as pb,filterChanged as fw,isNonNullable as hb,Subject as mw,filter as fb,mapTo as mb,combine as bw,once as gw,ErrorCategory as Sw,ValueSubject as bb,clientChecker as vw}from"@vkontakte/videoplayer-shared";var hw=3,db=(a,e,t=hw)=>{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 Se=a=>{let e=v=>Oe(a,v).pipe(mb(void 0)),r=pb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>Oe(a,v))).pipe(Pt(v=>v.type==="ended"?a.readyState<2:a.readyState<3),fw()),i=pb(Oe(a,"progress"),Oe(a,"timeupdate")).pipe(Pt(()=>db(a.buffered,a.currentTime))),s=vw.isSafari?bw({play:e("play").pipe(gw()),playing:e("playing")}).pipe(mb(void 0)):e("playing"),n=Oe(a,"volumechange").pipe(Pt(()=>({muted:a.muted,volume:a.volume}))),o=Oe(a,"ratechange").pipe(Pt(()=>a.playbackRate)),u=Oe(a,"error").pipe(fb(()=>!!(a.error||a.played.length)),Pt(()=>{var y;let v=a.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:Sw.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(y=a.error)!=null?y:void 0}})),c=Oe(a,"timeupdate").pipe(Pt(()=>a.currentTime)),l=new mw,d=.3,p;c.subscribe(v=>{a.loop&&hb(p)&&hb(v)&&p>=a.duration-d&&v<=d&&l.next(p),p=v});let h=e("pause").pipe(fb(()=>!a.error&&p!==a.duration)),f=Oe(a,"enterpictureinpicture"),b=Oe(a,"leavepictureinpicture"),g=new bb(lb(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new bb(ku(a));return Oe(a,"fullscreenchange").pipe(Pt(()=>ku(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$:Oe(a,"durationchange").pipe(Pt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S}};import{VideoQuality as wt}from"@vkontakte/videoplayer-shared";var kt=a=>{switch(a){case"mobile":return wt.Q_144P;case"lowest":return wt.Q_240P;case"low":return wt.Q_360P;case"sd":case"medium":return wt.Q_480P;case"hd":case"high":return wt.Q_720P;case"fullhd":case"full":return wt.Q_1080P;case"quadhd":case"quad":return wt.Q_1440P;case"ultrahd":case"ultra":return wt.Q_2160P}};var Jt=Xe($i(),1);import{isNonNullable as ve,isNullable as $u,now as $b,isHigher as Lu,isHigherOrEqual as Pb,isInvariantQuality as wb,isLower as Mu,isLowerOrEqual as kb,videoSizeToQuality as kw,assertNotEmptyArray as Lb,assertNonNullable as Rw}from"@vkontakte/videoplayer-shared";var Ru=!1,ct={},Eb=a=>{Ru=a},xb=()=>{ct={}},Ab=a=>{a(ct)},Li=(a,e)=>{var t;Ru&&(ct.meta=(t=ct.meta)!=null?t:{},ct.meta[a]=e)},ue=class{constructor(e){this.name=e}next(e){var r,i;if(!Ru)return;ct.series=(r=ct.series)!=null?r:{};let t=(i=ct.series[this.name])!=null?i:[];t.push([Date.now(),e]),ct.series[this.name]=t}};var $w=new ue("best_bitrate"),Mb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Cu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Mi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=$b()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Cb='Assertion "ABR Tracks is empty array" failed',Ms=(a,e,t,r)=>{var u;let i=[...e].sort(Cu(1)),s=[...t].sort(Cu(1)),n=s.filter(c=>ve(c.bitrate)&&ve(a.bitrate)?a.bitrate/c.bitrate>r:!0),o=(u=(0,Jt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Jt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Jt.default)(n,-1):(0,Jt.default)(s,0)},Rb=a=>"quality"in a,Db=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&$b()-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=Rb(s)?"video":"audio",o=Rb(s)?s.quality:s.bitrate;return e({message:`
7
+ [last ${n} selected] ${o}
8
+ `}),s}return r==null||r.recordSwitch(t),t},Rt=(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,_;Lb(a,Cb);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&&kw(f),g=r.considerPlaybackRate&&ve(o)?o:1,S=a.filter(k=>!wb(k.quality)).sort((k,x)=>Lu(k.quality,x.quality)?-1:1),T=(N=(0,Jt.default)(S,-1))==null?void 0:N.quality,v=(L=(0,Jt.default)(S,0))==null?void 0:L.quality,y=$u(i)||ve(i.min)&&ve(i.max)&&Mu(i.max,i.min)||ve(i.min)&&v&&Lu(i.min,v)||ve(i.max)&&T&&Mu(i.max,T),I=g*Mb(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),$={},V=S.filter(k=>{if(!(b?Mu(k.quality,b):!0))return $[k.quality]="FitsContainer",!1;if(!(ve(t)&&isFinite(t)&&ve(k.bitrate)?t-s>=k.bitrate*I:!0))return $[k.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&ve(r.minBufferToSwitchUp)&&u&&!wb(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Lu(k.quality,u.quality))return $[k.quality]="Buffer",!1;if(!!d&&Pb(k.quality,d))return $[k.quality]="DroppedFramesLimit",!1;let Z=y||($u(i.max)||kb(k.quality,i.max))&&($u(i.min)||Pb(k.quality,i.min)),le=ve(l)&&!l?kb(k.quality,r.backgroundVideoQualityLimit):!0;return!Z||!le?($[k.quality]="FitsQualityLimits",!1):!0})[0];V&&V.bitrate&&$w.next(V.bitrate);let D=(F=V!=null?V:S[Math.ceil((S.length-1)/2)])!=null?F:a[0];return D.quality!==((_=c==null?void 0:c.last)==null?void 0:_.quality)&&p({message:`
9
+ [VIDEO TRACKS ABR]
10
+ [available video tracks]
11
+ ${a.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
9
12
  `)}
10
13
 
11
14
  [tuning]
12
- ${Object.entries(r!=null?r:{}).map(([P,x])=>`${P}: ${x}`).join(`
15
+ ${Object.entries(r!=null?r:{}).map(([k,x])=>`${k}: ${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: ${y},
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(T).map(([P,x])=>`${P}: ${x}`).join(`
32
+ [limited video tracks]
33
+ ${Object.entries($).map(([k,x])=>`${k}: ${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 V=$&&l&&l.history[$.id]&&rb()-l.history[$.id]<=r.trackCooldown&&(!l.last||$.id!==l.last.id);if($!=null&&$.id&&l&&!V&&l.recordSelection($),V&&(l!=null&&l.last)){let P=l.last;return l==null||l.recordSwitch(P),d({message:`
36
- [last selected] ${P==null?void 0:P.quality}
37
- `}),P}return l==null||l.recordSwitch($),$},yt=fw;var ie=a=>new URL(a).hostname;import{assertNever as ub,assertNonNullable as lb,combine as Dw,debounce as Ow,ErrorCategory as cb,filter as db,filterChanged as Bw,isNonNullable as Tu,map as fs,merge as pb,observableFrom as Vw,once as _w,Subscription as Nw,ValueSubject as Iu,videoQualityToHeight as Fw,videoSizeToQuality as qw}from"@vkontakte/videoplayer-shared";var ib=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"))},Se=a=>k(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!ib(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return ib(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as ds,isNullable as gw,assertNonNullable as Ti}from"@vkontakte/videoplayer-shared";import{isNonNullable as ab,assertNonNullable as cs,now as mw}from"@vkontakte/videoplayer-shared";function ae(){return mw()}function gu(a){return ae()-a}function Su(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 sb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function xr(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,g=()=>{if(u)return;cs(c);let R=gu(c),F;if(R<b){F=b-R,setTimeout(g,F);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,M()},S=R=>(s=R,N),I=R=>(d=R,N),v=()=>(h="json",N),y=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},T=R=>(p=R,N),M=()=>{c=ae(),n=new i,n.open("get",a);let R=0,F,_=0,P=()=>(cs(c),Math.max(c,Math.max(F||0,_||0)));if(s&&n.addEventListener("progress",x=>{let D=ae();s.updateChunk&&x.loaded>R&&(s.updateChunk(P(),x.loaded-R),R=x.loaded,F=D)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;cs(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let D=n.response.byteLength-R;D&&s.updateChunk&&s.updateChunk(P(),D)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),p){let x=()=>{cs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(_=ae(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),N},N={withBitrateReporting:S,withParallel:T,withJSONResponse:v,withRetryCount:R=>(l=R,N),withRetryInterval:(R,F)=>(ab(R)&&(b=R),ab(F)&&(f=F),N),withTimeout:R=>(o=R,N),withFinally:I,send:M,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return N}var vi=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 yi=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=ae(),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=ae()-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=xr(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=ae()}_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=ae();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 ps=1e4,vu=3;var Sw=6e4,vw=10,yw=1,Tw=500,Ii=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 vi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Su(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=Su(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||ds(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=()=>{sb(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 yi(vu,ps,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 y=s&&(!c||c===this.rep);return y||t("Not running!"),y},p=(y,T,M)=>{u&&u.abort(),u=xr(this.urlResolver.resolve(y,!1),T,M,()=>this._retryCallback()).withTimeout(ps).withBitrateReporting(this.bitrateSwitcher).withRetryCount(vu).withFinally(()=>{u=null}).send()},h=(y,T,M)=>{Ti(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),T,M,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=y=>{let T=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${T}=>${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 M=ae()-1e4,C=0;for(let V=0;V<this.bufferStates.length;V++){let G=this.bufferStates[V];y=Math.min(y,G.buf),G.ts<M&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${y} drop=${C} jitter=${this.sourceJitter}`);let $=y-yw;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?f(1.15):$>1?f(1.1):$>.3?f(1.05):f(1)}},S=y=>{let T,M=()=>T&&T.start?T.start.length:0,C=x=>T.start[x]/1e3,$=x=>T.dur[x]/1e3,V=x=>T.fragIndex+x,G=(x,D)=>({chunkIdx:V(x),startTS:C(x),dur:$(x),discontinuity:D}),N=()=>{let x=0;if(T&&T.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,z=D;this.sourceJitter>1&&(z+=this.sourceJitter-1);let ee=T.dur.length-1;for(;ee>=0&&(z-=T.dur[ee],!(z<=0));--ee);x=Math.min(ee,T.dur.length-1-Y),x=Math.max(x,0)}return G(x,!0)},R=x=>{let D=M();if(!(D<=0)){if(ds(x)){for(let Y=0;Y<D;Y++)if(C(Y)>x)return G(Y)}return N()}},F=x=>{let D=M(),Y=x?x.chunkIdx+1:0,z=Y-T.fragIndex;if(!(D<=0)){if(!x||z<0||z-D>vw)return t(`Resync: offset=${z} bChunks=${D} chunk=`+JSON.stringify(x)),N();if(!(z>=D))return G(Y-T.fragIndex,!1)}},_=(x,D,Y)=>{l&&l.abort(),l=xr(this.urlResolver.resolve(x,!0,this.lowLatency),D,Y,()=>this._retryCallback()).withTimeout(ps).withRetryCount(vu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(x,D)=>{_(y,Y=>{if(!d())return;T=Y;let z=!!T.lowLatency;z!==this.lowLatency&&b(z);let ee=0;for(let H=0;H<T.dur.length;++H)ee+=T.dur[H];ee>0&&(Ti(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ee/T.dur.length)),i({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,x(R(D))},()=>this._handleNetworkError())},nextChunk:F}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ti(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:T,logger:M}=this.params,C=S(e.jidxUrl),$,V,G,N,R=0,F,_,P,x=()=>{F&&(clearTimeout(F),F=void 0);let q=Math.max(Tw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ce=R+q,Te=ae(),we=Math.min(1e4,ce-Te);R=Te;let ct=()=>{l||d()&&C.seek(()=>{d()&&(R=ae(),D(),x())})};we>0?F=window.setTimeout(()=>{this.paused?x():ct()},we):ct()},D=()=>{let q;for(;q=C.nextChunk(N);)N=q,Zt(q);let ce=C.nextChunk(G);if(ce){if(G&&ce.discontinuity){M("Detected discontinuity; restarting playback"),this.paused?x():(I(),this._initPlayerWith(e));return}H(ce)}else x()},Y=(q,ce)=>{if(!d()||!this.sourceBuffer)return;let Te,we,ct,er=dt=>{window.setTimeout(()=>{d()&&Y(q,ce)},dt)};if(this.sourceBuffer.updating)M("Source buffer is updating; delaying appendBuffer"),er(100);else{let dt=ae(),wt=T.currentTime;!this.paused&&T.buffered.length>1&&_===wt&&dt-P>500&&(M("Stall suspected; trying to fix"),this._fixupStall()),_!==wt&&(_=wt,P=dt);let tr=this._getBufferSizeSec();if(tr>30)M(`Buffered ${tr} seconds; delaying appendBuffer`),er(2e3);else try{this.sourceBuffer.appendBuffer(q),this.videoPlayStarted?(this.bufferStates.push({ts:dt,buf:tr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ce&&ce()}catch(Nr){if(Nr.name==="QuotaExceededError")M("QuotaExceededError; delaying appendBuffer"),ct=this.sourceBuffer.buffered.length,ct!==0&&(Te=this.sourceBuffer.buffered.start(0),we=wt,we-Te>4&&this.sourceBuffer.remove(Te,we-3)),er(1e3);else throw Nr}}},z=()=>{V&&$&&(M([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(G)]),Y(V,function(){V=null,D()}))},ee=q=>e.fragUrlTemplate.replace("%%id%%",q.chunkIdx),H=q=>{d()&&h(ee(q),(ce,Te)=>{if(d()){if(Te/=1e3,V=ce,G=q,n=q.startTS,Te){let we=Math.min(10,q.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}z()}},()=>this._handleNetworkError())},Zt=q=>{d()&&(Ti(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ee(q),!1)))},lt=q=>{d()&&(e.cachedHeader=q,Y(q,()=>{$=!0,z()}))};s=!0,C.seek(q=>{if(d()){if(R=ae(),!q){x();return}N=q,!gw(y)||q.startTS>y?H(q):(G=q,D())}},y),e.cachedHeader?lt(e.cachedHeader):p(e.headerUrl,lt,()=>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(),ds(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,Ti(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return ds(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=ae();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,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&gu(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=ae();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=xr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ps).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;Se(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))},Sw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Iw,filter as nb,fromEvent as Ew,interval as xw,isHigher as Pw,isInvariantQuality as Aw,isLower as ww,merge as kw,Subject as ob,Subscription as Rw}from"@vkontakte/videoplayer-shared";var yu=class{constructor(){this.onDroopedVideoFramesLimit$=new ob;this.subscription=new Rw;this.playing=!1;this.tracks=[];this.forceChecker$=new ob;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&&!Aw(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&&Pw(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(Ew(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=xw(this.droppedFramesChecker.checkTime).pipe(nb(()=>this.playing),nb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(Iw(this.droppedFramesChecker.checkTime)),r=kw(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])=>ww(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}},hs=yu;import{map as $w,Observable as Lw}from"@vkontakte/videoplayer-shared";import{fromEvent as Mw}from"@vkontakte/videoplayer-shared";var Ei=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Cw=(a,e)=>new Lw(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ei()))},w(w({},r),e));i.observe(a);let s=Mw(document,"visibilitychange").pipe($w(n=>!document.hidden||Ei())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),De=Cw;var Uw=["paused","playing","ready"],Hw=["paused","playing","ready"],xi=class{constructor(e){this.subscription=new Nw;this.videoState=new L("stopped");this.representations$=new Iu([]);this.textTracksManager=new Me;this.droppedFramesManager=new hs;this.maxSeekBackTime$=new Iu(1/0);this.zeroTime$=new Iu(void 0);this.liveOffset=new tt;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:cb.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:qw(u.video),d=u.bitrate/1e3,p=w({},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),Tu(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(Hw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Uw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(se(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(se(this.params.source.url,u))}return;default:return ub(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:cb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};pb(this.videoState.stateChangeStarted$.pipe(fs(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(fs(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(ie(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(fs(i=>i.map(({track:s})=>s)),db(i=>!!i.length),_w()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Bw(),fs(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Dw({zeroTime:this.zeroTime$.pipe(db(Tu)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(Qe(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(Le(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(De(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&Fw(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 ub(i.to)}},t)).add(pb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Vw(["init"])).pipe(Ow(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 Ii({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&&Tu(t)?t:yt(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;lb(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;lb(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(se(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var hb=xi;var it=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as hR,assertNonNullable as fR,debounce as mR,ErrorCategory as zu,filter as Fg,filterChanged as Ku,fromEvent as bR,isLowerOrEqual as qg,isNonNullable as gR,isInvariantQuality as SR,map as Ug,merge as Ns,observableFrom as vR,observeElementSize as yR,once as Hg,Subscription as TR,ValueSubject as IR}from"@vkontakte/videoplayer-shared";var ms=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}},Pr=class extends ms{constructor(){super(),this.listeners||ms.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)}},Pi=class{constructor(){Object.defineProperty(this,"signal",{value:new Pr,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&&(Pi.prototype[Symbol.toStringTag]="AbortController",Pr.prototype[Symbol.toStringTag]="AbortSignal");function bs(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 Eu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!bs({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 Ai=bs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),fb=Ai?Eu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,at=Ai?fb.fetch:window.fetch,AO=Ai?fb.Request:window.Request,st=Ai?Pi:window.AbortController,wO=Ai?Pr:window.AbortSignal;var wb=We(gi(),1);var nt=()=>window.ManagedMediaSource||window.MediaSource,gs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},mb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},bb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as As,clientChecker as Ps}from"@vkontakte/videoplayer-shared";var Oe=document.createElement("video"),Ww='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Yw='video/mp4; codecs="hev1.1.6.L93.B0"',kb='video/webm; codecs="vp09.00.10.08"',Rb='video/webm; codecs="av01.0.00M.08"',Qw='audio/mp4; codecs="mp4a.40.2"',zw='audio/webm; codecs="opus"',gb,Sb,qt={mms:gs(),mse:mb(),hls:!!((gb=Oe.canPlayType)!=null&&gb.call(Oe,"application/x-mpegurl")||(Sb=Oe.canPlayType)!=null&&Sb.call(Oe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},vb,yb,ve={mp4:!!((vb=Oe.canPlayType)!=null&&vb.call(Oe,"video/mp4")),webm:!!((yb=Oe.canPlayType)!=null&&yb.call(Oe,"video/webm")),cmaf:!0},vs,Tb,ys,Ib,Ts,Eb,Is,xb,Es,Pb,xs,Ab,ye={h264:!!((Tb=(vs=nt())==null?void 0:vs.isTypeSupported)!=null&&Tb.call(vs,Ww)),h265:!!((Ib=(ys=nt())==null?void 0:ys.isTypeSupported)!=null&&Ib.call(ys,Yw)),vp9:!!((Eb=(Ts=nt())==null?void 0:Ts.isTypeSupported)!=null&&Eb.call(Ts,kb)),av1:!!((xb=(Is=nt())==null?void 0:Is.isTypeSupported)!=null&&xb.call(Is,Rb)),aac:!!((Pb=(Es=nt())==null?void 0:Es.isTypeSupported)!=null&&Pb.call(Es,Qw)),opus:!!((Ab=(xs=nt())==null?void 0:xs.isTypeSupported)!=null&&Ab.call(xs,zw))},Ar=(ye.h264||ye.h265)&&ye.aac,Ut,Kw=()=>k(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(B(w({},a),{video:B(w({},a.video),{contentType:Rb})})),window.navigator.mediaCapabilities.decodingInfo(B(w({},a),{video:B(w({},a.video),{contentType:kb})}))]);Ut={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{Kw()}catch(a){console.error(a)}var wr=qt.hls&&ve.mp4,$b=()=>Object.keys(ye).filter(a=>ye[a]),Lb=(a,e=!1,t=!1)=>{let r=qt.mse||qt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&ve.mp4&&Ar;case"DASH_WEBM":return r&&ve.webm&&ye.vp9&&ye.opus;case"DASH_WEBM_AV1":return r&&ve.webm&&ye.av1&&ye.opus;case"DASH_STREAMS":return r&&(ve.mp4&&Ar||ve.webm&&(ye.vp9||ye.av1)&&(ye.opus||ye.aac));case"DASH_LIVE":return qt.mse&&ve.mp4&&Ar;case"DASH_LIVE_CMAF":return r&&ve.mp4&&Ar&&ve.cmaf;case"DASH_ONDEMAND":return r&&ve.mp4&&Ar;case"HLS":case"HLS_ONDEMAND":return wr||e&&qt.mse&&ve.mp4&&Ar;case"HLS_LIVE":case"HLS_LIVE_CMAF":return wr;case"MPEG":return ve.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return qt.webrtc&&qt.ws&&ye.h264&&(ve.mp4||ve.webm);default:return As(i)}})},Ss=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 Ut?Ut[t].smooth?[t,e]:Ut[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Ut?Ut[t].powerEfficient?[t,e]:Ut[e].powerEfficient?[e,t]:[t,e]:[e,t];default:As(a)}return[e,t]},Mb=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Ss(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Ps.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",...Ss(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ss(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ss(a),...i,"HLS","HLS_ONDEMAND"];default:As(e)}return wr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Cb=({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=Ps.isMac&&Ps.isSafari;if(Ps.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:As(a)}else wr&&!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"]},xu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Db=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,wb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as wi}from"@vkontakte/videoplayer-shared";var Ob=a=>{if(!a)return{id:"EmptyResponse",category:wi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:wi.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:wi.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:wi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:wi.PARSER,message:"Response is valid XML, but parser failed"}};var ki=(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 Wu,assertNonNullable as Jt,combine as Cs,ErrorCategory as It,filter as Ds,filterChanged as Cg,fromEvent as Or,interval as Yu,isNonNullable as Dg,map as Qu,merge as Br,Subject as Og,Subscription as Bg,tap as sR,throttle as nR,clientChecker as oR,ValueSubject as ue,flattenObject as ia,getTraceSubscriptionMethod as uR}from"@vkontakte/videoplayer-shared";var Cr=We(gi(),1);var Jw=(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)},Xw=a=>window.clearTimeout(a),Bb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Pu=Bb?Jw:window.requestIdleCallback,UO=Bb?Xw:window.cancelIdleCallback;var Ag=We(ns(),1);import{assertNever as Zw,ErrorCategory as Vb,clientChecker as Au,Subject as _b}from"@vkontakte/videoplayer-shared";var ek=16,Nb=!1;try{Nb=Au.isSafari&&!!Au.macVersion&&Au.macVersion<=ek}catch(a){console.error(a)}var wu=class{constructor(e){this.bufferFull$=new _b;this.error$=new _b;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:Vb.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return k(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 k(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 k(this,null,function*(){return new Promise(t=>{let r;Nb&&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:Vb.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:Zw(t)}}},Fb=wu;var ku=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 Mr,assertNonNullable as Ke,ErrorCategory as Qt,fromEvent as qu,getExponentialDelay as Uu,isNonNullable as Pg,isNullable as Ue,once as Jk,Subject as Xk,Subscription as Zk,ValueSubject as Ji}from"@vkontakte/videoplayer-shared";var W=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 kr=class extends W{};var Ri=class extends W{};var $i=class extends W{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 Li=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mi=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ci=class extends W{constructor(e,t){super(e,t),this.data=this.content}};var X=class extends W{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ht=class extends X{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 Di=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Oi=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends X{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 Vi=class extends X{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var _i=class extends X{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Ni=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Fi=class extends X{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 qi=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Hi=class extends X{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ji=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends X{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 Wi=class extends X{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 Yi=class extends X{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 rk={ftyp:$i,moov:Li,moof:Mi,mdat:Ci,sidx:Ht,trak:Di,mdia:Ni,mfhd:Hi,tkhd:Fi,traf:ji,tfhd:Gi,tfdt:Wi,trun:Yi,minf:qi,sv3d:Oi,st3d:Bi,prhd:Vi,proj:Ui,equi:_i,uuid:Ri,unknown:kr},jt=class a{constructor(e={}){this.options=w({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=rk[e];return r?new r(t,new a):new kr(t,new a)}};var Rr=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 ak=new TextDecoder("ascii"),sk=a=>ak.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",nk=a=>{let e=new Ht(a,new jt),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})},ok=(a,e)=>{let r=new jt().parse(a),i=new Rr(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)},uk=(a,e)=>{let r=new jt().parse(a),s=new Rr(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},lk=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 jt().parse(a),i=new Rr(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},qb={validateData:sk,parseInit:lk,getIndexRange:()=>{},parseSegments:nk,parseFeedableSegmentChunk:ok,getSegmentEndTime:uk};import{assertNonNullable as $u,isNonNullable as Gb,isNullable as dk}from"@vkontakte/videoplayer-shared";import{assertNever as ck}from"@vkontakte/videoplayer-shared";var Ub={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"}},Hb=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=Qi(a,t),i=r in Ub,s=i?Ub[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=Qi(u),d=l*Ge(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}},Qi=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*Ge(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*Ge(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*Ge(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 Qi(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:ck(e)}},Gt=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Hb(r);if(!e(i))return;i.type==="master"&&Gt(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},jb=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Hb(a);return Gt(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 Wb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],pk=[231,22612,22743,167,171,163,160,175],hk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Gt(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=qe(f,h);l=Qi(g)}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?Gt(f,({tag:g,type:S,value:I})=>g===30321?(c=qe(I,S)===1,!1):!0):s&&n&&Wb.includes(p)&&(o=!0),!o}),$u(e,"Failed to parse webm Segment start"),$u(t,"Failed to parse webm Segment end"),$u(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}}}},fk=a=>{if(dk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},mk=(a,e)=>{let t=!1,r=!1,i=o=>Gb(o.time)&&Gb(o.position),s=[],n;return Gt(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&&Wb.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}}})},bk=a=>{let e=0,t=!1;try{Gt(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):pk.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},Yb={validateData:jb,parseInit:hk,getIndexRange:fk,parseSegments:mk,parseFeedableSegmentChunk:bk};var $r=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Yb;case"mp4":return qb}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Vu=We(mg(),1);var Bu=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 gg,isNullable as Sg}from"@vkontakte/videoplayer-shared";var bg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var vg=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},Wt=(a,e)=>{let t=a;t=(0,Vu.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,Vu.default)(t,n,(o,u)=>Sg(s)?o:Sg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Tg=(a,e)=>{var y,T,M,C,$,V,G,N,R,F,_,P,x,D,Y,z,ee,H,Zt,lt,q,ce,Te,we,ct,er,dt,wt,tr,Nr,pl,hl,fl,ml,bl,gl,Sl,vl,yl,Tl,Il,El,xl,Pl,Al,wl,kl,Rl,$l,Ll;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(M=(T=(y=s.querySelector("BaseURL"))==null?void 0:y.textContent)==null?void 0:T.trim())!=null?M:"",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],g=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=vg(h);else if(f){let de=vg(f);gg(de)&&(p=de)}else g&&(p=parseInt(g,10));let S=0,I=($=(C=s.getAttribute("profiles"))==null?void 0:C.split(","))!=null?$:[];for(let de of u){let DS=(V=de.getAttribute("id"))!=null?V:"id"+(S++).toString(10),Fr=(G=de.getAttribute("mimeType"))!=null?G:"",en=(N=de.getAttribute("codecs"))!=null?N:"",tn=(R=de.getAttribute("contentType"))!=null?R:Fr==null?void 0:Fr.split("/")[0],OS=(_=(F=de.getAttribute("profiles"))==null?void 0:F.split(","))!=null?_:[],BS=(P=de.getAttribute("lang"))!=null?P:void 0,VS=(Y=(D=(x=de.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:D.trim())!=null?Y:void 0,_S=de.querySelectorAll("Representation"),NS=de.querySelector("SegmentTemplate"),FS=(ee=(z=de.querySelector("Role"))==null?void 0:z.getAttribute("value"))!=null?ee:void 0,qr=tn,te={id:DS,language:BS,isDefault:FS==="main",label:VS,codecs:en,hdr:qr==="video"&&Bu(en),mime:Fr,representations:[]};for(let Z of _S){let qS=(H=Z.getAttribute("lang"))!=null?H:void 0,US=(Zt=Z.getAttribute("label"))!=null?Zt:void 0,HS=(ce=(q=(lt=Z.querySelector("BaseURL"))==null?void 0:lt.textContent)==null?void 0:q.trim())!=null?ce:"",rn=new URL(HS||o,e).toString(),rr=(Te=Z.getAttribute("mimeType"))!=null?Te:Fr,Sa=(ct=(we=Z.getAttribute("codecs"))!=null?we:en)!=null?ct:"",an;if(tn==="text"){let kt=Z.getAttribute("id")||"",sn=kt.includes("_auto");an={id:kt,isAuto:sn,kind:"text",url:rn}}else{let kt=(dt=(er=Z.getAttribute("contentType"))!=null?er:rr==null?void 0:rr.split("/")[0])!=null?dt:tn,sn=(tr=(wt=de.getAttribute("profiles"))==null?void 0:wt.split(","))!=null?tr:[],jS=parseInt((Nr=Z.getAttribute("width"))!=null?Nr:"",10),Ml=parseInt((pl=Z.getAttribute("height"))!=null?pl:"",10),Cl=parseInt((hl=Z.getAttribute("bandwidth"))!=null?hl:"",10)/1e3,Dl=(fl=Z.getAttribute("frameRate"))!=null?fl:"",GS=(ml=Z.getAttribute("quality"))!=null?ml:void 0,WS=Dl?bg(Dl):void 0,YS=(bl=Z.getAttribute("id"))!=null?bl:"id"+(S++).toString(10),QS=kt==="video"?`${Ml}p`:kt==="audio"?`${Cl}Kbps`:Sa,zS=`${YS}@${QS}`,KS=[...I,...OS,...sn],nn,JS=Z.querySelector("SegmentBase"),Rt=(gl=Z.querySelector("SegmentTemplate"))!=null?gl:NS;if(JS){let $t=(vl=(Sl=Z.querySelector("SegmentBase Initialization"))==null?void 0:Sl.getAttribute("range"))!=null?vl:"",[Lt,un]=$t.split("-").map(ir=>parseInt(ir,10)),pt={from:Lt,to:un},Ur=(yl=Z.querySelector("SegmentBase"))==null?void 0:yl.getAttribute("indexRange"),[ln,va]=Ur?Ur.split("-").map(ir=>parseInt(ir,10)):[],Hr=Ur?{from:ln,to:va}:void 0;nn={type:"byteRange",url:rn,initRange:pt,indexRange:Hr}}else if(Rt){let $t={representationId:(Tl=Z.getAttribute("id"))!=null?Tl:void 0,bandwidth:(Il=Z.getAttribute("bandwidth"))!=null?Il:void 0},Lt=parseInt((El=Rt.getAttribute("timescale"))!=null?El:"",10),un=(xl=Rt.getAttribute("initialization"))!=null?xl:"",pt=Rt.getAttribute("media"),Ur=(Al=parseInt((Pl=Rt.getAttribute("startNumber"))!=null?Pl:"",10))!=null?Al:1,ln=Wt(un,$t);if(!pt)throw new ReferenceError("No media attribute in SegmentTemplate");let va=(wl=Rt.querySelectorAll("SegmentTimeline S"))!=null?wl:[],Hr=[],ir=0,cn="",dn=0;if(va.length){let ya=Ur,Be=0;for(let ar of va){let je=parseInt((kl=ar.getAttribute("d"))!=null?kl:"",10),Mt=parseInt((Rl=ar.getAttribute("r"))!=null?Rl:"",10)||0,Ta=parseInt(($l=ar.getAttribute("t"))!=null?$l:"",10);Be=Number.isFinite(Ta)?Ta:Be;let pn=je/Lt*1e3,hn=Be/Lt*1e3;for(let Ia=0;Ia<Mt+1;Ia++){let ZS=Wt(pt,B(w({},$t),{segmentNumber:ya.toString(10),segmentTime:(Be+Ia*je).toString(10)})),Ol=(hn!=null?hn:0)+Ia*pn,ev=Ol+pn;ya++,Hr.push({time:{from:Ol,to:ev},url:ZS})}Be+=(Mt+1)*je,ir+=(Mt+1)*pn}dn=Be/Lt*1e3,cn=Wt(pt,B(w({},$t),{segmentNumber:ya.toString(10),segmentTime:Be.toString(10)}))}else if(gg(p)){let Be=parseInt((Ll=Rt.getAttribute("duration"))!=null?Ll:"",10)/Lt*1e3,ar=Math.ceil(p/Be),je=0;for(let Mt=1;Mt<ar;Mt++){let Ta=Wt(pt,B(w({},$t),{segmentNumber:Mt.toString(10),segmentTime:je.toString(10)}));Hr.push({time:{from:je,to:je+Be},url:Ta}),je+=Be}dn=je,cn=Wt(pt,B(w({},$t),{segmentNumber:ar.toString(10),segmentTime:je.toString(10)}))}let XS={time:{from:dn,to:1/0},url:cn};nn={type:"template",baseUrl:rn,segmentTemplateUrl:pt,initUrl:ln,totalSegmentsDurationMs:ir,segments:Hr,nextSegmentBeyondManifest:XS,timescale:Lt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!kt||!rr)continue;let on={video:"video",audio:"audio",text:"text"}[kt];if(!on)continue;qr||(qr=on),an={id:zS,kind:on,segmentReference:nn,profiles:KS,duration:p,bitrate:Cl,mime:rr,codecs:Sa,width:jS,height:Ml,fps:WS,quality:GS}}te.language||(te.language=qS),te.label||(te.label=US),te.mime||(te.mime=rr),te.codecs||(te.codecs=Sa),te.hdr||(te.hdr=qr==="video"&&Bu(Sa)),te.representations.push(an)}qr&&i[qr].push(te)}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,streams:i}};var zi=We(gi(),1);import{videoSizeToQuality as Kk}from"@vkontakte/videoplayer-shared";var Ig=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?St(s):void 0)!=null?o:Kk({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},Eg=({id:a,bitrate:e})=>({id:a,bitrate:e}),ws=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,zi.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,zi.default)(t,-1)},xg=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Nu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,zi.default)(r.split("."),0),isDefault:i}),Fu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,zi.default)(i.split("."),0)}),ks=a=>"url"in a,Yt=a=>a.type==="template",Ki=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Xi=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new Ji(0);this.onLastSegment$=new Ji(!1);this.fullyBuffered$=new Ji(!1);this.playingRepresentation$=new Ji(void 0);this.playingRepresentationInit$=new Ji(void 0);this.error$=new Xk;this.gaps=[];this.subscription=new Zk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new st;this.destroyAbortController=new st;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=Mr(this.destroyAbortController.signal,function(e){return re(this,null,function*(){let t=this.representations.get(e);Ke(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Fb(this.sourceBuffer),this.subscription.add(qu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Qt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Qt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(qu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Qt.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,ku(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=it(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);Ke(r,"No init buffer for starting representation"),Ke(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=Mr(this.destroyAbortController.signal,function(e,t=!1){return re(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Ke(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Ue(s)||Ue(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Ke(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();Pg(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=Mr(this.destroyAbortController.signal,function(e){return re(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||!Yt(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);Ke(i);let s=this.segments.get(r);Ke(s,"No segments for starting representation");let n=this.initData.get(r);if(Ke(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.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 st,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(Ue(e)||Ue(this.downloadingRepresentationId)||Ue(this.playingRepresentationId)||Ue(this.sourceBuffer)||!Ue(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ke(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=it(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)&&ku(this.sourceBuffer.buffered)>=this.bufferLimit){let d=it(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,Cr.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&&it(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Cr.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;Pg(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||!Yt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>B(w({},p),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Cr.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;Ke(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Yt(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=Wt(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,g=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&I&&this.sourceBuffer&&!ki(this.sourceBuffer.buffered,r))&&g&&I});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let 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 k(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 k(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 Mr(o,function(){return re(this,null,function*(){let c=Uu(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=$r(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]),Ki(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return k(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 Mr(n,function(){return re(this,null,function*(){let u=Uu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),qu(window,"online").pipe(Jk()).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),Ki(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(Yt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Cr.default)(e,0).byte.from,to:(0,Cr.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:Qt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Yt(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:Qt.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 k(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=$r(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,g=p?d.byte.to-r:e.byteLength,S=b<i,I=g<=i;if(d.status==="downloading"&&S&&I){d.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+b,h);this.sourceBufferTaskQueue.append(v,s).then(y=>y&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(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),y=c.loadedBytes===h?v:$r(o.mime).parseFeedableSegmentChunk(v);y!=null&&y.byteLength&&(d.status="partially_fed",c.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(T=>{if(s.aborted)n();else if(T)c.fedBytes+=y.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return k(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 g=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(g,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 g=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?g:$r(u.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.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",ks(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=Pu(()=>(0,Ag.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return k(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Mr(this.destroyAbortController.signal,function(){return re(this,null,function*(){let o=Uu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,$r(e.mime),i)).then(o=>k(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&&Yt(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:Qt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return k(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 k(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return k(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||Ue(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=ks(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 k(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||Ue(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=ks(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=Pu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Qt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Ue(this.sourceBuffer)||Ue(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 wg=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 ea,assertNever as kg,fromEvent as Rg,merge as eR,now as ta,Subscription as tR,ValueSubject as Hu,flattenObject as Dr}from"@vkontakte/videoplayer-shared";var Rs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new Hu(void 0);this.lastConnectionReused$=new Hu(void 0);this.lastRequestFirstBytes$=new Hu(void 0);this.abortAllController=new st;this.subscription=new tR;this.fetchManifest=ea(this.abortAllController.signal,function(e){return re(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Zi(r));let i=yield at(r,{signal:this.abortAllController.signal}).catch(ra);return i?(t.log("success",Dr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Dr({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=ea(this.abortAllController.signal,function(l){return re(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 R,F;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(c,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),c=_.toString();break}default:kg(t)}this.requestQuic&&(c=Zi(c));let h=this.abortAllController.signal,f;if(n){let _=new st;if(f=eR(Rg(this.abortAllController.signal,"abort"),Rg(n,"abort")).subscribe(()=>{try{_.abort()}catch(P){ra(P)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(P){ra(P)}h=_.signal}let b=ta();p.log("startRequest",Dr({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield at(c,{priority:s,headers:d,signal:h}).catch(ra),S=ta();if(!g)return p.error("error",{message:"No response in request"}),p.end(),f==null||f.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.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 _=ta(),P={requestStartedAt:b,requestEndedAt:_,duration:_-b};return p.log("endRequest",Dr(P)),p.end(),g.arrayBuffer()}let[I,v]=g.body.tee(),y=I.getReader();o&&((F=this.throughputEstimator)==null||F.trackStream(v,u));let T=0,M=new Uint8Array(0),C=!1,$=_=>{f==null||f.unsubscribe(),C=!0,ra(_)},V=ea(h,function(x){return re(this,arguments,function*({done:_,value:P}){if(T===0&&this.lastRequestFirstBytes$.next(ta()-b),h.aborted){f==null||f.unsubscribe();return}if(!_&&P){let D=new Uint8Array(M.length+P.length);D.set(M),D.set(P,M.length),M=D,T+=P.byteLength,i==null||i(new DataView(M.buffer),T),yield y==null?void 0:y.read().then(V,$)}})}.bind(this));yield y==null?void 0:y.read().then(V,$),f==null||f.unsubscribe();let G=ta(),N={failed:C,requestStartedAt:b,requestEndedAt:G,duration:G-b};return C?(p.error("endRequest",Dr(N)),p.end(),null):(p.log("endRequest",Dr(N)),p.end(),M.buffer)})}.bind(this));this.fetchByteRangeRepresentation=ea(this.abortAllController.signal,function(e,t,r){return re(this,null,function*(){var S;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=(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 I=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!I)return null;b=new DataView(I)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=ea(this.abortAllController.signal,function(e,t){return re(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=>B(w({},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}=wg(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return k(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:kg(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ra=a=>{if(!Ki(a))throw a};var zt=(a,e,t)=>t*e+(1-t)*a,ju=(a,e)=>a.reduce((t,r)=>t+r,0)/e,$g=(a,e,t,r)=>{let i=0,s=t,n=ju(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 rR,ValueSubject as Lg}from"@vkontakte/videoplayer-shared";var Tt=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 Lg(e.initial),this.debounced$=new Lg(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new oe(`raw_${t}`),this.smoothedSeries$=new oe(`smoothed_${t}`),this.reportedSeries$=new oe(`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+=Ge(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)&&(rR(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 $s=class extends Tt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=zt(this.slow,e,this.params.emaAlphaSlow),this.fast=zt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ls=class extends Tt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ju(this.pastMeasures,this.takenMeasures);this.emaSmoothed=zt(this.emaSmoothed,e,this.params.emaAlpha);let r=$g(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Ms=class extends Tt{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?zt(this.smoothed,t,this.params.emaAlpha):t}};var Kt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new $s({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Ls({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 Ms(w({initial:e,label:"liveEdgeDelay"},t))}};var Gu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var Vg=["timeupdate","progress","play","seeked","stalled","waiting"];var Os=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Bg;this.representationSubscription=new Bg;this.state$=new L("none");this.currentVideoRepresentation$=new ue(void 0);this.currentVideoRepresentationInit$=new ue(void 0);this.currentAudioRepresentation$=new ue(void 0);this.currentVideoSegmentLength$=new ue(0);this.currentAudioSegmentLength$=new ue(0);this.error$=new Og;this.lastConnectionType$=new ue(void 0);this.lastConnectionReused$=new ue(void 0);this.lastRequestFirstBytes$=new ue(void 0);this.isLive$=new ue(!1);this.liveDuration$=new ue(0);this.liveAvailabilityStartTime$=new ue(void 0);this.bufferLength$=new ue(0);this.liveLoadBufferLength$=new ue(0);this.livePositionFromPlayer$=new ue(0);this.timeInWaiting=0;this.isActiveLowLatency$=new ue(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Og;this.gapWatchdogActive=!1;this.destroyController=new st;this.initManifest=Wu(this.destroyController.signal,function(e,t,r){return re(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=se(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:It.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Wu(this.destroyController.signal,function(){return re(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:It.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t;try{t=Tg(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Ob(e))!=null?n:{id:"ManifestParsing",category:It.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((f=(h=nt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${c}"`))||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 c=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(c.map(({codecs:h})=>h)),p=Db(d);if(p&&(i[u]=c.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);oR.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=B(w({},t),{streams:i});return this.tracer.log("updateManifestEnd",ia(s)),s})}.bind(this));this.initRepresentations=Wu(this.destroyController.signal,function(e,t,r){return re(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",ia({initialVideo:e,initialAudio:t,sourceHls:r})),Jt(this.manifest),Jt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Or(p,"error").pipe(Ds(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:It.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?bb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&gs())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 Xi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Dg(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Xi("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(Yu(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=au(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Br(...Vg.filter(p=>p!=="waiting").map(p=>Or(this.element,p))).pipe(Qu(p=>this.element?it(this.element.buffered,this.element.currentTime*1e3):0),Cg(),Ds(p=>!!p),sR(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Cg()).subscribe(h=>Gu(this.element,1))),this.representationSubscription.add(Cs({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Ds(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(Cs({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,I=h-b,v=1;Math.abs(I)>g&&(v=1+Math.sign(I)*S),Gu(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,T;return(T=(y=v.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?T:S}))-S}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(Cs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(nR(1e3)).subscribe(b=>k(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(Jt(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,S=au(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,M=isFinite(h)?h:f,C=this.isActiveLowLatency$.getValue(),$=I<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLowLatency$.next(C&&$);let V="none";if(C?V="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&$?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(G=>G.proceedLowLatencyLive()),V="active_low_latency"):S!==0&&M<v?V="live_forward_buffering":M<v+T&&(V="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),V==="live_forward_buffering"||V==="live_with_target_offset"){let G=p-(v+y),N=this.normolizeLiveOffset(Math.trunc(S+G/g)),R=Math.abs(N-S),F;!h||R<=this.tuning.dashCmafLive.offsetCalculationError?F=S:N>0&&R>this.tuning.dashCmafLive.offsetCalculationError?F=N:F=0,this.manifestUrlString=se(this.manifestUrlString,F,2)}V!=="none"&&V!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=Br(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Qu(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=Br(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Qu(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Br(this.forceEnded$,Cs({allBuffersFull:u,someBufferEnded:l}).pipe(Ds(({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:It.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Br(...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&&Dg(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=Yu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:It.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 Rs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=Kt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,w({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return k(this,null,function*(){var r,i,s,n;Jt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=se(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(){Jt(this.element),this.state$.setState("running"),this.subscription.add(Br(...Vg.map(e=>Or(this.element,e)),Or(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:It.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;this.element&&this.element.readyState===2&&!this.element.seeking&&ki(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var i,s;if(!this.element)return;this.timeInWaiting+=1e3;let r={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),r=B(w({},r),{liveLastSeekOffset:this.liveLastSeekOffset});else{let n=this.element.currentTime*1e3;(i=this.videoBufferManager)==null||i.maintain(n),(s=this.audioBufferManager)==null||s.maintain(n),r=B(w({},r),{position:n})}this.tracer.log("stallIntervalCallback",ia(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Yu(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:It.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return k(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;Jt(this.element),Jt(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),ki(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,this.tracer.log("seek",ia({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=uR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return k(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=B(w({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",ia(t)))}}};var Bs=class{constructor(e,t){this.fov=e,this.orientation=t}};var Vs=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/Ge(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=w({},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*Ge(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 _g=`attribute vec2 a_vertex;
36
+ [best video track] ${V==null?void 0:V.quality}
37
+ [selected video track] ${D==null?void 0:D.quality}
38
+ `}),Db(r,p,D,c)},Bb=(a,e,t,{throughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var f;Lb(t,Cb);let c=i.considerPlaybackRate&&ve(s)?s:1,l=[...t].sort(Cu(-1)),d=a.bitrate;Rw(d);let p=c*Mb(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),h;return ve(r)&&isFinite(r)&&(h=l.find(b=>ve(b.bitrate)?r-d>=b.bitrate*p:!0)),h||(h=Ms(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 qb,assertNonNullable as Ub,combine as Kw,debounce as Jw,ErrorCategory as Hb,filter as jb,filterChanged as Xw,isNonNullable as _u,map as Vs,merge as Gb,observableFrom as Zw,once as ek,Subscription as tk,ValueSubject as Nu,videoQualityToHeight as rk,videoSizeToQuality as ik}from"@vkontakte/videoplayer-shared";var Ob=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"))},ye=a=>R(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!Ob(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return Ob(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as Ds,isNullable as Cw,assertNonNullable as Bi}from"@vkontakte/videoplayer-shared";import{isNonNullable as Vb,assertNonNullable as Cs,now as Lw}from"@vkontakte/videoplayer-shared";function ie(){return Lw()}function Du(a){return ie()-a}function Bu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let c=n.indexOf("?")>-1?"&":"?";return u&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function _b(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Or(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;Cs(l);let L=Du(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,k=()=>(Cs(l),Math.max(l,Math.max(F||0,_||0)));if(s&&n.addEventListener("progress",x=>{let B=ie();s.updateChunk&&x.loaded>L&&(s.updateChunk(k(),x.loaded-L),L=x.loaded,F=B)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;Cs(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let B=n.response.byteLength-L;B&&s.updateChunk&&s.updateChunk(k(),B)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),p){let x=()=>{Cs(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)=>(Vb(L)&&(b=L),Vb(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 Ci=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Di=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=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=Or(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 Bs=1e4,Ou=3;var Dw=6e4,Bw=10,Ow=1,Vw=500,Oi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new Ci(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Bu(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=Bu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(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||Ds(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{_b(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Di(Ou,Bs,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=Or(this.urlResolver.resolve(y,!1),I,$,()=>this._retryCallback()).withTimeout(Bs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ou).withFinally(()=>{u=null}).send()},h=(y,I,$)=>{Bi(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 D=0;D<this.bufferStates.length;D++){let H=this.bufferStates[D];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 V=y-Ow;this.sourceJitter>=0?V-=this.sourceJitter/2:this.sourceJitter-=1,V>3?f(1.15):V>1?f(1.1):V>.3?f(1.05):f(1)}},S=y=>{let I,$=()=>I&&I.start?I.start.length:0,G=x=>I.start[x]/1e3,V=x=>I.dur[x]/1e3,D=x=>I.fragIndex+x,H=(x,B)=>({chunkIdx:D(x),startTS:G(x),dur:V(x),discontinuity:B}),N=()=>{let x=0;if(I&&I.dur){let B=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,z=B;this.sourceJitter>1&&(z+=this.sourceJitter-1);let Z=I.dur.length-1;for(;Z>=0&&(z-=I.dur[Z],!(z<=0));--Z);x=Math.min(Z,I.dur.length-1-W),x=Math.max(x,0)}return H(x,!0)},L=x=>{let B=$();if(!(B<=0)){if(Ds(x)){for(let W=0;W<B;W++)if(G(W)>x)return H(W)}return N()}},F=x=>{let B=$(),W=x?x.chunkIdx+1:0,z=W-I.fragIndex;if(!(B<=0)){if(!x||z<0||z-B>Bw)return t(`Resync: offset=${z} bChunks=${B} chunk=`+JSON.stringify(x)),N();if(!(z>=B))return H(W-I.fragIndex,!1)}},_=(x,B,W)=>{c&&c.abort(),c=Or(this.urlResolver.resolve(x,!0,this.lowLatency),B,W,()=>this._retryCallback()).withTimeout(Bs).withRetryCount(Ou).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(x,B)=>{_(y,W=>{if(!d())return;I=W;let z=!!I.lowLatency;z!==this.lowLatency&&b(z);let Z=0;for(let le=0;le<I.dur.length;++le)Z+=I.dur[le];Z>0&&(Bi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Z/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(B))},()=>this._handleNetworkError())},nextChunk:F}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),Bi(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:y=>{let{videoElement:I,logger:$}=this.params,G=S(e.jidxUrl),V,D,H,N,L=0,F,_,k,x=()=>{F&&(clearTimeout(F),F=void 0);let w=Math.max(Vw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),de=L+w,Ee=ie(),Re=Math.min(1e4,de-Ee);L=Ee;let St=()=>{c||d()&&G.seek(()=>{d()&&(L=ie(),B(),x())})};Re>0?F=window.setTimeout(()=>{this.paused?x():St()},Re):St()},B=()=>{let w;for(;w=G.nextChunk(N);)N=w,Ot(w);let de=G.nextChunk(H);if(de){if(H&&de.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?x():(T(),this._initPlayerWith(e));return}le(de)}else x()},W=(w,de)=>{if(!d()||!this.sourceBuffer)return;let Ee,Re,St,ur=vt=>{window.setTimeout(()=>{d()&&W(w,de)},vt)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),ur(100);else{let vt=ie(),Vt=I.currentTime;!this.paused&&I.buffered.length>1&&_===Vt&&vt-k>500&&($("Stall suspected; trying to fix"),this._fixupStall()),_!==Vt&&(_=Vt,k=vt);let cr=this._getBufferSizeSec();if(cr>30)$(`Buffered ${cr} seconds; delaying appendBuffer`),ur(2e3);else try{this.sourceBuffer.appendBuffer(w),this.videoPlayStarted?(this.bufferStates.push({ts:vt,buf:cr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),de&&de()}catch(Jr){if(Jr.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),St=this.sourceBuffer.buffered.length,St!==0&&(Ee=this.sourceBuffer.buffered.start(0),Re=Vt,Re-Ee>4&&this.sourceBuffer.remove(Ee,Re-3)),ur(1e3);else throw Jr}}},z=()=>{D&&V&&($([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(H)]),W(D,function(){D=null,B()}))},Z=w=>e.fragUrlTemplate.replace("%%id%%",w.chunkIdx),le=w=>{d()&&h(Z(w),(de,Ee)=>{if(d()){if(Ee/=1e3,D=de,H=w,n=w.startTS,Ee){let Re=Math.min(10,w.dur/Ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Re:Re}z()}},()=>this._handleNetworkError())},Ot=w=>{d()&&(Bi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Z(w),!1)))},gt=w=>{d()&&(e.cachedHeader=w,W(w,()=>{V=!0,z()}))};s=!0,G.seek(w=>{if(d()){if(L=ie(),!w){x();return}N=w,!Cw(y)||w.startTS>y?le(w):(H=w,B())}},y),e.cachedHeader?gt(e.cachedHeader):p(e.headerUrl,gt,()=>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(),Ds(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,Bi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ds(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&&Du(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=Or(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Bs).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;ye(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))},Dw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as _w,filter as Nb,fromEvent as Nw,interval as Fw,isHigher as qw,isInvariantQuality as Uw,isLower as Hw,merge as jw,Subject as Fb,Subscription as Gw}from"@vkontakte/videoplayer-shared";var Vu=class{constructor(){this.onDroopedVideoFramesLimit$=new Fb;this.subscription=new Gw;this.playing=!1;this.tracks=[];this.forceChecker$=new Fb;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Uw(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&qw(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(Nw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Fw(this.droppedFramesChecker.checkTime).pipe(Nb(()=>this.playing),Nb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(_w(this.droppedFramesChecker.checkTime)),r=jw(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])=>Hw(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}},Os=Vu;import{map as Ww,Observable as Yw}from"@vkontakte/videoplayer-shared";import{fromEvent as Qw}from"@vkontakte/videoplayer-shared";var Vi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var zw=(a,e)=>new Yw(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Vi()))},A(A({},r),e));i.observe(a);let s=Qw(document,"visibilitychange").pipe(Ww(n=>!document.hidden||Vi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ve=zw;var ak=["paused","playing","ready"],sk=["paused","playing","ready"],_i=class{constructor(e){this.subscription=new tk;this.videoState=new C("stopped");this.representations$=new Nu([]);this.textTracksManager=new Be;this.droppedFramesManager=new Os;this.maxSeekBackTime$=new Nu(1/0);this.zeroTime$=new Nu(void 0);this.liveOffset=new ut;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:Hb.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=kt(u.name))!=null?r:ik(u.video),d=u.bitrate/1e3,p=A({},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),_u(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(sk.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&ak.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 qb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Hb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Gb(this.videoState.stateChangeStarted$.pipe(Vs(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Vs(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.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=Se(this.video);this.subscription.add(this.representations$.pipe(Vs(i=>i.map(({track:s})=>s)),jb(i=>!!i.length),ek()).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(Xw(),Vs(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Kw({zeroTime:this.zeroTime$.pipe(jb(_u)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(et(this.video,this.params.desiredState.isLooped,t)).add(ge(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(De(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(Ve(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&rk(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 qb(i.to)}},t)).add(Gb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Zw(["init"])).pipe(Jw(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),be(this.video)}createLiveDashPlayer(){let e=new Oi({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&&_u(t)?t:Rt(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;Ub(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;Ub(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 Wb=_i;var lt=(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 LR,assertNonNullable as MR,debounce as CR,ErrorCategory as fc,filter as bS,filterChanged as mc,fromEvent as DR,isNonNullable as BR,map as gS,merge as ln,observableFrom as OR,observeElementSize as VR,once as SS,Subscription as _R,ValueSubject as NR}from"@vkontakte/videoplayer-shared";var _s=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}},Vr=class extends _s{constructor(){super(),this.listeners||_s.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)}},Ni=class{constructor(){Object.defineProperty(this,"signal",{value:new Vr,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&&(Ni.prototype[Symbol.toStringTag]="AbortController",Vr.prototype[Symbol.toStringTag]="AbortSignal");function Ns(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Fu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Ns({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(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 Fi=Ns({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Yb=Fi?Fu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,dt=Fi?Yb.fetch:window.fetch,jB=Fi?Yb.Request:window.Request,pt=Fi?Ni:window.AbortController,GB=Fi?Vr:window.AbortSignal;var ng=Xe($i(),1);var ht=()=>window.ManagedMediaSource||window.MediaSource,Fs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Qb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},zb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as zs,clientChecker as Qs}from"@vkontakte/videoplayer-shared";var _e=document.createElement("video"),uk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',ck='video/mp4; codecs="hev1.1.6.L93.B0"',og='video/webm; codecs="vp09.00.10.08"',ug='video/webm; codecs="av01.0.00M.08"',lk='audio/mp4; codecs="mp4a.40.2"',dk='audio/webm; codecs="opus"',Kb,Jb,Xt={mms:Fs(),mse:Qb(),hls:!!((Kb=_e.canPlayType)!=null&&Kb.call(_e,"application/x-mpegurl")||(Jb=_e.canPlayType)!=null&&Jb.call(_e,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Xb,Zb,Te={mp4:!!((Xb=_e.canPlayType)!=null&&Xb.call(_e,"video/mp4")),webm:!!((Zb=_e.canPlayType)!=null&&Zb.call(_e,"video/webm")),cmaf:!0},Us,eg,Hs,tg,js,rg,Gs,ig,Ws,ag,Ys,sg,Ie={h264:!!((eg=(Us=ht())==null?void 0:Us.isTypeSupported)!=null&&eg.call(Us,uk)),h265:!!((tg=(Hs=ht())==null?void 0:Hs.isTypeSupported)!=null&&tg.call(Hs,ck)),vp9:!!((rg=(js=ht())==null?void 0:js.isTypeSupported)!=null&&rg.call(js,og)),av1:!!((ig=(Gs=ht())==null?void 0:Gs.isTypeSupported)!=null&&ig.call(Gs,ug)),aac:!!((ag=(Ws=ht())==null?void 0:Ws.isTypeSupported)!=null&&ag.call(Ws,lk)),opus:!!((sg=(Ys=ht())==null?void 0:Ys.isTypeSupported)!=null&&sg.call(Ys,dk))},_r=(Ie.h264||Ie.h265)&&Ie.aac,Zt,pk=()=>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(M(A({},a),{video:M(A({},a.video),{contentType:ug})})),window.navigator.mediaCapabilities.decodingInfo(M(A({},a),{video:M(A({},a.video),{contentType:og})}))]);Zt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{pk()}catch(a){console.error(a)}var Nr=Xt.hls&&Te.mp4,cg=()=>Object.keys(Ie).filter(a=>Ie[a]),lg=(a,e=!1,t=!1)=>{let r=Xt.mse||Xt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&Te.mp4&&_r;case"DASH_WEBM":return r&&Te.webm&&Ie.vp9&&Ie.opus;case"DASH_WEBM_AV1":return r&&Te.webm&&Ie.av1&&Ie.opus;case"DASH_STREAMS":return r&&(Te.mp4&&_r||Te.webm&&(Ie.vp9||Ie.av1)&&(Ie.opus||Ie.aac));case"DASH_LIVE":return Xt.mse&&Te.mp4&&_r;case"DASH_LIVE_CMAF":return r&&Te.mp4&&_r&&Te.cmaf;case"DASH_ONDEMAND":return r&&Te.mp4&&_r;case"HLS":case"HLS_ONDEMAND":return Nr||e&&Xt.mse&&Te.mp4&&_r;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Nr;case"MPEG":return Te.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Xt.webrtc&&Xt.ws&&Ie.h264&&(Te.mp4||Te.webm);default:return zs(i)}})},qs=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 Zt?Zt[t].smooth?[t,e]:Zt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Zt?Zt[t].powerEfficient?[t,e]:Zt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:zs(a)}return[e,t]},dg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...qs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Qs.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",...qs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...qs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...qs(a),...i,"HLS","HLS_ONDEMAND"];default:zs(e)}return Nr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},pg=({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=Qs.isMac&&Qs.isSafari;if(Qs.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:zs(a)}else Nr&&!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"]},qu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],hg=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,ng.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as qi}from"@vkontakte/videoplayer-shared";var fg=a=>{if(!a)return{id:"EmptyResponse",category:qi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:qi.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:qi.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:qi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:qi.PARSER,message:"Response is valid XML, but parser failed"}};var Ui=(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 dc,assertNonNullable as nr,combine as an,ErrorCategory as Lt,filter as sn,filterChanged as cS,fromEvent as Yr,interval as pc,isNonNullable as lS,map as hc,merge as Qr,Subject as dS,Subscription as pS,tap as ER,throttle as xR,clientChecker as AR,ValueSubject as se,flattenObject as Sa,getTraceSubscriptionMethod as PR}from"@vkontakte/videoplayer-shared";var Gr=Xe($i(),1);var hk=(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)},fk=a=>window.clearTimeout(a),mg=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Uu=mg?hk:window.requestIdleCallback,nO=mg?fk:window.cancelIdleCallback;var rS=Xe(Rs(),1);import{assertNever as mk,ErrorCategory as bg,clientChecker as Hu,Subject as gg}from"@vkontakte/videoplayer-shared";var bk=16,Sg=!1;try{Sg=Hu.isSafari&&!!Hu.macVersion&&Hu.macVersion<=bk}catch(a){console.error(a)}var ju=class{constructor(e){this.bufferFull$=new gg;this.error$=new gg;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:bg.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;Sg&&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:bg.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:mk(t)}}},vg=ju;var Gu=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 jr,assertNonNullable as rt,ErrorCategory as ir,fromEvent as sc,getExponentialDelay as nc,isNonNullable as oc,isNullable as Ne,once as hR,Subject as fR,Subscription as mR,ValueSubject as da}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 Fr=class extends j{};var Hi=class extends j{};var ji=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 Gi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Wi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yi=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var X=class extends j{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var er=class extends X{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 Qi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ki=class extends X{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 Ji=class extends X{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Xi=class extends X{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Zi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends X{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 ta=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ra=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ia=class extends X{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var aa=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var sa=class extends X{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 na=class extends X{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 oa=class extends X{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 Sk={ftyp:ji,moov:Gi,moof:Wi,mdat:Yi,sidx:er,trak:Qi,mdia:Zi,mfhd:ia,tkhd:ea,traf:aa,tfhd:sa,tfdt:na,trun:oa,minf:ta,sv3d:zi,st3d:Ki,prhd:Ji,proj:ra,equi:Xi,uuid:Hi,unknown:Fr},tr=class a{constructor(e={}){this.options=A({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=Sk[e];return r?new r(t,new a):new Fr(t,new a)}};var qr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var yk=new TextDecoder("ascii"),Tk=a=>yk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Ik=a=>{let e=new er(a,new tr),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})},Ek=(a,e)=>{let r=new tr().parse(a),i=new qr(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)},xk=(a,e)=>{let r=new tr().parse(a),s=new qr(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},Ak=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 tr().parse(a),i=new qr(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},yg={validateData:Tk,parseInit:Ak,getIndexRange:()=>{},parseSegments:Ik,parseFeedableSegmentChunk:Ek,getSegmentEndTime:xk};import{assertNonNullable as Yu,isNonNullable as xg,isNullable as wk}from"@vkontakte/videoplayer-shared";import{assertNever as Pk}from"@vkontakte/videoplayer-shared";var Tg={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"}},Ig=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=ua(a,t),i=r in Tg,s=i?Tg[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=ua(u),d=c*Je(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}},ua=(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},We=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ua(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:Pk(e)}},rr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Ig(r);if(!e(i))return;i.type==="master"&&rr(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=Ig(a);return rr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=We(o,n):s===17026?t=We(o,n):s===17029&&(r=We(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Ag=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],kk=[231,22612,22743,167,171,163,160,175],Rk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,c,l=!1,d=0;return rr(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=We(f,h);c=ua(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=We(f,h):p===17545?i=We(f,h):p===21420&&c===475249515?u=We(f,h):p===374648427?rr(f,({tag:g,type:S,value:T})=>g===30321?(l=We(T,S)===1,!1):!0):s&&n&&Ag.includes(p)&&(o=!0),!o}),Yu(e,"Failed to parse webm Segment start"),Yu(t,"Failed to parse webm Segment end"),Yu(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},$k=a=>{if(wk(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=>xg(o.time)&&xg(o.position),s=[],n;return rr(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=We(c,u));break;case 183:break;case 241:n&&(n.position=We(c,u));break;default:t&&Ag.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}}})},Mk=a=>{let e=0,t=!1;try{rr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):kk.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},Pg={validateData:Eg,parseInit:Rk,getIndexRange:$k,parseSegments:Lk,parseFeedableSegmentChunk:Mk};var Ur=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Pg;case"mp4":return yg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var ec=Xe(Qg(),1);var Zu=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 Kg,isNullable as Jg}from"@vkontakte/videoplayer-shared";var zg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Xg=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},ft=(a,e)=>{let t=a;t=(0,ec.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,ec.default)(t,n,(o,u)=>Jg(s)?o:Jg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Zg=(a,e)=>{var y,I,$,G,V,D,H,N,L,F,_,k,x,B,W,z,Z,le,Ot,gt,w,de,Ee,Re,St,ur,vt,Vt,cr,Jr,Lc,Mc,Cc,Dc,Bc,Oc,Vc,_c,Nc,Fc,qc,Uc,Hc,jc,Gc,Wc,Yc,Qc,zc,Kc,Jc,Xc,Zc,el,tl,rl,il,al,sl,nl;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=Xg(h);else if(f){let pe=Xg(f);Kg(pe)&&(p=pe)}else g&&(p=parseInt(g,10));let S=0,T=(V=(G=s.getAttribute("profiles"))==null?void 0:G.split(","))!=null?V:[];for(let pe of u){let cv=(D=pe.getAttribute("id"))!=null?D:"id"+(S++).toString(10),Xr=(H=pe.getAttribute("mimeType"))!=null?H:"",An=(N=pe.getAttribute("codecs"))!=null?N:"",Pn=(L=pe.getAttribute("contentType"))!=null?L:Xr==null?void 0:Xr.split("/")[0],lv=(_=(F=pe.getAttribute("profiles"))==null?void 0:F.split(","))!=null?_:[],dv=(k=pe.getAttribute("lang"))!=null?k:void 0,pv=(W=(B=(x=pe.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:B.trim())!=null?W:void 0,hv=pe.querySelectorAll("Representation"),fv=pe.querySelector("SegmentTemplate"),mv=(Z=(z=pe.querySelector("Role"))==null?void 0:z.getAttribute("value"))!=null?Z:void 0,Zr=Pn,ee={id:cv,language:dv,isDefault:mv==="main",label:pv,codecs:An,hdr:Zr==="video"&&Zu(An),mime:Xr,representations:[]};for(let Y of hv){let bv=(le=Y.getAttribute("lang"))!=null?le:void 0,gv=(Ot=Y.getAttribute("label"))!=null?Ot:void 0,Sv=(de=(w=(gt=Y.querySelector("BaseURL"))==null?void 0:gt.textContent)==null?void 0:w.trim())!=null?de:"",Ca=new URL(Sv||o,e).toString(),lr=(Ee=Y.getAttribute("mimeType"))!=null?Ee:Xr,Da=(St=(Re=Y.getAttribute("codecs"))!=null?Re:An)!=null?St:"",Ba;if(Pn==="text"){let _t=Y.getAttribute("id")||"",Oa=_t.includes("_auto"),Nt=Y.querySelector("SegmentTemplate");if(Nt){let dr={representationId:(ur=Y.getAttribute("id"))!=null?ur:void 0,bandwidth:(vt=Y.getAttribute("bandwidth"))!=null?vt:void 0},Va=parseInt((Vt=Y.getAttribute("bandwidth"))!=null?Vt:"",10)/1e3,_a=(Jr=parseInt((cr=Nt.getAttribute("startNumber"))!=null?cr:"",10))!=null?Jr:1,pr=parseInt((Lc=Nt.getAttribute("timescale"))!=null?Lc:"",10),wn=(Mc=Nt.querySelectorAll("SegmentTimeline S"))!=null?Mc:[],hr=Nt.getAttribute("media");if(!hr)throw new ReferenceError("No media attribute in SegmentTemplate");let Na=[],Fa=0,qa="",fr=0,ei=_a,ne=0;for(let Fe of wn){let Ft=parseInt((Cc=Fe.getAttribute("d"))!=null?Cc:"",10),$e=parseInt((Dc=Fe.getAttribute("r"))!=null?Dc:"",10)||0,yt=parseInt((Bc=Fe.getAttribute("t"))!=null?Bc:"",10);ne=Number.isFinite(yt)?yt:ne;let qt=Ft/pr*1e3,Tt=ne/pr*1e3;for(let ze=0;ze<$e+1;ze++){let It=ft(hr,M(A({},dr),{segmentNumber:ei.toString(10),segmentTime:(ne+ze*Ft).toString(10)})),mr=(Tt!=null?Tt:0)+ze*qt,ri=mr+qt;ei++,Na.push({time:{from:mr,to:ri},url:It})}ne+=($e+1)*Ft,Fa+=($e+1)*qt}fr=ne/pr*1e3,qa=ft(hr,M(A({},dr),{segmentNumber:ei.toString(10),segmentTime:ne.toString(10)}));let ti={time:{from:fr,to:1/0},url:qa},it={type:"template",baseUrl:Ca,segmentTemplateUrl:hr,initUrl:"",totalSegmentsDurationMs:Fa,segments:Na,nextSegmentBeyondManifest:ti,timescale:pr};Ba={id:_t,kind:"text",segmentReference:it,profiles:[],duration:p,bitrate:Va,mime:"",codecs:"",width:0,height:0,isAuto:Oa}}else Ba={id:Y.getAttribute("id")||"",isAuto:Oa,kind:"text",url:Ca}}else{let _t=(Vc=(Oc=Y.getAttribute("contentType"))!=null?Oc:lr==null?void 0:lr.split("/")[0])!=null?Vc:Pn,Oa=(Nc=(_c=pe.getAttribute("profiles"))==null?void 0:_c.split(","))!=null?Nc:[],Nt=parseInt((Fc=Y.getAttribute("width"))!=null?Fc:"",10),dr=parseInt((qc=Y.getAttribute("height"))!=null?qc:"",10),Va=parseInt((Uc=Y.getAttribute("bandwidth"))!=null?Uc:"",10)/1e3,_a=(Hc=Y.getAttribute("frameRate"))!=null?Hc:"",pr=(jc=Y.getAttribute("quality"))!=null?jc:void 0,wn=_a?zg(_a):void 0,hr=(Gc=Y.getAttribute("id"))!=null?Gc:"id"+(S++).toString(10),Na=_t==="video"?`${dr}p`:_t==="audio"?`${Va}Kbps`:Da,Fa=`${hr}@${Na}`,qa=[...T,...lv,...Oa],fr,ei=Y.querySelector("SegmentBase"),ne=(Wc=Y.querySelector("SegmentTemplate"))!=null?Wc:fv;if(ei){let it=(Qc=(Yc=Y.querySelector("SegmentBase Initialization"))==null?void 0:Yc.getAttribute("range"))!=null?Qc:"",[Fe,Ft]=it.split("-").map(It=>parseInt(It,10)),$e={from:Fe,to:Ft},yt=(zc=Y.querySelector("SegmentBase"))==null?void 0:zc.getAttribute("indexRange"),[qt,Tt]=yt?yt.split("-").map(It=>parseInt(It,10)):[],ze=yt?{from:qt,to:Tt}:void 0;fr={type:"byteRange",url:Ca,initRange:$e,indexRange:ze}}else if(ne){let it={representationId:(Kc=Y.getAttribute("id"))!=null?Kc:void 0,bandwidth:(Jc=Y.getAttribute("bandwidth"))!=null?Jc:void 0},Fe=parseInt((Xc=ne.getAttribute("timescale"))!=null?Xc:"",10),Ft=(Zc=ne.getAttribute("initialization"))!=null?Zc:"",$e=ne.getAttribute("media"),yt=(tl=parseInt((el=ne.getAttribute("startNumber"))!=null?el:"",10))!=null?tl:1,qt=ft(Ft,it);if(!$e)throw new ReferenceError("No media attribute in SegmentTemplate");let Tt=(rl=ne.querySelectorAll("SegmentTimeline S"))!=null?rl:[],ze=[],It=0,mr="",ri=0;if(Tt.length){let Ua=yt,qe=0;for(let br of Tt){let Ke=parseInt((il=br.getAttribute("d"))!=null?il:"",10),Ut=parseInt((al=br.getAttribute("r"))!=null?al:"",10)||0,Ha=parseInt((sl=br.getAttribute("t"))!=null?sl:"",10);qe=Number.isFinite(Ha)?Ha:qe;let kn=Ke/Fe*1e3,Rn=qe/Fe*1e3;for(let ja=0;ja<Ut+1;ja++){let yv=ft($e,M(A({},it),{segmentNumber:Ua.toString(10),segmentTime:(qe+ja*Ke).toString(10)})),ol=(Rn!=null?Rn:0)+ja*kn,Tv=ol+kn;Ua++,ze.push({time:{from:ol,to:Tv},url:yv})}qe+=(Ut+1)*Ke,It+=(Ut+1)*kn}ri=qe/Fe*1e3,mr=ft($e,M(A({},it),{segmentNumber:Ua.toString(10),segmentTime:qe.toString(10)}))}else if(Kg(p)){let qe=parseInt((nl=ne.getAttribute("duration"))!=null?nl:"",10)/Fe*1e3,br=Math.ceil(p/qe),Ke=0;for(let Ut=1;Ut<br;Ut++){let Ha=ft($e,M(A({},it),{segmentNumber:Ut.toString(10),segmentTime:Ke.toString(10)}));ze.push({time:{from:Ke,to:Ke+qe},url:Ha}),Ke+=qe}ri=Ke,mr=ft($e,M(A({},it),{segmentNumber:br.toString(10),segmentTime:Ke.toString(10)}))}let vv={time:{from:ri,to:1/0},url:mr};fr={type:"template",baseUrl:Ca,segmentTemplateUrl:$e,initUrl:qt,totalSegmentsDurationMs:It,segments:ze,nextSegmentBeyondManifest:vv,timescale:Fe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!_t||!lr)continue;let ti={video:"video",audio:"audio",text:"text"}[_t];if(!ti)continue;Zr||(Zr=ti),Ba={id:Fa,kind:ti,segmentReference:fr,profiles:qa,duration:p,bitrate:Va,mime:lr,codecs:Da,width:Nt,height:dr,fps:wn,quality:pr}}ee.language||(ee.language=bv),ee.label||(ee.label=gv),ee.mime||(ee.mime=lr),ee.codecs||(ee.codecs=Da),ee.hdr||(ee.hdr=Zr==="video"&&Zu(Da)),ee.representations.push(Ba)}Zr&&i[Zr].push(ee)}return{dynamic:c,liveAvailabilityStartTime:d,duration:p,streams:i}};var ca=Xe($i(),1);import{videoSizeToQuality as pR}from"@vkontakte/videoplayer-shared";var eS=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?kt(s):void 0)!=null?o:pR({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},tS=({id:a,bitrate:e})=>({id:a,bitrate:e}),Ks=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,ca.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,ca.default)(t,-1)},Js=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),ic=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,ca.default)(r.split("."),0),isDefault:i}),ac=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,ca.default)(i.split("."),0)}),Xs=a=>"url"in a,Ye=a=>a.type==="template",la=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var pa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new da(0);this.onLastSegment$=new da(!1);this.fullyBuffered$=new da(!1);this.playingRepresentation$=new da(void 0);this.playingRepresentationInit$=new da(void 0);this.error$=new fR;this.gaps=[];this.subscription=new mR;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new pt;this.destroyAbortController=new pt;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=jr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){let t=this.representations.get(e);rt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new vg(this.sourceBuffer),this.subscription.add(sc(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:ir.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:ir.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(sc(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ir.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,Gu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=lt(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);rt(r,"No init buffer for starting representation"),rt(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=jr(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);rt(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Ne(s)||Ne(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),rt(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();oc(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=jr(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||!Ye(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);rt(i);let s=this.segments.get(r);rt(s,"No segments for starting representation");let n=this.initData.get(r);if(rt(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 pt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;if(Ne(e)||Ne(this.downloadingRepresentationId)||Ne(this.playingRepresentationId)||Ne(this.sourceBuffer)||!Ne(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(rt(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=lt(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)&&Gu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=lt(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,Gr.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&&lt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Gr.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;oc(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||!Ye(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>M(A({},p),{status:"none",size:void 0})),c=(i=this.segments.get(o.id))!=null?i:[],l=(n=(s=(0,Gr.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;rt(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(!Ye(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=ft(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&&!Ui(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 jr(o,function(){return te(this,null,function*(){let l=nc(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=Ur(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]),la(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 jr(n,function(){return te(this,null,function*(){let u=nc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),sc(window,"online").pipe(hR()).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),la(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(Ye(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Gr.default)(e,0).byte.from,to:(0,Gr.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:ir.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ye(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:ir.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=Ur(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();oc(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(V=>V&&!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||Ne(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:Ur(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:Ur(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",Xs(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=Uu(()=>(0,rS.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?jr(this.destroyAbortController.signal,function(){return te(this,null,function*(){let o=nc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ur(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&&Ye(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:ir.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||Ne(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=Xs(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||Ne(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=Xs(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=Uu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:ir.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Ne(this.sourceBuffer)||Ne(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 ha=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var iS=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 fa,assertNever as aS,fromEvent as sS,merge as bR,now as ma,Subscription as gR,ValueSubject as uc,flattenObject as Wr}from"@vkontakte/videoplayer-shared";var Zs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new uc(void 0);this.lastConnectionReused$=new uc(void 0);this.lastRequestFirstBytes$=new uc(void 0);this.abortAllController=new pt;this.subscription=new gR;this.fetchManifest=fa(this.abortAllController.signal,function(e){return te(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ha(r));let i=yield dt(r,{signal:this.abortAllController.signal}).catch(ba);return i?(t.log("success",Wr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Wr({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=fa(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:aS(t)}this.requestQuic&&(l=ha(l));let h=this.abortAllController.signal,f;if(n){let _=new pt;if(f=bR(sS(this.abortAllController.signal,"abort"),sS(n,"abort")).subscribe(()=>{try{_.abort()}catch(k){ba(k)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(k){ba(k)}h=_.signal}let b=ma();p.log("startRequest",Wr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield dt(l,{priority:s,headers:d,signal:h}).catch(ba),S=ma();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 _=ma(),k={requestStartedAt:b,requestEndedAt:_,duration:_-b};return p.log("endRequest",Wr(k)),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,V=_=>{f==null||f.unsubscribe(),G=!0,ba(_)},D=fa(h,function(x){return te(this,arguments,function*({done:_,value:k}){if(I===0&&this.lastRequestFirstBytes$.next(ma()-b),h.aborted){f==null||f.unsubscribe();return}if(!_&&k){let B=new Uint8Array($.length+k.length);B.set($),B.set(k,$.length),$=B,I+=k.byteLength,i==null||i(new DataView($.buffer),I),yield y==null?void 0:y.read().then(D,V)}})}.bind(this));yield y==null?void 0:y.read().then(D,V),f==null||f.unsubscribe();let H=ma(),N={failed:G,requestStartedAt:b,requestEndedAt:H,duration:H-b};return G?(p.error("endRequest",Wr(N)),p.end(),null):(p.log("endRequest",Wr(N)),p.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=fa(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=fa(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=>M(A({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=iS(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:aS(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ba=a=>{if(!la(a))throw a};var ar=(a,e,t)=>t*e+(1-t)*a,cc=(a,e)=>a.reduce((t,r)=>t+r,0)/e,nS=(a,e,t,r)=>{let i=0,s=t,n=cc(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 SR,ValueSubject as oS}from"@vkontakte/videoplayer-shared";var $t=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 oS(e.initial),this.debounced$=new oS(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ue(`raw_${t}`),this.smoothedSeries$=new ue(`smoothed_${t}`),this.reportedSeries$=new ue(`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)&&(SR(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 en=class extends $t{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ar(this.slow,e,this.params.emaAlphaSlow),this.fast=ar(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var tn=class extends $t{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=cc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ar(this.emaSmoothed,e,this.params.emaAlpha);let r=nS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var rn=class extends $t{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?ar(this.smoothed,t,this.params.emaAlpha):t}};var sr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new en({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new tn({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 rn(A({initial:e,label:"liveEdgeDelay"},t))}};var lc=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as vR,ValueSubject as yR}from"@vkontakte/videoplayer-shared";var ga=class a{constructor(e,t){this.currentRepresentation$=new yR(null);this.currentSegment=null;this.currentSegmentId=0;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var i;if(vR(e))return;let t=null,r=null;for(let s of this.representations){let n=s.segmentReference.segments.find(o=>o.time.from<=e&&o.time.to>=e);if(n){t=n,r=s;break}}!t||!r||((i=this.currentSegment)==null?void 0:i.time.from)===t.time.from&&this.currentSegment.time.to===t.time.to||(this.currentSegment=t,this.currentSegmentId=(this.currentSegmentId+1)%Number.MAX_SAFE_INTEGER,this.currentRepresentation$.next(M(A({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(t.url,r.segmentReference.baseUrl).toString(),id:`subtitle-${this.currentSegmentId.toString(10)}`})))}destroy(){this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations=r;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ye(t.segmentReference))}};var hS=["timeupdate","progress","play","seeked","stalled","waiting"];var nn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new pS;this.representationSubscription=new pS;this.state$=new C("none");this.currentVideoRepresentation$=new se(void 0);this.currentVideoRepresentationInit$=new se(void 0);this.currentAudioRepresentation$=new se(void 0);this.currentVideoSegmentLength$=new se(0);this.currentAudioSegmentLength$=new se(0);this.error$=new dS;this.lastConnectionType$=new se(void 0);this.lastConnectionReused$=new se(void 0);this.lastRequestFirstBytes$=new se(void 0);this.currentLiveTextRepresentation$=new se(null);this.isLive$=new se(!1);this.liveDuration$=new se(0);this.liveAvailabilityStartTime$=new se(void 0);this.bufferLength$=new se(0);this.liveLoadBufferLength$=new se(0);this.livePositionFromPlayer$=new se(0);this.timeInWaiting=0;this.isActiveLowLatency$=new se(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new dS;this.gapWatchdogActive=!1;this.destroyController=new pt;this.initManifest=dc(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:Lt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=dc(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:Lt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Zg(e!=null?e:"",this.manifestUrlString)}catch(u){let c=(n=fg(e))!=null?n:{id:"ManifestParsing",category:Lt.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=ht())==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=hg(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);AR.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=M(A({},t),{streams:i});return this.tracer.log("updateManifestEnd",Sa(s)),s})}.bind(this));this.initRepresentations=dc(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})),nr(this.manifest),nr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Yr(p,"error").pipe(sn(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Lt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?zb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Fs())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new pa("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 pa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(ga.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new ga(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(pc(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=Tu(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Qr(...hS.filter(p=>p!=="waiting").map(p=>Yr(this.element,p))).pipe(hc(p=>this.element?lt(this.element.buffered,this.element.currentTime*1e3):0),cS(),sn(p=>!!p),ER(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(cS()).subscribe(h=>lc(this.element,1))),this.representationSubscription.add(an({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(sn(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(an({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),lc(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(an({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(xR(1e3)).subscribe(b=>R(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(nr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,S=Tu(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(),V=T<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLowLatency$.next(G&&V);let D="none";if(G?D="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&V?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(H=>H.proceedLowLatencyLive()),D="active_low_latency"):S!==0&&$<v?D="live_forward_buffering":$<v+I&&(D="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),D==="live_forward_buffering"||D==="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)}D!=="none"&&D!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=Qr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(hc(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Qr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(hc(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Qr(this.forceEnded$,an({allBuffersFull:u,someBufferEnded:c}).pipe(sn(({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:Lt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Qr(...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.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));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),Ye(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/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"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=pc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Lt.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Zs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=sr.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,A({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return R(this,null,function*(){var r,i,s,n,o;nr(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),(o=this.liveTextManager)==null||o.seekLive(this.manifest.streams.text))})}initBuffer(){nr(this.element),this.state$.setState("running"),this.subscription.add(Qr(...hS.map(e=>Yr(this.element,e)),Yr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Lt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Yr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Yr(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Ui(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=M(A({},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=M(A({},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=pc(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:Lt.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;nr(this.element),nr(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),Ui(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,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=M(A({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Sa(t)))}}};var on=class{constructor(e,t){this.fov=e,this.orientation=t}};var un=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=A({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*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 fS=`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 Ng=`#ifdef GL_ES
69
+ `;var mS=`#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 _s=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 Bs(this.params.fov,this.params.orientation),this.cameraRotationManager=new Vs(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(_g,this.gl.VERTEX_SHADER),r=this.createShader(Ng,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 Xt=class{constructor(e){this.subscription=new TR;this.videoState=new L("stopped");this.elementSize$=new IR(void 0);this.textTracksManager=new Me;this.droppedFramesManager=new hs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ls;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 hR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new _s(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(ie(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Os({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:zu.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(Fg(l=>!!l.length),Hg()).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(Fg(gR),Hg()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Ug(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Qe(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(Le(this.video,t.playbackRate,r.playbackRateState$,i)),s(yR(this.video),this.elementSize$),s(De(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(fR(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Nu(h));let f=[];for(let b of h.representations){let g=Eg(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 c.video){d.push(Fu(p));let h=[];for(let f of p.representations){let b=Ig(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=xg(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:zu.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(Ns(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$,bR(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(Ku()).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(Fu(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ku()).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(Nu(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(Ug(({to:l})=>l==="ready"),Ku());this.subscription.add(Ns(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(Ns(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Ns(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,vR(["init"])).pipe(mR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var C,$,V,G,N,R,F,_,P,x,D,Y,z,ee;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:H})=>H===i),o=t.currentVideoTrack$.getValue(),u=((G=(V=e.videoStream.getState())!=null?V:n&&(($=this.videoTracksMap.get(n))==null?void 0:$.stream))!=null?G:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:H})=>H===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=it(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(N=e.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(R=[...this.audioStreamsMap.keys()].find(({id:H})=>H===(f==null?void 0:f.id)))!=null?R:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let H=ws(n,c,(F=this.audioStreamsMap.get(b))!=null?F:[]);g=Math.max(g,(_=H==null?void 0:H.bitrate)!=null?_:-1/0)}if(o){let H=ws(o,c,(P=this.audioStreamsMap.get(b))!=null?P:[]);g=Math.max(g,(x=H==null?void 0:H.bitrate)!=null?x:-1/0)}}let S=yt(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:I}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(S=(D=c.filter(H=>!SR(H.quality)).sort((H,Zt)=>{var lt,q;return((lt=Zt.bitrate)!=null?lt:0)-((q=H.bitrate)!=null?q:0)}).filter(H=>qg(H.quality,S.quality)&&qg(H.quality,I))[0])!=null?D:S);let v=r?S!=null?S:n:n!=null?n:S,y=b&&ws(v,c,(Y=this.audioStreamsMap.get(b))!=null?Y:[]),T=(z=this.videoTracksMap.get(v))==null?void 0:z.representation,M=y&&((ee=this.audioTracksMap.get(y))==null?void 0:ee.representation);if(T&&M)return[T,M];if(T&&!M&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Se(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:zu.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 sa=class extends Xt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as jg,interval as ER,map as xR}from"@vkontakte/videoplayer-shared";var na=class extends Xt{constructor(e){super(e),this.liveOffset=new tt}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(jg({interval:ER(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:i})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(i-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(jg({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(xR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var Wg=We(ns(),1);import{assertNever as oa,assertNonNullable as Gg,debounce as PR,ErrorCategory as Fs,filter as AR,isNonNullable as wR,isNullable as kR,map as qs,merge as RR,Observable as $R,observableFrom as LR,Subscription as MR,videoSizeToQuality as CR}from"@vkontakte/videoplayer-shared";var He={};var Vr=(a,e)=>new $R(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),ua=class{constructor(e){this.subscription=new MR;this.videoState=new L("initializing");this.textTracksManager=new Me;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:oa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:oa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:oa(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:oa(e)}break;default:oa(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(ie(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:Fs.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Wg.default)(import("hls.js").then(i=>{e||(He.Hls=i.default,He.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Gg(He.Hls,"hls.js not loaded"),this.hls=new He.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Gg(He.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Fs.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=ge(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(Qe(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(Le(this.video,e.playbackRate,i.playbackRateState$,r)),s(De(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(qs(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Vr(this.hls,He.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Fs.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(Vr(this.hls,He.Events.MANIFEST_PARSED).pipe(qs(({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:CR({width:h,height:f});if(!b)return c;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}),c.push(S),c},[]))),t.availableVideoTracks$),s(Vr(this.hls,He.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(Vr(this.hls,He.Events.LEVEL_LOADING).pipe(qs(({url:l})=>ie(l))),t.hostname$),s(Vr(this.hls,He.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(mt(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=Vr(this.hls,He.Events.LEVEL_SWITCHED).pipe(qs(({level:l})=>n(this.hls.levels[l])));o.pipe(AR(wR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(mt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(kR(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=RR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,LR(["init"])).pipe(PR(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 k(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Se(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Fs.DOM,thrown:t})))||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0)}};var Yg="X-Playback-Duration",Ju=a=>k(void 0,null,function*(){var i;let e=yield at(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(Yg)?parseInt(e.headers.get(Yg),10):void 0});import{assertNever as NR,combine as FR,debounce as qR,ErrorCategory as Hs,filter as UR,filterChanged as HR,isNonNullable as zg,isNullable as js,map as Kg,merge as jR,observableFrom as GR,Subscription as WR,ValueSubject as el,VideoQuality as YR}from"@vkontakte/videoplayer-shared";var Zu=We(vo(),1);import{videoSizeToQuality as DR,getExponentialDelay as OR}from"@vkontakte/videoplayer-shared";var BR=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=DR({width:t,height:r})}return e!=null?e:null},VR=(a,e)=>{var s,n;let t=a.split(`
92
- `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,Zu.default)(l[1].split(",").map(I=>I.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=BR(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[I,v]=d.RESOLUTION.split("x").map(y=>parseInt(y,10));I&&v&&(g={width:I,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(c){let d=(0,Zu.default)(c[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}},_R=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Xu=0,Qg=(r,...i)=>k(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield at(a)).text();Xu+=1;try{let{qualityManifests:o,textTracks:u}=VR(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(Xu<=t.manifestRetryMaxCount)return yield _R(OR(Xu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Qg(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Us=Qg;var la=class{constructor(e){this.subscription=new WR;this.videoState=new L("stopped");this.textTracksManager=new Me;this.manifests$=new el([]);this.liveOffset=new tt;this.manifestStartTime$=new el(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 NR(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:YR.INVARIANT,url:this.params.source.url},Us(se(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:Hs.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Hs.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(ie(this.params.source.url)),this.maxSeekBackTime$=new el((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:Hs.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(Le(this.video,t.playbackRate,i.playbackRateState$,r)),s(De(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(HR(),Kg(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&zg(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(ie(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(FR({startTime:this.manifestStartTime$.pipe(UR(zg)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Kg(o=>o.map(({id:u,quality: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=jR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,GR(["init"])).pipe(qR(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(js(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=se(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Ju(n).then(l=>{var c;if(!js(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(js(d)||!isFinite(d))try{at(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();Ju(b).then(g=>{js(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){Se(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:Hs.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 zR,ErrorCategory as tl,fromEvent as rl,isNonNullable as KR,isNullable as JR,map as Jg,merge as Xg,observableFrom as Zg,Subscription as XR,ValueSubject as ZR,VideoQuality as e$,clientChecker as t$}from"@vkontakte/videoplayer-shared";var ca=class{constructor(e){this.subscription=new XR;this.videoState=new L("stopped");this.textTracksManager=new Me;this.manifests$=new ZR([]);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=fe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:e$.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(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Us(se(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:tl.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:tl.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(Jg(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Qe(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(Le(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&&KR(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(ie(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)}}}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(Jg(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)),!t$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Xg(rl(o,"addtrack"),rl(o,"removetrack"),rl(o,"change"),Zg(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Xg(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Zg(["init"])).pipe(zR(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(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(){Se(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:tl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as r$,assertNonNullable as eS,debounce as i$,ErrorCategory as tS,isHigher as a$,isHigherOrEqual as s$,isInvariantQuality as rS,isLowerOrEqual as n$,isNonNullable as o$,merge as u$,observableFrom as l$,Subscription as c$,map as d$}from"@vkontakte/videoplayer-shared";var da=class{constructor(e){this.subscription=new c$;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Me;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 r$(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:tS.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(d$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Qe(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(Le(this.video,t.playbackRate,i.playbackRateState$,r)),s(De(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&&o$(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=u$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,l$(["init"])).pipe(i$(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;eS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];eS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Zi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ie(t))}playIfAllowed(){Se(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!rS(d.track.quality)&&n$(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&&s$(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!rS(h.track.quality)&&a$(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=yt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as aS,debounce as m$,merge as sS,observableFrom as b$,Subscription as g$,map as nS,ValueSubject as S$,ErrorCategory as al,VideoQuality as v$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as p$}from"@vkontakte/videoplayer-shared";var iS=["stun:videostun.mycdn.me:80"],h$=1e3,f$=3,il=()=>null,Gs=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=il;this.externalStopCallback=il;this.externalErrorCallback=il;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 k(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 k(this,null,function*(){try{let e={iceServers:[{urls:iS}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=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 k(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return k(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:p$.WTF,message:e.message})}onPeerConnectionStream(e){return k(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 k(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),h$)}normalizeOptions(e={}){let t={stunServerList:iS,maxRetryNumber:f$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var pa=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new S$(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return aS(e)}};this.subscription=new g$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=fe(e.container,e.tuning),this.liveStreamClient=new Gs(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:al.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};sS(this.videoState.stateChangeStarted$.pipe(nS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(nS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=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(De(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 aS(n.to)}},r)).add(sS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,b$(["init"])).pipe(m$(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(ie(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:v$.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:al.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Se(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:al.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ha=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 ba,assertNonNullable as Et,ErrorCategory as Ys,filter as A$,isNonNullable as pS,isNullable as w$,map as k$,merge as R$,once as $$,Subject as Pe,Subscription as hS,ValueSubject as O,flattenObject as fS}from"@vkontakte/videoplayer-shared";import{Observable as y$,map as oS,Subscription as T$,Subject as I$}from"@vkontakte/videoplayer-shared";var uS=a=>new y$(e=>{let t=new T$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(oS(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(oS(({type:l})=>l!==void 0)),n=new I$,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 lS,Subscription as E$,combine as x$,filter as cS,once as dS}from"@vkontakte/videoplayer-shared";var fa=null,Ws=null;function sl(){return fa||(fa=new(window.AudioContext||window.webkitAudioContext)),Ws||(Ws=new GainNode(fa,{gain:1}),Ws.connect(fa.destination)),{audioCtx:fa,gainNode:Ws}}import{clientChecker as P$}from"@vkontakte/videoplayer-shared";var _r=class _r{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new E$;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe(cS(n=>!!n.type),dS()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){P$.isSafari&&e!=="MPEG"||this.subscriptions.add(x$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(cS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),dS()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:i}=sl(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${_r.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:_r.errorId,category:lS.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:_r.errorId,category:lS.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=sl();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};_r.errorId="VolumeMultiplierManager";var ma=_r;var L$={chunkDuration:5e3,maxParallelRequests:5},ga=class{constructor(e){this.current$=new O({type:void 0});this.providerError$=new Pe;this.noAvailableProvidersError$=new Pe;this.volumeMultiplierError$=new Pe;this.providerOutput={position$:new O(0),duration$:new O(1/0),volume$:new O({muted:!1,volume:1}),availableVideoStreams$:new O([]),currentVideoStream$:new O(void 0),availableVideoTracks$:new O([]),currentVideoTrack$:new O(void 0),availableAudioStreams$:new O([]),currentAudioStream$:new O(void 0),availableAudioTracks$:new O([]),currentVideoSegmentLength$:new O(0),currentAudioSegmentLength$:new O(0),isAudioAvailable$:new O(!0),autoVideoTrackLimitingAvailable$:new O(!1),autoVideoTrackLimits$:new O(void 0),currentBuffer$:new O(void 0),isBuffering$:new O(!0),error$:new Pe,warning$:new Pe,willSeekEvent$:new Pe,seekedEvent$:new Pe,loopedEvent$:new Pe,endedEvent$:new Pe,firstBytesEvent$:new Pe,loadedMetadataEvent$:new Pe,firstFrameEvent$:new Pe,canplay$:new Pe,isLive$:new O(void 0),isLowLatency$:new O(!1),canChangePlaybackSpeed$:new O(!0),liveTime$:new O(void 0),liveBufferTime$:new O(void 0),availableTextTracks$:new O([]),currentTextTrack$:new O(void 0),hostname$:new O(void 0),httpConnectionType$:new O(void 0),httpConnectionReused$:new O(void 0),inPiP$:new O(!1),inFullscreen$:new O(!1),element$:new O(void 0),elementVisible$:new O(!0),availableSources$:new O(void 0),is3DVideo$:new O(!1),playbackState$:new O("")};this.subscription=new hS;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Lb([...Cb(this.params.tuning),...Mb(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>pS(e.sources[u])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(u=>!i.includes(u)),...t.filter(u=>i.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",fS(s)),this.screenFormatsIterator=new ha(s);let n=[...xu(!0),...xu(!1)];this.chromecastFormatsIterator=new ha(n.filter(u=>pS(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new ma(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(w$(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Ys.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 ba(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 Et(o),new sa(B(w({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),new na(B(w({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Et(o),wr||!this.params.tuning.useHlsJs?new ca(B(w({},n),{source:o})):new ua(B(w({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),new la(B(w({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Et(o),new da(B(w({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new hb(B(w({},n),{source:o,config:B(w({},L$),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new pa({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 ba(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 Et(o),new fi({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 ba(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ba(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 ba(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 B(w({},e),{url:r(e.url)})}return(0,mS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new hS,t=!1,r=0;return e.add(R$(this.providerOutput.error$,uS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(k$(i=>({id:`ProviderHangup:${i}`,category:Ys.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(A$(({to:s})=>s==="playing"),$$()).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===Ys.NETWORK,u=i.category===Ys.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=B(w({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",fS(n))})),e}};import{fromEvent as Qs,once as M$,combine as C$,Subscription as bS,ValueSubject as nl,map as D$,filter as O$,isNonNullable as zs,now as Ae,safeStorage as ol}from"@vkontakte/videoplayer-shared";var B$=5e3,gS="one_video_throughput",SS="one_video_rtt",ot=window.navigator.connection,vS=()=>{let a=ot==null?void 0:ot.downlink;if(zs(a)&&a!==10)return a*1e3},yS=()=>{let a=ot==null?void 0:ot.rtt;if(zs(a)&&a!==3e3)return a},TS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},ul=class a{constructor(e){this.subscription=new bS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(gS)||(e.useBrowserEstimation?vS():void 0)||B$,r=(s=(i=a.load(SS))!=null?i:e.useBrowserEstimation?yS():void 0)!=null?s:0;if(this.throughput$=new nl(t),this.rtt$=new nl(r),this.rttAdjustedThroughput$=new nl(TS(t,r,e.rttPenaltyRequestSize)),this.throughput=Kt.getSmoothedValue(t,-1,e),this.rtt=Kt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=vS();u&&this.throughput.next(u);let l=yS();zs(l)&&this.rtt.next(l)};ot&&"onchange"in ot&&this.subscription.add(Qs(ot,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{ol.set(gS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{ol.set(SS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(C$({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(D$(({throughput:n,rtt:o})=>TS(n,o,e.rttPenaltyRequestSize)),O$(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=Ae(),i=new bS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Qs(e,"progress").pipe(M$()).subscribe(s=>{t=s.loaded,r=Ae()}));break;case 1:case 0:i.add(Qs(e,"loadstart").subscribe(()=>{t=0,r=Ae()}));break}i.add(Qs(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ae(),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=Ae(),n=0,o=Ae(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>k(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Ae()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Ae();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=Ae()}else n+=d.byteLength;o=Ae()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ae()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ae()-o,this.concurrentDownloads.size),n=0,o=Ae());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=ol.get(e);if(zs(t))return(r=parseInt(t,10))!=null?r:void 0}},IS=ul;import{fillWithDefault as V$,VideoQuality as ES}from"@vkontakte/videoplayer-shared";var xS={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:ES.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ES.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},PS=a=>{var e;return B(w({},V$(a,xS)),{configName:[...(e=a.configName)!=null?e:[],...xS.configName]})};import{assertNonNullable as Ks,combine as xt,ErrorCategory as Js,filter as le,filterChanged as j,fromEvent as cl,isNonNullable as j$,isNullable as G$,Logger as W$,map as U,mapTo as RS,merge as Pt,now as Xs,once as ut,Subject as Q,Subscription as $S,tap as LS,ValueSubject as A,isHigher as Y$,isInvariantQuality as MS,flattenObject as At,throttle as dl,getTraceSubscriptionMethod as CS}from"@vkontakte/videoplayer-shared";import{merge as _$,map as N$,filter as AS,isNonNullable as F$}from"@vkontakte/videoplayer-shared";var ll=({seekState:a,position$:e})=>_$(a.stateChangeEnded$.pipe(N$(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),AS(F$)),e.pipe(AS(()=>a.getState().state==="none")));import{assertNonNullable as q$}from"@vkontakte/videoplayer-shared";var wS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return q$(e,`Wrong container or containerId {${a.container}}`),e};import{filter as U$,once as H$}from"@vkontakte/videoplayer-shared";var kS=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(U$(i=>i.length>0),H$()).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:[]},t){this.subscription=new $S;this.logger=new W$;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new A(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new A("stopped"),position$:new A(0),duration$:new A(1/0),muted$:new A(!1),volume$:new A(1),availableVideoStreams$:new A([]),currentVideoStream$:new A(void 0),availableQualities$:new A([]),availableQualitiesFps$:new A({}),currentQuality$:new A(void 0),isAutoQualityEnabled$:new A(!0),autoQualityLimitingAvailable$:new A(!1),autoQualityLimits$:new A({}),availableAudioStreams$:new A([]),currentAudioStream$:new A(void 0),availableAudioTracks$:new A([]),isAudioAvailable$:new A(!0),currentPlaybackRate$:new A(1),currentBuffer$:new A({start:0,end:0}),isBuffering$:new A(!0),isStalled$:new A(!1),isEnded$:new A(!1),isLooped$:new A(!1),isLive$:new A(void 0),canChangePlaybackSpeed$:new A(void 0),atLiveEdge$:new A(void 0),atLiveDurationEdge$:new A(void 0),liveTime$:new A(void 0),liveBufferTime$:new A(void 0),currentFormat$:new A(void 0),availableTextTracks$:new A([]),currentTextTrack$:new A(void 0),throughputEstimation$:new A(void 0),rttEstimation$:new A(void 0),videoBitrate$:new A(void 0),hostname$:new A(void 0),httpConnectionType$:new A(void 0),httpConnectionReused$:new A(void 0),surface$:new A("none"),chromecastState$:new A("NOT_AVAILABLE"),chromecastDeviceName$:new A(void 0),intrinsicVideoSize$:new A(void 0),availableSources$:new A(void 0),is3DVideo$:new A(!1),currentVideoSegmentLength$:new A(0),currentAudioSegmentLength$:new A(0)};this.events={inited$:new Q,ready$:new Q,started$:new Q,playing$:new Q,paused$:new Q,stopped$:new Q,willStart$:new Q,willResume$:new Q,willPause$:new Q,willStop$:new Q,willDestruct$:new Q,watchCoverageRecord$:new Q,watchCoverageLive$:new Q,managedError$:new Q,fatalError$:new Q,ended$:new Q,looped$:new Q,seeked$:new Q,willSeek$:new Q,firstBytes$:new Q,loadedMetadata$:new Q,firstFrame$:new Q,canplay$:new Q,log$:new Q};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:Zm};if(this.initLogs(),this.tuning=PS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Pa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new IS(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Js.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var t,r,i;return this.config=e,this.tracer.log("initVideo",At(e)),this.domContainer=wS(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new ga({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&&!Ei()?(this.tracer.log("request play from hidden tab"),cl(document,"visibilitychange").pipe(ut()).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){Ks(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(le(r=>r.length>0),ut()).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",At(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Ks(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",At(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>w({type:"external"},t))),this}selectTextTrack(e){var t;return kS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",w({},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(G$(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return j$(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(Pt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(U(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(le(({from:e})=>e==="stopped"),ut()).subscribe(()=>{this.initedAt=Xs(),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",At(n)),n.state==="requested"?this.desiredState.seekState.setState(B(w({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Js.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",At(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(U(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(U(n=>n.destination),j()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(U(n=>n.map(({quality:o})=>o).sort((o,u)=>MS(o)?1:MS(u)?-1:Y$(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(j()).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(j((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(j((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(j()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(j()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(j()).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(U(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(xt({hasLiveOffsetByPaused:Pt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(U(n=>n.to),j(),U(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(xt({atLiveEdge:xt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:ll({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(U(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),j(),LS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(U(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(xt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(U(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),j(),LS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(U(n=>n.muted),j()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(U(n=>n.volume),j()).subscribe(this.info.volume$)).add(ll({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Pt(e.providerOutput.endedEvent$.pipe(RS(!0)),e.providerOutput.seekedEvent$.pipe(RS(!1))).pipe(j()).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(U(n=>({id:n?`No${n}`:"NoProviders",category:Js.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(ut(),U(n=>n!=null?n:Xs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ut(),U(()=>Xs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ut(),U(()=>Xs()-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 A(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new A(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(le(({to:n})=>n==="playing"),ut()).subscribe(()=>r.next(!1)));let i=0,s=Pt(e.providerOutput.isBuffering$,t,r).pipe(U(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),j());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(Pt(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(Pt(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(U(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(j((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(le(r=>r.length>0),ut()).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=yt(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(Pt(this.desiredState.videoTrack.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(U(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;Ks(this.providerContainer),Ks(e),Xm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Jm(r)),this.providerContainer.current$.subscribe(({type:r})=>Si("provider",r)),e.duration$.subscribe(r=>Si("duration",r)),e.availableVideoTracks$.pipe(le(r=>!!r.length),ut()).subscribe(r=>Si("tracks",r)),this.events.fatalError$.subscribe(new oe("fatalError")),this.events.managedError$.subscribe(new oe("managedError")),e.position$.subscribe(new oe("position")),e.currentVideoTrack$.pipe(U(r=>r==null?void 0:r.quality)).subscribe(new oe("quality")),this.info.currentBuffer$.subscribe(new oe("buffer")),e.isBuffering$.subscribe(new oe("isBuffering"))].forEach(r=>this.subscription.add(r)),Si("codecs",$b())}initTracerSubscription(){let e=CS(this.tracer.log.bind(this.tracer)),t=CS(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(j()).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(xt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(le(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),j((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(le(r=>r>0),j()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(le(r=>r>0),j()).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(xt({currentBuffer:this.info.currentBuffer$.pipe(le(r=>r.end>0),j((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(j())}).pipe(dl(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(j()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(j()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(j()).subscribe(e("canChangePlaybackSpeed"))).add(xt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(le(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),dl(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(j(),le(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(j(),le(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(j()).subscribe(e("muted"))).add(this.info.volume$.pipe(j()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(j(),le(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(xt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(le(({throughputEstimation:r,rtt:i})=>!!r&&!!i),dl(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(j(),le(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=()=>k(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:Js.DOM,message:String(i)})})});this.subscription.add(Pt(cl(document,"visibilitychange"),cl(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",At({quality:t,availableTracks:At(e),track:At(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 JG,Observable as XG,Subject as ZG,ValueSubject as eW,VideoQuality as tW}from"@vkontakte/videoplayer-shared";var rW=`@vkontakte/videoplayer-core@${Nl}`;export{Ea as ChromecastState,mn as HttpConnectionType,XG as Observable,pe as PlaybackState,Zs as Player,rW as SDK_VERSION,ZG as Subject,JG as Subscription,bn as Surface,Nl as VERSION,eW as ValueSubject,ht as VideoFormat,tW as VideoQuality};
112
+ `;var cn=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 on(this.params.fov,this.params.orientation),this.cameraRotationManager=new un(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(fS,this.gl.VERTEX_SHADER),r=this.createShader(mS,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 or=class{constructor(e){this.subscription=new _R;this.videoState=new C("stopped");this.elementSize$=new NR(void 0);this.textTracksManager=new Be;this.droppedFramesManager=new Os;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Mi;this.audioTrackSwitchHistory=new Mi;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let c=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-c,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&E(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return LR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new cn(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=me(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new nn({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=Se(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:fc.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(c=>!!c.length),SS()).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(bS(BR),SS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(gS(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(et(this.video,t.isLooped,i)),this.subscription.add(ge(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(VR(this.video),this.elementSize$),s(Ve(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(MR(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of l.audio){p.push(ic(h));let f=[];for(let b of h.representations){let g=tS(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(ac(p));let h=[];for(let f of p.representations){let b=eS(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=Js(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:fc.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(ln(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$,DR(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(mc()).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(ac(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(mc()).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(ic(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(gS(({to:c})=>c==="ready"),mc());this.subscription.add(ln(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(ln(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ln(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,OR(["init"])).pipe(CR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var $,G,V,D,H,N,L,F,_,k,x,B,W,z,Z,le,Ot,gt;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:w})=>w===i),o=t.currentVideoTrack$.getValue(),u=((D=(V=e.videoStream.getState())!=null?V:n&&((G=this.videoTracksMap.get(n))==null?void 0:G.stream))!=null?D:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let c=[...this.videoStreamsMap.keys()].find(({id:w})=>w===u.id),l=c&&this.videoStreamsMap.get(c);if(!l)return;let d=lt(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:w})=>w===(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 w=Ms(n,l,(L=this.audioStreamsMap.get(b))!=null?L:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(F=w==null?void 0:w.bitrate)!=null?F:-1/0)}else{let w=Ks(n,l,(_=this.audioStreamsMap.get(b))!=null?_:[]);g=Math.max(g,(k=w==null?void 0:w.bitrate)!=null?k:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let w=Ms(o,l,(x=this.audioStreamsMap.get(b))!=null?x:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(B=w==null?void 0:w.bitrate)!=null?B:-1/0)}else{let w=Ks(o,l,(W=this.audioStreamsMap.get(b))!=null?W:[]);g=Math.max(g,(z=w==null?void 0:w.bitrate)!=null?z:-1/0)}}let S=Rt(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&&Bb(T,l,(Z=this.audioStreamsMap.get(b))!=null?Z:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):v=b&&Ks(T,l,(le=this.audioStreamsMap.get(b))!=null?le:[]);let y=(Ot=this.videoTracksMap.get(T))==null?void 0:Ot.representation,I=v&&((gt=this.audioTracksMap.get(v))==null?void 0:gt.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(){ye(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:fc.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),be(this.video),this.tracer.end()}};var ya=class extends or{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 vS,interval as FR,map as qR}from"@vkontakte/videoplayer-shared";var Ta=class extends or{constructor(e){super(e),this.liveOffset=new ut}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.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(vS({interval:FR(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:i})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(i-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(vS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(qR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(i=>{if(i){let s=Js(i,i);this.params.desiredState.internalTextTracks.startTransitionTo([s])}else this.params.desiredState.internalTextTracks.startTransitionTo([])}))}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 TS=Xe(Rs(),1);import{assertNever as Ia,assertNonNullable as yS,debounce as UR,ErrorCategory as dn,filter as HR,isNonNullable as jR,isNullable as GR,map as pn,merge as WR,Observable as YR,observableFrom as QR,Subscription as zR,videoSizeToQuality as KR}from"@vkontakte/videoplayer-shared";var Qe={};var zr=(a,e)=>new YR(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ea=class{constructor(e){this.subscription=new zR;this.videoState=new C("initializing");this.textTracksManager=new Be;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:Ia(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ia(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ia(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:Ia(e)}break;default:Ia(t)}};this.video=me(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(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),be(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:dn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,TS.default)(import("hls.js").then(i=>{e||(Qe.Hls=i.default,Qe.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){yS(Qe.Hls,"hls.js not loaded"),this.hls=new Qe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){yS(Qe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=c=>{t.error$.next({id:"HlsJsProvider",category:dn.WTF,message:"HlsJsProvider internal logic error",thrown:c})},i=Se(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(et(this.video,e.isLooped,r)),this.subscription.add(ge(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(De(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ve(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(pn(c=>c.to)),this.params.output.playbackState$),this.subscription.add(zr(this.hls,Qe.Events.ERROR).subscribe(c=>{var l;c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:dn.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(zr(this.hls,Qe.Events.MANIFEST_PARSED).pipe(pn(({levels:c})=>c.reduce((l,d)=>{var T,v;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(v=kt((T=d.attrs.QUALITY)!=null?T:""))!=null?v:KR({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(zr(this.hls,Qe.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(zr(this.hls,Qe.Events.LEVEL_LOADING).pipe(pn(({url:c})=>re(c))),t.hostname$),s(zr(this.hls,Qe.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(At(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=zr(this.hls,Qe.Events.LEVEL_SWITCHED).pipe(pn(({level:c})=>n(this.hls.levels[c])));o.pipe(HR(jR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(At(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),c=>{var f;if(GR(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=WR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,QR(["init"])).pipe(UR(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 ye(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:dn.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 IS="X-Playback-Duration",bc=a=>R(void 0,null,function*(){var i;let e=yield dt(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(IS)?parseInt(e.headers.get(IS),10):void 0});import{assertNever as r$,combine as i$,debounce as a$,ErrorCategory as fn,filter as s$,filterChanged as n$,isNonNullable as xS,isNullable as mn,map as AS,merge as o$,observableFrom as u$,Subscription as c$,ValueSubject as vc,VideoQuality as l$}from"@vkontakte/videoplayer-shared";var Sc=Xe(Oo(),1);import{videoSizeToQuality as JR,getExponentialDelay as XR}from"@vkontakte/videoplayer-shared";var ZR=a=>{let e=null;if(a.QUALITY&&(e=kt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=JR({width:t,height:r})}return e!=null?e:null},e$=(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,Sc.default)(c[1].split(",").map(T=>T.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=ZR(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,Sc.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}},t$=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),gc=0,ES=(r,...i)=>R(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield dt(a)).text();gc+=1;try{let{qualityManifests:o,textTracks:u}=e$(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(gc<=t.manifestRetryMaxCount)return yield t$(XR(gc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),ES(a,e,t)}return{qualityManifests:[],textTracks:[]}}),hn=ES;var xa=class{constructor(e){this.subscription=new c$;this.videoState=new C("stopped");this.textTracksManager=new Be;this.manifests$=new vc([]);this.liveOffset=new ut;this.manifestStartTime$=new vc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return r$(t)}};var t;this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:l$.INVARIANT,url:this.params.source.url},hn(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:fn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:fn.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 vc((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:fn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Se(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(ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ve(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(n$(),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&&xS(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(i$({startTime:this.manifestStartTime$.pipe(s$(xS)),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=o$(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,u$(["init"])).pipe(a$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),be(this.video)}prepare(){var o,u;let e=this.selectManifest();if(mn(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(),bc(n).then(c=>{var l;if(!mn(c))this.maxSeekBackTime$.next(c);else{let d=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();if(mn(d)||!isFinite(d))try{dt(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();bc(b).then(g=>{mn(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){ye(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:fn.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 d$,debounce as p$,ErrorCategory as yc,fromEvent as Tc,isNonNullable as h$,isNullable as f$,map as PS,merge as wS,observableFrom as kS,Subscription as m$,ValueSubject as b$,VideoQuality as g$,clientChecker as S$}from"@vkontakte/videoplayer-shared";var Aa=class{constructor(e){this.subscription=new m$;this.videoState=new C("stopped");this.textTracksManager=new Be;this.manifests$=new b$([]);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 d$(t)}};this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:g$.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),hn(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:yc.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:yc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Se(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(PS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(et(this.video,t.isLooped,r)),this.subscription.add(ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(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&&h$(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(PS(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)),!S$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(wS(Tc(o,"addtrack"),Tc(o,"removetrack"),Tc(o,"change"),kS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=wS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,kS(["init"])).pipe(p$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),be(this.video)}prepare(){var s,n;let e=this.selectManifest();if(f$(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(){ye(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:yc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as v$,assertNonNullable as RS,debounce as y$,ErrorCategory as $S,isHigher as T$,isHigherOrEqual as I$,isInvariantQuality as LS,isLowerOrEqual as E$,isNonNullable as x$,merge as A$,observableFrom as P$,Subscription as w$,map as k$}from"@vkontakte/videoplayer-shared";var Pa=class{constructor(e){this.subscription=new w$;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Be;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 v$(e)}};this.params=e,this.video=me(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:$S.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Se(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(k$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(et(this.video,t.isLooped,r)),this.subscription.add(ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ve(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&&x$(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=A$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,P$(["init"])).pipe(y$(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),be(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;RS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];RS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ha(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(re(t))}playIfAllowed(){ye(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:$S.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)&&E$(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&&I$(l.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!LS(h.track.quality)&&T$(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=Rt(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 CS,debounce as M$,merge as DS,observableFrom as C$,Subscription as D$,map as BS,ValueSubject as B$,ErrorCategory as Ec,VideoQuality as O$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as R$}from"@vkontakte/videoplayer-shared";var MS=["stun:videostun.mycdn.me:80"],$$=1e3,L$=3,Ic=()=>null,bn=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=Ic;this.externalStopCallback=Ic;this.externalErrorCallback=Ic;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:MS}]};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:R$.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),$$)}normalizeOptions(e={}){let t={stunServerList:MS,maxRetryNumber:L$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var wa=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new B$(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 CS(e)}};this.subscription=new D$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=me(e.container,e.tuning),this.liveStreamClient=new bn(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),be(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ec.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};DS(this.videoState.stateChangeStarted$.pipe(BS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(BS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Se(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(Ve(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(ge(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 CS(n.to)}},r)).add(DS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,C$(["init"])).pipe(M$(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:O$.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:Ec.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ye(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:Ec.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ka=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 La,assertNonNullable as Mt,ErrorCategory as Sn,filter as H$,isNonNullable as qS,isNullable as j$,map as G$,merge as W$,once as Y$,Subject as we,Subscription as US,ValueSubject as O,flattenObject as HS}from"@vkontakte/videoplayer-shared";import{Observable as V$,map as OS,Subscription as _$,Subject as N$}from"@vkontakte/videoplayer-shared";var VS=a=>new V$(e=>{let t=new _$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(OS(({from:c,to:l})=>`${c}-${l}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(OS(({type:c})=>c!==void 0)),n=new N$,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 _S,Subscription as F$,combine as q$,filter as NS,once as FS}from"@vkontakte/videoplayer-shared";var Ra=null,gn=null;function xc(){return Ra||(Ra=new(window.AudioContext||window.webkitAudioContext)),gn||(gn=new GainNode(Ra,{gain:1}),gn.connect(Ra.destination)),{audioCtx:Ra,gainNode:gn}}import{clientChecker as U$}from"@vkontakte/videoplayer-shared";var Kr=class Kr{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new F$;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe(NS(n=>!!n.type),FS()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){U$.isSafari&&e!=="MPEG"||this.subscriptions.add(q$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(NS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),FS()).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}=xc(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Kr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Kr.errorId,category:_S.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:Kr.errorId,category:_S.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=xc();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Kr.errorId="VolumeMultiplierManager";var $a=Kr;var Q$={chunkDuration:5e3,maxParallelRequests:5},Ma=class{constructor(e){this.current$=new O({type:void 0});this.providerError$=new we;this.noAvailableProvidersError$=new we;this.volumeMultiplierError$=new we;this.providerOutput={position$:new O(0),duration$:new O(1/0),volume$:new O({muted:!1,volume:1}),availableVideoStreams$:new O([]),currentVideoStream$:new O(void 0),availableVideoTracks$:new O([]),currentVideoTrack$:new O(void 0),availableAudioStreams$:new O([]),currentAudioStream$:new O(void 0),availableAudioTracks$:new O([]),currentVideoSegmentLength$:new O(0),currentAudioSegmentLength$:new O(0),isAudioAvailable$:new O(!0),autoVideoTrackLimitingAvailable$:new O(!1),autoVideoTrackLimits$:new O(void 0),currentBuffer$:new O(void 0),isBuffering$:new O(!0),error$:new we,warning$:new we,willSeekEvent$:new we,seekedEvent$:new we,loopedEvent$:new we,endedEvent$:new we,firstBytesEvent$:new we,loadedMetadataEvent$:new we,firstFrameEvent$:new we,canplay$:new we,isLive$:new O(void 0),isLowLatency$:new O(!1),canChangePlaybackSpeed$:new O(!0),liveTime$:new O(void 0),liveBufferTime$:new O(void 0),availableTextTracks$:new O([]),currentTextTrack$:new O(void 0),hostname$:new O(void 0),httpConnectionType$:new O(void 0),httpConnectionReused$:new O(void 0),inPiP$:new O(!1),inFullscreen$:new O(!1),element$:new O(void 0),elementVisible$:new O(!0),availableSources$:new O(void 0),is3DVideo$:new O(!1),playbackState$:new O("")};this.subscription=new US;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=lg([...pg(this.params.tuning),...dg(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>qS(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",HS(s)),this.screenFormatsIterator=new ka(s);let n=[...qu(!0),...qu(!1)];this.chromecastFormatsIterator=new ka(n.filter(u=>qS(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new $a(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(j$(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Sn.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 La(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 Mt(o),new ya(M(A({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Ta(M(A({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Mt(o),Nr||!this.params.tuning.useHlsJs?new Aa(M(A({},n),{source:o})):new Ea(M(A({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Mt(o),new xa(M(A({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Pa(M(A({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Wb(M(A({},n),{source:o,config:M(A({},Q$),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Mt(o),new wa({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return La(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 Mt(o),new wi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return La(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return La(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 La(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 M(A({},e),{url:r(e.url)})}return(0,jS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new US,t=!1,r=0;return e.add(W$(this.providerOutput.error$,VS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(G$(i=>({id:`ProviderHangup:${i}`,category:Sn.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(H$(({to:s})=>s==="playing"),Y$()).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===Sn.NETWORK,u=i.category===Sn.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=M(A({},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",HS(n))})),e}};import{fromEvent as vn,once as z$,combine as K$,Subscription as GS,ValueSubject as Ac,map as J$,filter as X$,isNonNullable as yn,now as ke,safeStorage as Pc}from"@vkontakte/videoplayer-shared";var Z$=5e3,WS="one_video_throughput",YS="one_video_rtt",mt=window.navigator.connection,QS=()=>{let a=mt==null?void 0:mt.downlink;if(yn(a)&&a!==10)return a*1e3},zS=()=>{let a=mt==null?void 0:mt.rtt;if(yn(a)&&a!==3e3)return a},KS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},wc=class a{constructor(e){this.subscription=new GS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(WS)||(e.useBrowserEstimation?QS():void 0)||Z$,r=(s=(i=a.load(YS))!=null?i:e.useBrowserEstimation?zS():void 0)!=null?s:0;if(this.throughput$=new Ac(t),this.rtt$=new Ac(r),this.rttAdjustedThroughput$=new Ac(KS(t,r,e.rttPenaltyRequestSize)),this.throughput=sr.getSmoothedValue(t,-1,e),this.rtt=sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=QS();u&&this.throughput.next(u);let c=zS();yn(c)&&this.rtt.next(c)};mt&&"onchange"in mt&&this.subscription.add(vn(mt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Pc.set(WS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Pc.set(YS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(K$({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(J$(({throughput:n,rtt:o})=>KS(n,o,e.rttPenaltyRequestSize)),X$(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=ke(),i=new GS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(vn(e,"progress").pipe(z$()).subscribe(s=>{t=s.loaded,r=ke()}));break;case 1:case 0:i.add(vn(e,"loadstart").subscribe(()=>{t=0,r=ke()}));break}i.add(vn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=ke(),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=ke(),n=0,o=ke(),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,ke()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=ke();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=ke()}else n+=d.byteLength;o=ke()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ke()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ke()-o,this.concurrentDownloads.size),n=0,o=ke());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=Pc.get(e);if(yn(t))return(r=parseInt(t,10))!=null?r:void 0}},JS=wc;import{fillWithDefault as eL,VideoQuality as XS}from"@vkontakte/videoplayer-shared";var ZS={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:XS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:XS.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},ev=a=>{var e;return M(A({},eL(a,ZS)),{configName:[...(e=a.configName)!=null?e:[],...ZS.configName]})};import{assertNonNullable as Tn,combine as Ct,ErrorCategory as In,filter as ce,filterChanged as U,fromEvent as Rc,isNonNullable as oL,isNullable as uL,Logger as cL,map as q,mapTo as av,merge as Dt,now as En,once as bt,Subject as Q,Subscription as sv,tap as nv,ValueSubject as P,isHigher as lL,isInvariantQuality as ov,flattenObject as Bt,throttle as $c,getTraceSubscriptionMethod as uv,Tracer as dL}from"@vkontakte/videoplayer-shared";import{merge as tL,map as rL,filter as tv,isNonNullable as iL}from"@vkontakte/videoplayer-shared";var kc=({seekState:a,position$:e})=>tL(a.stateChangeEnded$.pipe(rL(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),tv(iL)),e.pipe(tv(()=>a.getState().state==="none")));import{assertNonNullable as aL}from"@vkontakte/videoplayer-shared";var rv=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return aL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as sL,once as nL}from"@vkontakte/videoplayer-shared";var iv=(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(sL(i=>i.length>0),nL()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var xn=class{constructor(e={configName:[]},t=dL.createRootTracer(!1)){this.subscription=new sv;this.logger=new cL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({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 Q,ready$:new Q,started$:new Q,playing$:new Q,paused$:new Q,stopped$:new Q,willStart$:new Q,willResume$:new Q,willPause$:new Q,willStop$:new Q,willDestruct$:new Q,watchCoverageRecord$:new Q,watchCoverageLive$:new Q,managedError$:new Q,fatalError$:new Q,ended$:new Q,looped$:new Q,seeked$:new Q,willSeek$:new Q,firstBytes$:new Q,loadedMetadata$:new Q,firstFrame$:new Q,canplay$:new Q,log$:new Q};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Ab};if(this.initLogs(),this.tuning=ev(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Qa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new JS(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:In.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o;this.config=e;let i=e,{container:t}=i,r=ll(i,["container"]);return this.tracer.log("initVideo",Bt(r)),this.domContainer=rv(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new Ma({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.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&&!Vi()?(this.tracer.log("request play from hidden tab"),Rc(document,"visibilitychange").pipe(bt()).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){Tn(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(ce(r=>r.length>0),bt()).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",Bt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Tn(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",Bt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>A({type:"external"},t))),this}selectTextTrack(e){var t;return iv(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",A({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}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(uL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return oL(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(Dt(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(ce(({from:e})=>e==="stopped"),bt()).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",Bt(n)),n.state==="requested"?this.desiredState.seekState.setState(M(A({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:In.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Bt(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)=>ov(o)?1:ov(u)?-1:lL(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(Ct({hasLiveOffsetByPaused:Dt(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(Ct({atLiveEdge:Ct({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:kc({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(),nv(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(q(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ct({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(),nv(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(kc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Dt(e.providerOutput.endedEvent$.pipe(av(!0)),e.providerOutput.seekedEvent$.pipe(av(!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:In.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(bt(),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(bt(),q(()=>En()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(bt(),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(ce(({to:n})=>n==="playing"),bt()).subscribe(()=>r.next(!1)));let i=0,s=Dt(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(Dt(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(Dt(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 sv;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(ce(r=>r.length>0),bt()).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=Rt(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(Dt(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;Tn(this.providerContainer),Tn(e),xb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Eb(r)),this.providerContainer.current$.subscribe(({type:r})=>Li("provider",r)),e.duration$.subscribe(r=>Li("duration",r)),e.availableVideoTracks$.pipe(ce(r=>!!r.length),bt()).subscribe(r=>Li("tracks",r)),this.events.fatalError$.subscribe(new ue("fatalError")),this.events.managedError$.subscribe(new ue("managedError")),e.position$.subscribe(new ue("position")),e.currentVideoTrack$.pipe(q(r=>r==null?void 0:r.quality)).subscribe(new ue("quality")),this.info.currentBuffer$.subscribe(new ue("buffer")),e.isBuffering$.subscribe(new ue("isBuffering"))].forEach(r=>this.subscription.add(r)),Li("codecs",cg())}initTracerSubscription(){let e=uv(this.tracer.log.bind(this.tracer)),t=uv(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(Ct({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ce(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),U((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ce(r=>r>0),U()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ce(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(Ct({currentBuffer:this.info.currentBuffer$.pipe(ce(r=>r.end>0),U((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(U())}).pipe($c(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(Ct({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ce(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),$c(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(U(),ce(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(U(),ce(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(),ce(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ct({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ce(({throughputEstimation:r,rtt:i})=>!!r&&!!i),$c(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(U(),ce(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:In.DOM,message:String(i)})})});this.subscription.add(Dt(Rc(document,"visibilitychange"),Rc(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",Bt({quality:t,availableTracks:Bt(e),track:Bt(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 CW,Observable as DW,Subject as BW,ValueSubject as OW,VideoQuality as VW}from"@vkontakte/videoplayer-shared";var _W=`@vkontakte/videoplayer-core@${dl}`;export{Wa as ChromecastState,Mn as HttpConnectionType,DW as Observable,he as PlaybackState,xn as Player,_W as SDK_VERSION,BW as Subject,CW as Subscription,Cn as Surface,dl as VERSION,OW as ValueSubject,Et as VideoFormat,VW as VideoQuality};