@vkontakte/videoplayer-core 2.0.111-dev.974e99b3.0 → 2.0.111-dev.ae3e5b42.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,18 +1,18 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.111-dev.974e99b3.0
3
- * Thu, 19 Sep 2024 08:04:36 GMT
2
+ * @vkontakte/videoplayer-core v2.0.111-dev.ae3e5b42.0
3
+ * Wed, 02 Oct 2024 09:38:29 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-111/doc/
5
5
  */
6
- var pv=Object.create;var gn=Object.defineProperty,hv=Object.defineProperties,fv=Object.getOwnPropertyDescriptor,mv=Object.getOwnPropertyDescriptors,bv=Object.getOwnPropertyNames,Pa=Object.getOwnPropertySymbols,gv=Object.getPrototypeOf,Sn=Object.prototype.hasOwnProperty,Hc=Object.prototype.propertyIsEnumerable;var Sv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var Ye=Math.pow,Uc=(a,e,t)=>e in a?gn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,k=(a,e)=>{for(var t in e||(e={}))Sn.call(e,t)&&Uc(a,t,e[t]);if(Pa)for(var t of Pa(e))Hc.call(e,t)&&Uc(a,t,e[t]);return a},V=(a,e)=>hv(a,mv(e));var jc=(a,e)=>{var t={};for(var r in a)Sn.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&Pa)for(var r of Pa(a))e.indexOf(r)<0&&Hc.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var vv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of bv(e))!Sn.call(a,i)&&i!==t&&gn(a,i,{get:()=>e[i],enumerable:!(r=fv(e,i))||r.enumerable});return a};var Qe=(a,e,t)=>(t=a!=null?pv(gv(a)):{},vv(e||!a||!a.__esModule?gn(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())}),vn=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 vn,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[Sv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var Ee=m((hL,Xc)=>{"use strict";Xc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Wr=m((fL,Zc)=>{"use strict";var wv=Ee();Zc.exports=!wv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var he=m((mL,rl)=>{"use strict";var el=Wr(),tl=Function.prototype,xn=tl.call,kv=el&&tl.bind.bind(xn,xn);rl.exports=el?kv:function(a){return function(){return xn.apply(a,arguments)}}});var nr=m((bL,al)=>{"use strict";var il=he(),Rv=il({}.toString),$v=il("".slice);al.exports=function(a){return $v(Rv(a),8,-1)}});var nl=m((gL,sl)=>{"use strict";var Lv=he(),Mv=Ee(),Cv=nr(),Pn=Object,Dv=Lv("".split);sl.exports=Mv(function(){return!Pn("z").propertyIsEnumerable(0)})?function(a){return Cv(a)==="String"?Dv(a,""):Pn(a)}:Pn});var or=m((SL,ol)=>{"use strict";ol.exports=function(a){return a==null}});var Yr=m((vL,ul)=>{"use strict";var Bv=or(),Ov=TypeError;ul.exports=function(a){if(Bv(a))throw new Ov("Can't call method on "+a);return a}});var ur=m((yL,cl)=>{"use strict";var Vv=nl(),_v=Yr();cl.exports=function(a){return Vv(_v(a))}});var An=m((TL,ll)=>{"use strict";ll.exports=function(){}});var Bt=m((IL,dl)=>{"use strict";dl.exports={}});var K=m((wn,pl)=>{"use strict";var Qr=function(a){return a&&a.Math===Math&&a};pl.exports=Qr(typeof globalThis=="object"&&globalThis)||Qr(typeof window=="object"&&window)||Qr(typeof self=="object"&&self)||Qr(typeof global=="object"&&global)||Qr(typeof wn=="object"&&wn)||function(){return this}()||Function("return this")()});var z=m((EL,hl)=>{"use strict";var kn=typeof document=="object"&&document.all;hl.exports=typeof kn=="undefined"&&kn!==void 0?function(a){return typeof a=="function"||a===kn}:function(a){return typeof a=="function"}});var bl=m((xL,ml)=>{"use strict";var Nv=K(),Fv=z(),fl=Nv.WeakMap;ml.exports=Fv(fl)&&/native code/.test(String(fl))});var Re=m((PL,gl)=>{"use strict";var qv=z();gl.exports=function(a){return typeof a=="object"?a!==null:qv(a)}});var $e=m((AL,Sl)=>{"use strict";var Uv=Ee();Sl.exports=!Uv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ra=m((wL,yl)=>{"use strict";var Hv=K(),vl=Re(),Rn=Hv.document,jv=vl(Rn)&&vl(Rn.createElement);yl.exports=function(a){return jv?Rn.createElement(a):{}}});var $n=m((kL,Tl)=>{"use strict";var Gv=$e(),Wv=Ee(),Yv=Ra();Tl.exports=!Gv&&!Wv(function(){return Object.defineProperty(Yv("div"),"a",{get:function(){return 7}}).a!==7})});var Ln=m((RL,Il)=>{"use strict";var Qv=$e(),zv=Ee();Il.exports=Qv&&zv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ze=m(($L,El)=>{"use strict";var Kv=Re(),Jv=String,Xv=TypeError;El.exports=function(a){if(Kv(a))return a;throw new Xv(Jv(a)+" is not an object")}});var xe=m((LL,xl)=>{"use strict";var Zv=Wr(),$a=Function.prototype.call;xl.exports=Zv?$a.bind($a):function(){return $a.apply($a,arguments)}});var La=m((ML,Pl)=>{"use strict";Pl.exports={}});var Xe=m((CL,wl)=>{"use strict";var Mn=La(),Cn=K(),ey=z(),Al=function(a){return ey(a)?a:void 0};wl.exports=function(a,e){return arguments.length<2?Al(Mn[a])||Al(Cn[a]):Mn[a]&&Mn[a][e]||Cn[a]&&Cn[a][e]}});var zr=m((DL,kl)=>{"use strict";var ty=he();kl.exports=ty({}.isPrototypeOf)});var cr=m((BL,Ll)=>{"use strict";var ry=K(),Rl=ry.navigator,$l=Rl&&Rl.userAgent;Ll.exports=$l?String($l):""});var Bn=m((OL,Vl)=>{"use strict";var Ol=K(),Dn=cr(),Ml=Ol.process,Cl=Ol.Deno,Dl=Ml&&Ml.versions||Cl&&Cl.version,Bl=Dl&&Dl.v8,Fe,Ma;Bl&&(Fe=Bl.split("."),Ma=Fe[0]>0&&Fe[0]<4?1:+(Fe[0]+Fe[1]));!Ma&&Dn&&(Fe=Dn.match(/Edge\/(\d+)/),(!Fe||Fe[1]>=74)&&(Fe=Dn.match(/Chrome\/(\d+)/),Fe&&(Ma=+Fe[1])));Vl.exports=Ma});var On=m((VL,Nl)=>{"use strict";var _l=Bn(),iy=Ee(),ay=K(),sy=ay.String;Nl.exports=!!Object.getOwnPropertySymbols&&!iy(function(){var a=Symbol("symbol detection");return!sy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&_l&&_l<41})});var Vn=m((_L,Fl)=>{"use strict";var ny=On();Fl.exports=ny&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var _n=m((NL,ql)=>{"use strict";var oy=Xe(),uy=z(),cy=zr(),ly=Vn(),dy=Object;ql.exports=ly?function(a){return typeof a=="symbol"}:function(a){var e=oy("Symbol");return uy(e)&&cy(e.prototype,dy(a))}});var Kr=m((FL,Ul)=>{"use strict";var py=String;Ul.exports=function(a){try{return py(a)}catch(e){return"Object"}}});var Ze=m((qL,Hl)=>{"use strict";var hy=z(),fy=Kr(),my=TypeError;Hl.exports=function(a){if(hy(a))return a;throw new my(fy(a)+" is not a function")}});var Jr=m((UL,jl)=>{"use strict";var by=Ze(),gy=or();jl.exports=function(a,e){var t=a[e];return gy(t)?void 0:by(t)}});var Wl=m((HL,Gl)=>{"use strict";var Nn=xe(),Fn=z(),qn=Re(),Sy=TypeError;Gl.exports=function(a,e){var t,r;if(e==="string"&&Fn(t=a.toString)&&!qn(r=Nn(t,a))||Fn(t=a.valueOf)&&!qn(r=Nn(t,a))||e!=="string"&&Fn(t=a.toString)&&!qn(r=Nn(t,a)))return r;throw new Sy("Can't convert object to primitive value")}});var qe=m((jL,Yl)=>{"use strict";Yl.exports=!0});var Kl=m((GL,zl)=>{"use strict";var Ql=K(),vy=Object.defineProperty;zl.exports=function(a,e){try{vy(Ql,a,{value:e,configurable:!0,writable:!0})}catch(t){Ql[a]=e}return e}});var Xr=m((WL,Zl)=>{"use strict";var yy=qe(),Ty=K(),Iy=Kl(),Jl="__core-js_shared__",Xl=Zl.exports=Ty[Jl]||Iy(Jl,{});(Xl.versions||(Xl.versions=[])).push({version:"3.38.0",mode:yy?"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 Un=m((YL,td)=>{"use strict";var ed=Xr();td.exports=function(a,e){return ed[a]||(ed[a]=e||{})}});var Zr=m((QL,rd)=>{"use strict";var Ey=Yr(),xy=Object;rd.exports=function(a){return xy(Ey(a))}});var Ue=m((zL,id)=>{"use strict";var Py=he(),Ay=Zr(),wy=Py({}.hasOwnProperty);id.exports=Object.hasOwn||function(e,t){return wy(Ay(e),t)}});var Hn=m((KL,ad)=>{"use strict";var ky=he(),Ry=0,$y=Math.random(),Ly=ky(1 .toString);ad.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Ly(++Ry+$y,36)}});var se=m((JL,nd)=>{"use strict";var My=K(),Cy=Un(),sd=Ue(),Dy=Hn(),By=On(),Oy=Vn(),lr=My.Symbol,jn=Cy("wks"),Vy=Oy?lr.for||lr:lr&&lr.withoutSetter||Dy;nd.exports=function(a){return sd(jn,a)||(jn[a]=By&&sd(lr,a)?lr[a]:Vy("Symbol."+a)),jn[a]}});var ld=m((XL,cd)=>{"use strict";var _y=xe(),od=Re(),ud=_n(),Ny=Jr(),Fy=Wl(),qy=se(),Uy=TypeError,Hy=qy("toPrimitive");cd.exports=function(a,e){if(!od(a)||ud(a))return a;var t=Ny(a,Hy),r;if(t){if(e===void 0&&(e="default"),r=_y(t,a,e),!od(r)||ud(r))return r;throw new Uy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Fy(a,e)}});var Gn=m((ZL,dd)=>{"use strict";var jy=ld(),Gy=_n();dd.exports=function(a){var e=jy(a,"string");return Gy(e)?e:e+""}});var Ot=m(hd=>{"use strict";var Wy=$e(),Yy=$n(),Qy=Ln(),Ca=ze(),pd=Gn(),zy=TypeError,Wn=Object.defineProperty,Ky=Object.getOwnPropertyDescriptor,Yn="enumerable",Qn="configurable",zn="writable";hd.f=Wy?Qy?function(e,t,r){if(Ca(e),t=pd(t),Ca(r),typeof e=="function"&&t==="prototype"&&"value"in r&&zn in r&&!r[zn]){var i=Ky(e,t);i&&i[zn]&&(e[t]=r.value,r={configurable:Qn in r?r[Qn]:i[Qn],enumerable:Yn in r?r[Yn]:i[Yn],writable:!1})}return Wn(e,t,r)}:Wn:function(e,t,r){if(Ca(e),t=pd(t),Ca(r),Yy)try{return Wn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new zy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var ei=m((tM,fd)=>{"use strict";fd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var dr=m((rM,md)=>{"use strict";var Jy=$e(),Xy=Ot(),Zy=ei();md.exports=Jy?function(a,e,t){return Xy.f(a,e,Zy(1,t))}:function(a,e,t){return a[e]=t,a}});var Da=m((iM,gd)=>{"use strict";var eT=Un(),tT=Hn(),bd=eT("keys");gd.exports=function(a){return bd[a]||(bd[a]=tT(a))}});var Ba=m((aM,Sd)=>{"use strict";Sd.exports={}});var Zn=m((sM,Td)=>{"use strict";var rT=bl(),yd=K(),iT=Re(),aT=dr(),Kn=Ue(),Jn=Xr(),sT=Da(),nT=Ba(),vd="Object already initialized",Xn=yd.TypeError,oT=yd.WeakMap,Oa,ti,Va,uT=function(a){return Va(a)?ti(a):Oa(a,{})},cT=function(a){return function(e){var t;if(!iT(e)||(t=ti(e)).type!==a)throw new Xn("Incompatible receiver, "+a+" required");return t}};rT||Jn.state?(He=Jn.state||(Jn.state=new oT),He.get=He.get,He.has=He.has,He.set=He.set,Oa=function(a,e){if(He.has(a))throw new Xn(vd);return e.facade=a,He.set(a,e),e},ti=function(a){return He.get(a)||{}},Va=function(a){return He.has(a)}):(Vt=sT("state"),nT[Vt]=!0,Oa=function(a,e){if(Kn(a,Vt))throw new Xn(vd);return e.facade=a,aT(a,Vt,e),e},ti=function(a){return Kn(a,Vt)?a[Vt]:{}},Va=function(a){return Kn(a,Vt)});var He,Vt;Td.exports={set:Oa,get:ti,has:Va,enforce:uT,getterFor:cT}});var eo=m((nM,Pd)=>{"use strict";var lT=Wr(),xd=Function.prototype,Id=xd.apply,Ed=xd.call;Pd.exports=typeof Reflect=="object"&&Reflect.apply||(lT?Ed.bind(Id):function(){return Ed.apply(Id,arguments)})});var to=m((oM,Ad)=>{"use strict";var dT=nr(),pT=he();Ad.exports=function(a){if(dT(a)==="Function")return pT(a)}});var $d=m(Rd=>{"use strict";var wd={}.propertyIsEnumerable,kd=Object.getOwnPropertyDescriptor,hT=kd&&!wd.call({1:2},1);Rd.f=hT?function(e){var t=kd(this,e);return!!t&&t.enumerable}:wd});var Cd=m(Md=>{"use strict";var fT=$e(),mT=xe(),bT=$d(),gT=ei(),ST=ur(),vT=Gn(),yT=Ue(),TT=$n(),Ld=Object.getOwnPropertyDescriptor;Md.f=fT?Ld:function(e,t){if(e=ST(e),t=vT(t),TT)try{return Ld(e,t)}catch(r){}if(yT(e,t))return gT(!mT(bT.f,e,t),e[t])}});var ro=m((lM,Dd)=>{"use strict";var IT=Ee(),ET=z(),xT=/#|\.prototype\./,ri=function(a,e){var t=AT[PT(a)];return t===kT?!0:t===wT?!1:ET(e)?IT(e):!!e},PT=ri.normalize=function(a){return String(a).replace(xT,".").toLowerCase()},AT=ri.data={},wT=ri.NATIVE="N",kT=ri.POLYFILL="P";Dd.exports=ri});var ii=m((dM,Od)=>{"use strict";var Bd=to(),RT=Ze(),$T=Wr(),LT=Bd(Bd.bind);Od.exports=function(a,e){return RT(a),e===void 0?a:$T?LT(a,e):function(){return a.apply(e,arguments)}}});var Le=m((pM,_d)=>{"use strict";var ai=K(),MT=eo(),CT=to(),DT=z(),BT=Cd().f,OT=ro(),pr=La(),VT=ii(),hr=dr(),Vd=Ue();Xr();var _T=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 MT(a,this,arguments)};return e.prototype=a.prototype,e};_d.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?ai:i?ai[t]:ai[t]&&ai[t].prototype,o=r?pr:pr[t]||hr(pr,t,{})[t],u=o.prototype,c,l,d,p,h,f,b,g,S;for(p in e)c=OT(r?p:t+(i?".":"#")+p,a.forced),l=!c&&n&&Vd(n,p),f=o[p],l&&(a.dontCallGetSet?(S=BT(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=VT(h,ai):a.wrap&&l?g=_T(h):s&&DT(h)?g=CT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&hr(g,"sham",!0),hr(o,p,g),s&&(d=t+"Prototype",Vd(pr,d)||hr(pr,d,{}),hr(pr[d],p,h),a.real&&u&&(c||!u[p])&&hr(u,p,h)))}});var qd=m((hM,Fd)=>{"use strict";var io=$e(),NT=Ue(),Nd=Function.prototype,FT=io&&Object.getOwnPropertyDescriptor,ao=NT(Nd,"name"),qT=ao&&function(){}.name==="something",UT=ao&&(!io||io&&FT(Nd,"name").configurable);Fd.exports={EXISTS:ao,PROPER:qT,CONFIGURABLE:UT}});var Hd=m((fM,Ud)=>{"use strict";var HT=Math.ceil,jT=Math.floor;Ud.exports=Math.trunc||function(e){var t=+e;return(t>0?jT:HT)(t)}});var _a=m((mM,jd)=>{"use strict";var GT=Hd();jd.exports=function(a){var e=+a;return e!==e||e===0?0:GT(e)}});var Wd=m((bM,Gd)=>{"use strict";var WT=_a(),YT=Math.max,QT=Math.min;Gd.exports=function(a,e){var t=WT(a);return t<0?YT(t+e,0):QT(t,e)}});var Qd=m((gM,Yd)=>{"use strict";var zT=_a(),KT=Math.min;Yd.exports=function(a){var e=zT(a);return e>0?KT(e,9007199254740991):0}});var Na=m((SM,zd)=>{"use strict";var JT=Qd();zd.exports=function(a){return JT(a.length)}});var Xd=m((vM,Jd)=>{"use strict";var XT=ur(),ZT=Wd(),eI=Na(),Kd=function(a){return function(e,t,r){var i=XT(e),s=eI(i);if(s===0)return!a&&-1;var n=ZT(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Jd.exports={includes:Kd(!0),indexOf:Kd(!1)}});var tp=m((yM,ep)=>{"use strict";var tI=he(),so=Ue(),rI=ur(),iI=Xd().indexOf,aI=Ba(),Zd=tI([].push);ep.exports=function(a,e){var t=rI(a),r=0,i=[],s;for(s in t)!so(aI,s)&&so(t,s)&&Zd(i,s);for(;e.length>r;)so(t,s=e[r++])&&(~iI(i,s)||Zd(i,s));return i}});var no=m((TM,rp)=>{"use strict";rp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var ap=m((IM,ip)=>{"use strict";var sI=tp(),nI=no();ip.exports=Object.keys||function(e){return sI(e,nI)}});var np=m(sp=>{"use strict";var oI=$e(),uI=Ln(),cI=Ot(),lI=ze(),dI=ur(),pI=ap();sp.f=oI&&!uI?Object.defineProperties:function(e,t){lI(e);for(var r=dI(t),i=pI(t),s=i.length,n=0,o;s>n;)cI.f(e,o=i[n++],r[o]);return e}});var oo=m((xM,op)=>{"use strict";var hI=Xe();op.exports=hI("document","documentElement")});var po=m((PM,fp)=>{"use strict";var fI=ze(),mI=np(),up=no(),bI=Ba(),gI=oo(),SI=Ra(),vI=Da(),cp=">",lp="<",co="prototype",lo="script",pp=vI("IE_PROTO"),uo=function(){},hp=function(a){return lp+lo+cp+a+lp+"/"+lo+cp},dp=function(a){a.write(hp("")),a.close();var e=a.parentWindow.Object;return a=null,e},yI=function(){var a=SI("iframe"),e="java"+lo+":",t;return a.style.display="none",gI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(hp("document.F=Object")),t.close(),t.F},Fa,qa=function(){try{Fa=new ActiveXObject("htmlfile")}catch(e){}qa=typeof document!="undefined"?document.domain&&Fa?dp(Fa):yI():dp(Fa);for(var a=up.length;a--;)delete qa[co][up[a]];return qa()};bI[pp]=!0;fp.exports=Object.create||function(e,t){var r;return e!==null?(uo[co]=fI(e),r=new uo,uo[co]=null,r[pp]=e):r=qa(),t===void 0?r:mI.f(r,t)}});var bp=m((AM,mp)=>{"use strict";var TI=Ee();mp.exports=!TI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var fo=m((wM,Sp)=>{"use strict";var II=Ue(),EI=z(),xI=Zr(),PI=Da(),AI=bp(),gp=PI("IE_PROTO"),ho=Object,wI=ho.prototype;Sp.exports=AI?ho.getPrototypeOf:function(a){var e=xI(a);if(II(e,gp))return e[gp];var t=e.constructor;return EI(t)&&e instanceof t?t.prototype:e instanceof ho?wI:null}});var fr=m((kM,vp)=>{"use strict";var kI=dr();vp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:kI(a,e,t),a}});var So=m((RM,Ip)=>{"use strict";var RI=Ee(),$I=z(),LI=Re(),MI=po(),yp=fo(),CI=fr(),DI=se(),BI=qe(),go=DI("iterator"),Tp=!1,et,mo,bo;[].keys&&(bo=[].keys(),"next"in bo?(mo=yp(yp(bo)),mo!==Object.prototype&&(et=mo)):Tp=!0);var OI=!LI(et)||RI(function(){var a={};return et[go].call(a)!==a});OI?et={}:BI&&(et=MI(et));$I(et[go])||CI(et,go,function(){return this});Ip.exports={IteratorPrototype:et,BUGGY_SAFARI_ITERATORS:Tp}});var Ua=m(($M,xp)=>{"use strict";var VI=se(),_I=VI("toStringTag"),Ep={};Ep[_I]="z";xp.exports=String(Ep)==="[object z]"});var si=m((LM,Pp)=>{"use strict";var NI=Ua(),FI=z(),Ha=nr(),qI=se(),UI=qI("toStringTag"),HI=Object,jI=Ha(function(){return arguments}())==="Arguments",GI=function(a,e){try{return a[e]}catch(t){}};Pp.exports=NI?Ha:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=GI(e=HI(a),UI))=="string"?t:jI?Ha(e):(r=Ha(e))==="Object"&&FI(e.callee)?"Arguments":r}});var wp=m((MM,Ap)=>{"use strict";var WI=Ua(),YI=si();Ap.exports=WI?{}.toString:function(){return"[object "+YI(this)+"]"}});var ni=m((CM,Rp)=>{"use strict";var QI=Ua(),zI=Ot().f,KI=dr(),JI=Ue(),XI=wp(),ZI=se(),kp=ZI("toStringTag");Rp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(JI(i,kp)||zI(i,kp,{configurable:!0,value:e}),r&&!QI&&KI(i,"toString",XI))}});var Lp=m((DM,$p)=>{"use strict";var eE=So().IteratorPrototype,tE=po(),rE=ei(),iE=ni(),aE=Bt(),sE=function(){return this};$p.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=tE(eE,{next:rE(+!r,t)}),iE(a,i,!1,!0),aE[i]=sE,a}});var Cp=m((BM,Mp)=>{"use strict";var nE=he(),oE=Ze();Mp.exports=function(a,e,t){try{return nE(oE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Bp=m((OM,Dp)=>{"use strict";var uE=Re();Dp.exports=function(a){return uE(a)||a===null}});var Vp=m((VM,Op)=>{"use strict";var cE=Bp(),lE=String,dE=TypeError;Op.exports=function(a){if(cE(a))return a;throw new dE("Can't set "+lE(a)+" as a prototype")}});var vo=m((_M,_p)=>{"use strict";var pE=Cp(),hE=Re(),fE=Yr(),mE=Vp();_p.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=pE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return fE(i),mE(s),hE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var zp=m((NM,Qp)=>{"use strict";var bE=Le(),gE=xe(),ja=qe(),Wp=qd(),SE=z(),vE=Lp(),Np=fo(),Fp=vo(),yE=ni(),TE=dr(),yo=fr(),IE=se(),qp=Bt(),Yp=So(),EE=Wp.PROPER,xE=Wp.CONFIGURABLE,Up=Yp.IteratorPrototype,Ga=Yp.BUGGY_SAFARI_ITERATORS,oi=IE("iterator"),Hp="keys",ui="values",jp="entries",Gp=function(){return this};Qp.exports=function(a,e,t,r,i,s,n){vE(t,e,r);var o=function(S){if(S===i&&p)return p;if(!Ga&&S&&S in l)return l[S];switch(S){case Hp:return function(){return new t(this,S)};case ui:return function(){return new t(this,S)};case jp:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[oi]||l["@@iterator"]||i&&l[i],p=!Ga&&d||o(i),h=e==="Array"&&l.entries||d,f,b,g;if(h&&(f=Np(h.call(new a)),f!==Object.prototype&&f.next&&(!ja&&Np(f)!==Up&&(Fp?Fp(f,Up):SE(f[oi])||yo(f,oi,Gp)),yE(f,u,!0,!0),ja&&(qp[u]=Gp))),EE&&i===ui&&d&&d.name!==ui&&(!ja&&xE?TE(l,"name",ui):(c=!0,p=function(){return gE(d,this)})),i)if(b={values:o(ui),keys:s?p:o(Hp),entries:o(jp)},n)for(g in b)(Ga||c||!(g in l))&&yo(l,g,b[g]);else bE({target:e,proto:!0,forced:Ga||c},b);return(!ja||n)&&l[oi]!==p&&yo(l,oi,p,{name:i}),qp[e]=p,b}});var Jp=m((FM,Kp)=>{"use strict";Kp.exports=function(a,e){return{value:a,done:e}}});var Io=m((qM,rh)=>{"use strict";var PE=ur(),To=An(),Xp=Bt(),eh=Zn(),AE=Ot().f,wE=zp(),Wa=Jp(),kE=qe(),RE=$e(),th="Array Iterator",$E=eh.set,LE=eh.getterFor(th);rh.exports=wE(Array,"Array",function(a,e){$E(this,{type:th,target:PE(a),index:0,kind:e})},function(){var a=LE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Wa(void 0,!0);switch(a.kind){case"keys":return Wa(t,!1);case"values":return Wa(e[t],!1)}return Wa([t,e[t]],!1)},"values");var Zp=Xp.Arguments=Xp.Array;To("keys");To("values");To("entries");if(!kE&&RE&&Zp.name!=="values")try{AE(Zp,"name",{value:"values"})}catch(a){}});var ah=m((UM,ih)=>{"use strict";var ME=se(),CE=Bt(),DE=ME("iterator"),BE=Array.prototype;ih.exports=function(a){return a!==void 0&&(CE.Array===a||BE[DE]===a)}});var Eo=m((HM,nh)=>{"use strict";var OE=si(),sh=Jr(),VE=or(),_E=Bt(),NE=se(),FE=NE("iterator");nh.exports=function(a){if(!VE(a))return sh(a,FE)||sh(a,"@@iterator")||_E[OE(a)]}});var uh=m((jM,oh)=>{"use strict";var qE=xe(),UE=Ze(),HE=ze(),jE=Kr(),GE=Eo(),WE=TypeError;oh.exports=function(a,e){var t=arguments.length<2?GE(a):e;if(UE(t))return HE(qE(t,a));throw new WE(jE(a)+" is not iterable")}});var dh=m((GM,lh)=>{"use strict";var YE=xe(),ch=ze(),QE=Jr();lh.exports=function(a,e,t){var r,i;ch(a);try{if(r=QE(a,"return"),!r){if(e==="throw")throw t;return t}r=YE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return ch(r),t}});var Qa=m((WM,mh)=>{"use strict";var zE=ii(),KE=xe(),JE=ze(),XE=Kr(),ZE=ah(),ex=Na(),ph=zr(),tx=uh(),rx=Eo(),hh=dh(),ix=TypeError,Ya=function(a,e){this.stopped=a,this.result=e},fh=Ya.prototype;mh.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=zE(e,r),c,l,d,p,h,f,b,g=function(T){return c&&hh(c,"normal",T),new Ya(!0,T)},S=function(T){return i?(JE(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=rx(a),!l)throw new ix(XE(a)+" is not iterable");if(ZE(l)){for(d=0,p=ex(a);p>d;d++)if(h=S(a[d]),h&&ph(fh,h))return h;return new Ya(!1)}c=tx(a,l)}for(f=s?a.next:c.next;!(b=KE(f,c)).done;){try{h=S(b.value)}catch(T){hh(c,"throw",T)}if(typeof h=="object"&&h&&ph(fh,h))return h}return new Ya(!1)}});var gh=m((YM,bh)=>{"use strict";var ax=$e(),sx=Ot(),nx=ei();bh.exports=function(a,e,t){ax?sx.f(a,e,nx(0,t)):a[e]=t}});var Sh=m(()=>{"use strict";var ox=Le(),ux=Qa(),cx=gh();ox({target:"Object",stat:!0},{fromEntries:function(e){var t={};return ux(e,function(r,i){cx(t,r,i)},{AS_ENTRIES:!0}),t}})});var yh=m((KM,vh)=>{"use strict";Io();Sh();var lx=La();vh.exports=lx.Object.fromEntries});var Ih=m((JM,Th)=>{"use strict";Th.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 xh=m(()=>{"use strict";Io();var dx=Ih(),px=K(),hx=ni(),Eh=Bt();for(za in dx)hx(px[za],za),Eh[za]=Eh.Array;var za});var Ah=m((eC,Ph)=>{"use strict";var fx=yh();xh();Ph.exports=fx});var xo=m((tC,wh)=>{"use strict";var mx=Ah();wh.exports=mx});var kh=m(()=>{"use strict"});var Po=m((aC,Rh)=>{"use strict";var ci=K(),bx=cr(),gx=nr(),Ka=function(a){return bx.slice(0,a.length)===a};Rh.exports=function(){return Ka("Bun/")?"BUN":Ka("Cloudflare-Workers")?"CLOUDFLARE":Ka("Deno/")?"DENO":Ka("Node.js/")?"NODE":ci.Bun&&typeof Bun.version=="string"?"BUN":ci.Deno&&typeof Deno.version=="object"?"DENO":gx(ci.process)==="process"?"NODE":ci.window&&ci.document?"BROWSER":"REST"}()});var Ja=m((sC,$h)=>{"use strict";var Sx=Po();$h.exports=Sx==="NODE"});var Mh=m((nC,Lh)=>{"use strict";var vx=Ot();Lh.exports=function(a,e,t){return vx.f(a,e,t)}});var Bh=m((oC,Dh)=>{"use strict";var yx=Xe(),Tx=Mh(),Ix=se(),Ex=$e(),Ch=Ix("species");Dh.exports=function(a){var e=yx(a);Ex&&e&&!e[Ch]&&Tx(e,Ch,{configurable:!0,get:function(){return this}})}});var Vh=m((uC,Oh)=>{"use strict";var xx=zr(),Px=TypeError;Oh.exports=function(a,e){if(xx(e,a))return a;throw new Px("Incorrect invocation")}});var wo=m((cC,_h)=>{"use strict";var Ax=he(),wx=z(),Ao=Xr(),kx=Ax(Function.toString);wx(Ao.inspectSource)||(Ao.inspectSource=function(a){return kx(a)});_h.exports=Ao.inspectSource});var jh=m((lC,Hh)=>{"use strict";var Rx=he(),$x=Ee(),Nh=z(),Lx=si(),Mx=Xe(),Cx=wo(),Fh=function(){},qh=Mx("Reflect","construct"),ko=/^\s*(?:class|function)\b/,Dx=Rx(ko.exec),Bx=!ko.test(Fh),li=function(e){if(!Nh(e))return!1;try{return qh(Fh,[],e),!0}catch(t){return!1}},Uh=function(e){if(!Nh(e))return!1;switch(Lx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Bx||!!Dx(ko,Cx(e))}catch(t){return!0}};Uh.sham=!0;Hh.exports=!qh||$x(function(){var a;return li(li.call)||!li(Object)||!li(function(){a=!0})||a})?Uh:li});var Wh=m((dC,Gh)=>{"use strict";var Ox=jh(),Vx=Kr(),_x=TypeError;Gh.exports=function(a){if(Ox(a))return a;throw new _x(Vx(a)+" is not a constructor")}});var Ro=m((pC,Qh)=>{"use strict";var Yh=ze(),Nx=Wh(),Fx=or(),qx=se(),Ux=qx("species");Qh.exports=function(a,e){var t=Yh(a).constructor,r;return t===void 0||Fx(r=Yh(t)[Ux])?e:Nx(r)}});var Kh=m((hC,zh)=>{"use strict";var Hx=he();zh.exports=Hx([].slice)});var Xh=m((fC,Jh)=>{"use strict";var jx=TypeError;Jh.exports=function(a,e){if(a<e)throw new jx("Not enough arguments");return a}});var $o=m((mC,Zh)=>{"use strict";var Gx=cr();Zh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Gx)});var No=m((bC,cf)=>{"use strict";var Pe=K(),Wx=eo(),Yx=ii(),ef=z(),Qx=Ue(),uf=Ee(),tf=oo(),zx=Kh(),rf=Ra(),Kx=Xh(),Jx=$o(),Xx=Ja(),Oo=Pe.setImmediate,Vo=Pe.clearImmediate,Zx=Pe.process,Lo=Pe.Dispatch,eP=Pe.Function,af=Pe.MessageChannel,tP=Pe.String,Mo=0,di={},sf="onreadystatechange",pi,_t,Co,Do;uf(function(){pi=Pe.location});var _o=function(a){if(Qx(di,a)){var e=di[a];delete di[a],e()}},Bo=function(a){return function(){_o(a)}},nf=function(a){_o(a.data)},of=function(a){Pe.postMessage(tP(a),pi.protocol+"//"+pi.host)};(!Oo||!Vo)&&(Oo=function(e){Kx(arguments.length,1);var t=ef(e)?e:eP(e),r=zx(arguments,1);return di[++Mo]=function(){Wx(t,void 0,r)},_t(Mo),Mo},Vo=function(e){delete di[e]},Xx?_t=function(a){Zx.nextTick(Bo(a))}:Lo&&Lo.now?_t=function(a){Lo.now(Bo(a))}:af&&!Jx?(Co=new af,Do=Co.port2,Co.port1.onmessage=nf,_t=Yx(Do.postMessage,Do)):Pe.addEventListener&&ef(Pe.postMessage)&&!Pe.importScripts&&pi&&pi.protocol!=="file:"&&!uf(of)?(_t=of,Pe.addEventListener("message",nf,!1)):sf in rf("script")?_t=function(a){tf.appendChild(rf("script"))[sf]=function(){tf.removeChild(this),_o(a)}}:_t=function(a){setTimeout(Bo(a),0)});cf.exports={set:Oo,clear:Vo}});var pf=m((gC,df)=>{"use strict";var lf=K(),rP=$e(),iP=Object.getOwnPropertyDescriptor;df.exports=function(a){if(!rP)return lf[a];var e=iP(lf,a);return e&&e.value}});var Fo=m((SC,ff)=>{"use strict";var hf=function(){this.head=null,this.tail=null};hf.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}}};ff.exports=hf});var bf=m((vC,mf)=>{"use strict";var aP=cr();mf.exports=/ipad|iphone|ipod/i.test(aP)&&typeof Pebble!="undefined"});var Sf=m((yC,gf)=>{"use strict";var sP=cr();gf.exports=/web0s(?!.*chrome)/i.test(sP)});var Pf=m((TC,xf)=>{"use strict";var br=K(),nP=pf(),vf=ii(),qo=No().set,oP=Fo(),uP=$o(),cP=bf(),lP=Sf(),Uo=Ja(),yf=br.MutationObserver||br.WebKitMutationObserver,Tf=br.document,If=br.process,Xa=br.Promise,Go=nP("queueMicrotask"),mr,Ho,jo,Za,Ef;Go||(hi=new oP,fi=function(){var a,e;for(Uo&&(a=If.domain)&&a.exit();e=hi.get();)try{e()}catch(t){throw hi.head&&mr(),t}a&&a.enter()},!uP&&!Uo&&!lP&&yf&&Tf?(Ho=!0,jo=Tf.createTextNode(""),new yf(fi).observe(jo,{characterData:!0}),mr=function(){jo.data=Ho=!Ho}):!cP&&Xa&&Xa.resolve?(Za=Xa.resolve(void 0),Za.constructor=Xa,Ef=vf(Za.then,Za),mr=function(){Ef(fi)}):Uo?mr=function(){If.nextTick(fi)}:(qo=vf(qo,br),mr=function(){qo(fi)}),Go=function(a){hi.head||mr(),hi.add(a)});var hi,fi;xf.exports=Go});var wf=m((IC,Af)=>{"use strict";Af.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var es=m((EC,kf)=>{"use strict";kf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Nt=m((xC,Rf)=>{"use strict";var dP=K();Rf.exports=dP.Promise});var gr=m((PC,Cf)=>{"use strict";var pP=K(),mi=Nt(),hP=z(),fP=ro(),mP=wo(),bP=se(),$f=Po(),gP=qe(),Wo=Bn(),Lf=mi&&mi.prototype,SP=bP("species"),Yo=!1,Mf=hP(pP.PromiseRejectionEvent),vP=fP("Promise",function(){var a=mP(mi),e=a!==String(mi);if(!e&&Wo===66||gP&&!(Lf.catch&&Lf.finally))return!0;if(!Wo||Wo<51||!/native code/.test(a)){var t=new mi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[SP]=r,Yo=t.then(function(){})instanceof r,!Yo)return!0}return!e&&($f==="BROWSER"||$f==="DENO")&&!Mf});Cf.exports={CONSTRUCTOR:vP,REJECTION_EVENT:Mf,SUBCLASSING:Yo}});var Sr=m((AC,Bf)=>{"use strict";var Df=Ze(),yP=TypeError,TP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new yP("Bad Promise constructor");e=r,t=i}),this.resolve=Df(e),this.reject=Df(t)};Bf.exports.f=function(a){return new TP(a)}});var em=m(()=>{"use strict";var IP=Le(),EP=qe(),as=Ja(),bt=K(),Ir=xe(),Of=fr(),Vf=vo(),xP=ni(),PP=Bh(),AP=Ze(),is=z(),wP=Re(),kP=Vh(),RP=Ro(),Uf=No().set,Xo=Pf(),$P=wf(),LP=es(),MP=Fo(),Hf=Zn(),ss=Nt(),Zo=gr(),jf=Sr(),ns="Promise",Gf=Zo.CONSTRUCTOR,CP=Zo.REJECTION_EVENT,DP=Zo.SUBCLASSING,Qo=Hf.getterFor(ns),BP=Hf.set,vr=ss&&ss.prototype,Ft=ss,ts=vr,Wf=bt.TypeError,zo=bt.document,eu=bt.process,Ko=jf.f,OP=Ko,VP=!!(zo&&zo.createEvent&&bt.dispatchEvent),Yf="unhandledrejection",_P="rejectionhandled",_f=0,Qf=1,NP=2,tu=1,zf=2,rs,Nf,FP,Ff,Kf=function(a){var e;return wP(a)&&is(e=a.then)?e:!1},Jf=function(a,e){var t=e.value,r=e.state===Qf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{i?(r||(e.rejection===zf&&UP(e),e.rejection=tu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),l=!0)),u===a.promise?n(new Wf("Promise-chain cycle")):(c=Kf(u))?Ir(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},Xf=function(a,e){a.notified||(a.notified=!0,Xo(function(){for(var t=a.reactions,r;r=t.get();)Jf(r,a);a.notified=!1,e&&!a.rejection&&qP(a)}))},Zf=function(a,e,t){var r,i;VP?(r=zo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),bt.dispatchEvent(r)):r={promise:e,reason:t},!CP&&(i=bt["on"+a])?i(r):a===Yf&&$P("Unhandled promise rejection",t)},qP=function(a){Ir(Uf,bt,function(){var e=a.facade,t=a.value,r=qf(a),i;if(r&&(i=LP(function(){as?eu.emit("unhandledRejection",t,e):Zf(Yf,e,t)}),a.rejection=as||qf(a)?zf:tu,i.error))throw i.value})},qf=function(a){return a.rejection!==tu&&!a.parent},UP=function(a){Ir(Uf,bt,function(){var e=a.facade;as?eu.emit("rejectionHandled",e):Zf(_P,e,a.value)})},yr=function(a,e,t){return function(r){a(e,r,t)}},Tr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=NP,Xf(a,!0))},Jo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Wf("Promise can't be resolved itself");var r=Kf(e);r?Xo(function(){var i={done:!1};try{Ir(r,e,yr(Jo,i,a),yr(Tr,i,a))}catch(s){Tr(i,s,a)}}):(a.value=e,a.state=Qf,Xf(a,!1))}catch(i){Tr({done:!1},i,a)}}};if(Gf&&(Ft=function(e){kP(this,ts),AP(e),Ir(rs,this);var t=Qo(this);try{e(yr(Jo,t),yr(Tr,t))}catch(r){Tr(t,r)}},ts=Ft.prototype,rs=function(e){BP(this,{type:ns,done:!1,notified:!1,parent:!1,reactions:new MP,rejection:!1,state:_f,value:void 0})},rs.prototype=Of(ts,"then",function(e,t){var r=Qo(this),i=Ko(RP(this,Ft));return r.parent=!0,i.ok=is(e)?e:!0,i.fail=is(t)&&t,i.domain=as?eu.domain:void 0,r.state===_f?r.reactions.add(i):Xo(function(){Jf(i,r)}),i.promise}),Nf=function(){var a=new rs,e=Qo(a);this.promise=a,this.resolve=yr(Jo,e),this.reject=yr(Tr,e)},jf.f=Ko=function(a){return a===Ft||a===FP?new Nf(a):OP(a)},!EP&&is(ss)&&vr!==Object.prototype)){Ff=vr.then,DP||Of(vr,"then",function(e,t){var r=this;return new Ft(function(i,s){Ir(Ff,r,i,s)}).then(e,t)},{unsafe:!0});try{delete vr.constructor}catch(a){}Vf&&Vf(vr,ts)}IP({global:!0,constructor:!0,wrap:!0,forced:Gf},{Promise:Ft});xP(Ft,ns,!1,!0);PP(ns)});var sm=m((RC,am)=>{"use strict";var HP=se(),rm=HP("iterator"),im=!1;try{tm=0,ru={next:function(){return{done:!!tm++}},return:function(){im=!0}},ru[rm]=function(){return this},Array.from(ru,function(){throw 2})}catch(a){}var tm,ru;am.exports=function(a,e){try{if(!e&&!im)return!1}catch(i){return!1}var t=!1;try{var r={};r[rm]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var iu=m(($C,nm)=>{"use strict";var jP=Nt(),GP=sm(),WP=gr().CONSTRUCTOR;nm.exports=WP||!GP(function(a){jP.all(a).then(void 0,function(){})})});var om=m(()=>{"use strict";var YP=Le(),QP=xe(),zP=Ze(),KP=Sr(),JP=es(),XP=Qa(),ZP=iu();YP({target:"Promise",stat:!0,forced:ZP},{all:function(e){var t=this,r=KP.f(t),i=r.resolve,s=r.reject,n=JP(function(){var o=zP(t.resolve),u=[],c=0,l=1;XP(e,function(d){var p=c++,h=!1;l++,QP(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 cm=m(()=>{"use strict";var eA=Le(),tA=qe(),rA=gr().CONSTRUCTOR,su=Nt(),iA=Xe(),aA=z(),sA=fr(),um=su&&su.prototype;eA({target:"Promise",proto:!0,forced:rA,real:!0},{catch:function(a){return this.then(void 0,a)}});!tA&&aA(su)&&(au=iA("Promise").prototype.catch,um.catch!==au&&sA(um,"catch",au,{unsafe:!0}));var au});var lm=m(()=>{"use strict";var nA=Le(),oA=xe(),uA=Ze(),cA=Sr(),lA=es(),dA=Qa(),pA=iu();nA({target:"Promise",stat:!0,forced:pA},{race:function(e){var t=this,r=cA.f(t),i=r.reject,s=lA(function(){var n=uA(t.resolve);dA(e,function(o){oA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var dm=m(()=>{"use strict";var hA=Le(),fA=Sr(),mA=gr().CONSTRUCTOR;hA({target:"Promise",stat:!0,forced:mA},{reject:function(e){var t=fA.f(this),r=t.reject;return r(e),t.promise}})});var nu=m((NC,pm)=>{"use strict";var bA=ze(),gA=Re(),SA=Sr();pm.exports=function(a,e){if(bA(a),gA(e)&&e.constructor===a)return e;var t=SA.f(a),r=t.resolve;return r(e),t.promise}});var mm=m(()=>{"use strict";var vA=Le(),yA=Xe(),hm=qe(),TA=Nt(),fm=gr().CONSTRUCTOR,IA=nu(),EA=yA("Promise"),xA=hm&&!fm;vA({target:"Promise",stat:!0,forced:hm||fm},{resolve:function(e){return IA(xA&&this===EA?TA:this,e)}})});var bm=m(()=>{"use strict";em();om();cm();lm();dm();mm()});var ym=m(()=>{"use strict";var PA=Le(),AA=qe(),os=Nt(),wA=Ee(),Sm=Xe(),vm=z(),kA=Ro(),gm=nu(),RA=fr(),uu=os&&os.prototype,$A=!!os&&wA(function(){uu.finally.call({then:function(){}},function(){})});PA({target:"Promise",proto:!0,real:!0,forced:$A},{finally:function(a){var e=kA(this,Sm("Promise")),t=vm(a);return this.then(t?function(r){return gm(e,a()).then(function(){return r})}:a,t?function(r){return gm(e,a()).then(function(){throw r})}:a)}});!AA&&vm(os)&&(ou=Sm("Promise").prototype.finally,uu.finally!==ou&&RA(uu,"finally",ou,{unsafe:!0}));var ou});var us=m((WC,Tm)=>{"use strict";var LA=Xe();Tm.exports=LA});var Em=m((YC,Im)=>{"use strict";kh();bm();ym();var MA=us();Im.exports=MA("Promise","finally")});var Pm=m((QC,xm)=>{"use strict";var CA=Em();xm.exports=CA});var cs=m((zC,Am)=>{"use strict";var DA=Pm();Am.exports=DA});var Jm=m(()=>{"use strict";var cw=Le(),lw=Zr(),dw=Na(),pw=_a(),hw=An();cw({target:"Array",proto:!0},{at:function(e){var t=lw(this),r=dw(t),i=pw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});hw("at")});var Zm=m((a0,Xm)=>{"use strict";Jm();var fw=us();Xm.exports=fw("Array","at")});var tb=m((s0,eb)=>{"use strict";var mw=Zm();eb.exports=mw});var vi=m((n0,rb)=>{"use strict";var bw=tb();rb.exports=bw});var og=m(()=>{"use strict"});var ug=m(()=>{"use strict"});var lg=m((h_,cg)=>{"use strict";var Ik=Re(),Ek=nr(),xk=se(),Pk=xk("match");cg.exports=function(a){var e;return Ik(a)&&((e=a[Pk])!==void 0?!!e:Ek(a)==="RegExp")}});var pg=m((f_,dg)=>{"use strict";var Ak=si(),wk=String;dg.exports=function(a){if(Ak(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return wk(a)}});var fg=m((m_,hg)=>{"use strict";var kk=ze();hg.exports=function(){var a=kk(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 gg=m((b_,bg)=>{"use strict";var Rk=xe(),$k=Ue(),Lk=zr(),Mk=fg(),mg=RegExp.prototype;bg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in mg)&&!$k(a,"flags")&&Lk(mg,a)?Rk(Mk,a):e}});var vg=m((g_,Sg)=>{"use strict";var _u=he(),Ck=Zr(),Dk=Math.floor,Ou=_u("".charAt),Bk=_u("".replace),Vu=_u("".slice),Ok=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Vk=/\$([$&'`]|\d{1,2})/g;Sg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=Vk;return i!==void 0&&(i=Ck(i),u=Ok),Bk(s,u,function(c,l){var d;switch(Ou(l,0)){case"$":return"$";case"&":return a;case"`":return Vu(e,0,t);case"'":return Vu(e,n);case"<":d=i[Vu(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=Dk(p/10);return h===0?c:h<=o?r[h-1]===void 0?Ou(l,1):r[h-1]+Ou(l,1):c}d=r[p-1]}return d===void 0?"":d})}});var Ig=m(()=>{"use strict";var _k=Le(),Nk=xe(),Fu=he(),yg=Yr(),Fk=z(),qk=or(),Uk=lg(),Cr=pg(),Hk=Jr(),jk=gg(),Gk=vg(),Wk=se(),Yk=qe(),Qk=Wk("replace"),zk=TypeError,Nu=Fu("".indexOf),Kk=Fu("".replace),Tg=Fu("".slice),Jk=Math.max;_k({target:"String",proto:!0},{replaceAll:function(e,t){var r=yg(this),i,s,n,o,u,c,l,d,p,h,f=0,b="";if(!qk(e)){if(i=Uk(e),i&&(s=Cr(yg(jk(e))),!~Nu(s,"g")))throw new zk("`.replaceAll` does not allow non-global regexes");if(n=Hk(e,Qk),n)return Nk(n,e,r,t);if(Yk&&i)return Kk(Cr(r),e,t)}for(o=Cr(r),u=Cr(e),c=Fk(t),c||(t=Cr(t)),l=u.length,d=Jk(1,l),p=Nu(o,u);p!==-1;)h=c?Cr(t(u,p,o)):Gk(u,o,p,[],void 0,t),b+=Tg(o,f,p)+h,f=p+l,p=p+d>o.length?-1:Nu(o,u,p+d);return f<o.length&&(b+=Tg(o,f)),b}})});var xg=m((y_,Eg)=>{"use strict";og();ug();Ig();var Xk=us();Eg.exports=Xk("String","replaceAll")});var Ag=m((T_,Pg)=>{"use strict";var Zk=xg();Pg.exports=Zk});var kg=m((I_,wg)=>{"use strict";var eR=Ag();wg.exports=eR});var Gc="2.0.111-dev.974e99b3.0";var pe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(pe||{}),mt=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(mt||{});var Aa=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Aa||{}),yn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(yn||{});var Tn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Tn||{});import{assertNever as Jc,assertNonNullable as yv,isNonNullable as wa,ValueSubject as In,Subject as Tv,Subscription as Iv,merge as Ev,observableFrom as xv,fromEvent as Yc,map as Qc,tap as zc,filterChanged as Pv,isNullable as En,ErrorCategory as Kc}from"@vkontakte/videoplayer-shared";var Wc=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 ka=class{constructor(e){this.connection$=new In(void 0);this.castState$=new In("NOT_AVAILABLE");this.errorEvent$=new Tv;this.realCastState$=new In("NOT_AVAILABLE");this.subscription=new Iv;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=wa((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Wc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Kc.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(){wa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();En(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();En(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(Yc(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 Jc(i.sessionState)}})).add(Ev(Yc(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(zc(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Qc(i=>i.castState)),xv([r.getCastState()])).pipe(Pv(),Qc(Av),zc(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=wa(this.connection$.getValue());if(s&&!n){let c=r.getCurrentSession();yv(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(En(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"?wa(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:Kc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Av=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 Jc(a)}};var AS=Qe(xo(),1);var Om=Qe(cs(),1);import{assertNever as wm}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:wm(t)}return a},cu=(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:wm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as BA,Subject as ls,merge as km}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new ls;this.transitionEnded$=new ls;this.transitionUpdated$=new ls;this.forceChanged$=new ls;this.stateChangeStarted$=km(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=km(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||BA(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 OA}from"@vkontakte/videoplayer-shared";var Rm=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 OA(a)}};import{assertNever as Er,assertNonNullable as qt,debounce as $m,ErrorCategory as Lm,fromEvent as Ut,isNonNullable as Mm,map as Cm,merge as Dm,observableFrom as VA,Subject as _A,Subscription as lu,timeout as NA,getHighestQuality as FA}from"@vkontakte/videoplayer-shared";var qA=5,UA=5,HA=500,Bm=7e3,bi=class{constructor(e){this.subscription=new lu;this.loadMediaTimeoutSubscription=new lu;this.videoState=new M("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Er(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Er(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Er(e)}break}default:Er(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Rm(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 lu;this.subscription.add(e),this.subscription.add(Dm(this.videoState.stateChangeStarted$.pipe(Cm(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Cm(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 _A;e.add(i.pipe($m(HA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>qA)&&i.next(o),s=o})),e.add(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<UA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Er(n)}}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Dm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,VA(["init"])).pipe($m(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&E(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var c;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let l=t[e];qt(l);let d=FA(Object.keys(l));qt(d);let p=l[d];qt(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];qt(l),r=l.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];qt(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];qt(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];qt(l),r=ae(l.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Lm.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Er(e)}let n=new chrome.cast.media.MediaInfo((c=this.params.meta.videoId)!=null?c:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Mm(o)&&(n.metadata.title=o),Mm(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(NA(Bm).subscribe(()=>s(`timeout(${Bm})`)))});(0,Om.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:Lm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as _m}from"@vkontakte/videoplayer-shared";import{clearVideoElement as jA}from"@vkontakte/videoplayer-shared";var Vm=a=>{try{a.pause(),a.playbackRate=0,jA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as GA,Subscription as WA}from"@vkontakte/videoplayer-shared";var du=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},pu=window.WeakMap?new WeakMap:new du,hu=window.WeakMap?new WeakMap:new Map,YA=(a,e=20)=>{let t=0;return GA(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?_m(t):(t=document.createElement("video"),a.appendChild(t)),pu.set(t,r);let i=new WA;return i.add(YA(t,e)),hu.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=hu.get(a);e==null||e.unsubscribe(),hu.delete(a);let t=pu.get(a);pu.delete(a),t?_m(a):Vm(a)};import{assertNonNullable as gi,isNonNullable as Je,isNullable as KA,fromEvent as xr,merge as Nm,observableFrom as Fm,filterChanged as qm,map as Si,Subject as Um,Subscription as JA,ValueSubject as XA,ErrorCategory as ZA}from"@vkontakte/videoplayer-shared";import{isNonNullable as fu,isNullable as QA,Subscription as zA}from"@vkontakte/videoplayer-shared";var ds=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=QA(i),c=new zA;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},Ke=(a,e,t)=>ds(e,()=>a.loop,r=>{fu(r)&&(a.loop=r)},{onError:t}),be=(a,e,t,r)=>ds(e,()=>({muted:a.muted,volume:a.volume}),i=>{fu(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Me=(a,e,t,r)=>ds(e,()=>a.playbackRate,i=>{fu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),gt=ds;var ew=a=>["__",a.language,a.label].join("|"),tw=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},mu=class a{constructor(){this.available$=new Um;this.current$=new XA(void 0);this.error$=new Um;this.subscription=new JA;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:ZA.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(gt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Je(s)&&this.setInternal(s)},{equal:(s,n)=>Je(s)&&Je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Si(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(gt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Je(s)&&this.setExternal(s)},{equal:(s,n)=>Je(s)&&Je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Si(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(gt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(gt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){gi(this.video);let{textTracks:e}=this.video;this.subscription.add(xr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Nm(xr(e,"addtrack"),xr(e,"removetrack"),Fm(["init"])).pipe(Si(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),qm((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Nm(xr(e,"change"),Fm(["init"])).pipe(Si(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Si(r=>r&&this.htmlTextTrackToITextTrack(r).id),qm()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(xr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var c,l,d,p,h;let u=(l=(c=o.target)==null?void 0:c.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(xr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;Je(t.align)&&(i.align=t.align),Je(t.position)&&(i.position=t.position),Je(t.size)&&(i.size=t.size),Je(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){gi(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:ew(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){gi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(KA(e)||!tw(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){gi(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){gi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ce=mu;var rt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Hm=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},bu=a=>{let e=Hm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},jm=a=>{let e=Hm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as De,map as St,merge as Wm,filterChanged as iw,isNonNullable as Ym,Subject as aw,filter as Qm,mapTo as zm,combine as sw,once as nw,ErrorCategory as ow,ValueSubject as Km,clientChecker as uw}from"@vkontakte/videoplayer-shared";var rw=3,Gm=(a,e,t=rw)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var ge=a=>{let e=v=>De(a,v).pipe(zm(void 0)),r=Wm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>De(a,v))).pipe(St(v=>v.type==="ended"?a.readyState<2:a.readyState<3),iw()),i=Wm(De(a,"progress"),De(a,"timeupdate")).pipe(St(()=>Gm(a.buffered,a.currentTime))),s=uw.isSafari?sw({play:e("play").pipe(nw()),playing:e("playing")}).pipe(zm(void 0)):e("playing"),n=De(a,"volumechange").pipe(St(()=>({muted:a.muted,volume:a.volume}))),o=De(a,"ratechange").pipe(St(()=>a.playbackRate)),u=De(a,"error").pipe(Qm(()=>!!(a.error||a.played.length)),St(()=>{var y;let v=a.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:ow.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(y=a.error)!=null?y:void 0}})),c=De(a,"timeupdate").pipe(St(()=>a.currentTime)),l=new aw,d=.3,p;c.subscribe(v=>{a.loop&&Ym(p)&&Ym(v)&&p>=a.duration-d&&v<=d&&l.next(p),p=v});let h=e("pause").pipe(Qm(()=>!a.error&&p!==a.duration)),f=De(a,"enterpictureinpicture"),b=De(a,"leavepictureinpicture"),g=new Km(jm(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new Km(bu(a));return De(a,"fullscreenchange").pipe(St(()=>bu(a))).subscribe(S),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:De(a,"durationchange").pipe(St(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S}};import{VideoQuality as vt}from"@vkontakte/videoplayer-shared";var yt=a=>{switch(a){case"mobile":return vt.Q_144P;case"lowest":return vt.Q_240P;case"low":return vt.Q_360P;case"sd":case"medium":return vt.Q_480P;case"hd":case"high":return vt.Q_720P;case"fullhd":case"full":return vt.Q_1080P;case"quadhd":case"quad":return vt.Q_1440P;case"ultrahd":case"ultra":return vt.Q_2160P}};var Ht=Qe(vi(),1);import{isNonNullable as Se,isNullable as Su,now as lb,isHigher as vu,isHigherOrEqual as nb,isInvariantQuality as ob,isLower as yu,isLowerOrEqual as ub,videoSizeToQuality as gw,assertNotEmptyArray as db,assertNonNullable as Sw}from"@vkontakte/videoplayer-shared";var gu=!1,it={},ib=a=>{gu=a},ab=()=>{it={}},sb=a=>{a(it)},yi=(a,e)=>{var t;gu&&(it.meta=(t=it.meta)!=null?t:{},it.meta[a]=e)},ne=class{constructor(e){this.name=e}next(e){var r,i;if(!gu)return;it.series=(r=it.series)!=null?r:{};let t=(i=it.series[this.name])!=null?i:[];t.push([Date.now(),e]),it.series[this.name]=t}};var vw=new ne("best_bitrate"),pb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Tu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ti=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=lb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},hb='Assertion "ABR Tracks is empty array" failed',ps=(a,e,t,r)=>{var u;let i=[...e].sort(Tu(1)),s=[...t].sort(Tu(1)),n=s.filter(c=>Se(c.bitrate)&&Se(a.bitrate)?a.bitrate/c.bitrate>r:!0),o=(u=(0,Ht.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Ht.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Ht.default)(n,-1):(0,Ht.default)(s,0)},cb=a=>"quality"in a,fb=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&lb()-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=cb(s)?"video":"audio",o=cb(s)?s.quality:s.bitrate;return e({message:`
6
+ var Ev=Object.create;var Rn=Object.defineProperty,xv=Object.defineProperties,Pv=Object.getOwnPropertyDescriptor,Av=Object.getOwnPropertyDescriptors,wv=Object.getOwnPropertyNames,Ua=Object.getOwnPropertySymbols,kv=Object.getPrototypeOf,$n=Object.prototype.hasOwnProperty,lc=Object.prototype.propertyIsEnumerable;var Rv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var Je=Math.pow,uc=(a,e,t)=>e in a?Rn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,P=(a,e)=>{for(var t in e||(e={}))$n.call(e,t)&&uc(a,t,e[t]);if(Ua)for(var t of Ua(e))lc.call(e,t)&&uc(a,t,e[t]);return a},M=(a,e)=>xv(a,Av(e));var cc=(a,e)=>{var t={};for(var r in a)$n.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&Ua)for(var r of Ua(a))e.indexOf(r)<0&&lc.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var $v=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of wv(e))!$n.call(a,i)&&i!==t&&Rn(a,i,{get:()=>e[i],enumerable:!(r=Pv(e,i))||r.enumerable});return a};var Xe=(a,e,t)=>(t=a!=null?Ev(kv(a)):{},$v(e||!a||!a.__esModule?Rn(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(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())}),Ln=function(a,e){this[0]=a,this[1]=e},te=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof Ln,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[Rv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var xe=m((AL,Sc)=>{"use strict";Sc.exports=function(a){try{return!!a()}catch(e){return!0}}});var ai=m((wL,vc)=>{"use strict";var _v=xe();vc.exports=!_v(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var fe=m((kL,Ic)=>{"use strict";var yc=ai(),Tc=Function.prototype,On=Tc.call,Nv=yc&&Tc.bind.bind(On,On);Ic.exports=yc?Nv:function(a){return function(){return On.apply(a,arguments)}}});var br=m((RL,xc)=>{"use strict";var Ec=fe(),Fv=Ec({}.toString),qv=Ec("".slice);xc.exports=function(a){return qv(Fv(a),8,-1)}});var Ac=m(($L,Pc)=>{"use strict";var Uv=fe(),Hv=xe(),jv=br(),Vn=Object,Gv=Uv("".split);Pc.exports=Hv(function(){return!Vn("z").propertyIsEnumerable(0)})?function(a){return jv(a)==="String"?Gv(a,""):Vn(a)}:Vn});var gr=m((LL,wc)=>{"use strict";wc.exports=function(a){return a==null}});var si=m((ML,kc)=>{"use strict";var Wv=gr(),Yv=TypeError;kc.exports=function(a){if(Wv(a))throw new Yv("Can't call method on "+a);return a}});var Sr=m((CL,Rc)=>{"use strict";var Qv=Ac(),zv=si();Rc.exports=function(a){return Qv(zv(a))}});var _n=m((DL,$c)=>{"use strict";$c.exports=function(){}});var Ht=m((BL,Lc)=>{"use strict";Lc.exports={}});var J=m((Nn,Mc)=>{"use strict";var ni=function(a){return a&&a.Math===Math&&a};Mc.exports=ni(typeof globalThis=="object"&&globalThis)||ni(typeof window=="object"&&window)||ni(typeof self=="object"&&self)||ni(typeof global=="object"&&global)||ni(typeof Nn=="object"&&Nn)||function(){return this}()||Function("return this")()});var K=m((OL,Cc)=>{"use strict";var Fn=typeof document=="object"&&document.all;Cc.exports=typeof Fn=="undefined"&&Fn!==void 0?function(a){return typeof a=="function"||a===Fn}:function(a){return typeof a=="function"}});var Oc=m((VL,Bc)=>{"use strict";var Kv=J(),Jv=K(),Dc=Kv.WeakMap;Bc.exports=Jv(Dc)&&/native code/.test(String(Dc))});var Le=m((_L,Vc)=>{"use strict";var Xv=K();Vc.exports=function(a){return typeof a=="object"?a!==null:Xv(a)}});var Me=m((NL,_c)=>{"use strict";var Zv=xe();_c.exports=!Zv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Wa=m((FL,Fc)=>{"use strict";var ey=J(),Nc=Le(),qn=ey.document,ty=Nc(qn)&&Nc(qn.createElement);Fc.exports=function(a){return ty?qn.createElement(a):{}}});var Un=m((qL,qc)=>{"use strict";var ry=Me(),iy=xe(),ay=Wa();qc.exports=!ry&&!iy(function(){return Object.defineProperty(ay("div"),"a",{get:function(){return 7}}).a!==7})});var Hn=m((UL,Uc)=>{"use strict";var sy=Me(),ny=xe();Uc.exports=sy&&ny(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ze=m((HL,Hc)=>{"use strict";var oy=Le(),uy=String,ly=TypeError;Hc.exports=function(a){if(oy(a))return a;throw new ly(uy(a)+" is not an object")}});var Pe=m((jL,jc)=>{"use strict";var cy=ai(),Ya=Function.prototype.call;jc.exports=cy?Ya.bind(Ya):function(){return Ya.apply(Ya,arguments)}});var Qa=m((GL,Gc)=>{"use strict";Gc.exports={}});var at=m((WL,Yc)=>{"use strict";var jn=Qa(),Gn=J(),dy=K(),Wc=function(a){return dy(a)?a:void 0};Yc.exports=function(a,e){return arguments.length<2?Wc(jn[a])||Wc(Gn[a]):jn[a]&&jn[a][e]||Gn[a]&&Gn[a][e]}});var oi=m((YL,Qc)=>{"use strict";var py=fe();Qc.exports=py({}.isPrototypeOf)});var vr=m((QL,Jc)=>{"use strict";var hy=J(),zc=hy.navigator,Kc=zc&&zc.userAgent;Jc.exports=Kc?String(Kc):""});var Yn=m((zL,id)=>{"use strict";var rd=J(),Wn=vr(),Xc=rd.process,Zc=rd.Deno,ed=Xc&&Xc.versions||Zc&&Zc.version,td=ed&&ed.v8,He,za;td&&(He=td.split("."),za=He[0]>0&&He[0]<4?1:+(He[0]+He[1]));!za&&Wn&&(He=Wn.match(/Edge\/(\d+)/),(!He||He[1]>=74)&&(He=Wn.match(/Chrome\/(\d+)/),He&&(za=+He[1])));id.exports=za});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=oi(),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 ui=m((ZL,ud)=>{"use strict";var Ey=String;ud.exports=function(a){try{return Ey(a)}catch(e){return"Object"}}});var st=m((eM,ld)=>{"use strict";var xy=K(),Py=ui(),Ay=TypeError;ld.exports=function(a){if(xy(a))return a;throw new Ay(Py(a)+" is not a function")}});var li=m((tM,cd)=>{"use strict";var wy=st(),ky=gr();cd.exports=function(a,e){var t=a[e];return ky(t)?void 0:wy(t)}});var pd=m((rM,dd)=>{"use strict";var Jn=Pe(),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 je=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=je(),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 di=m((oM,Id)=>{"use strict";var Dy=si(),By=Object;Id.exports=function(a){return By(Dy(a))}});var Ge=m((uM,Ed)=>{"use strict";var Oy=fe(),Vy=di(),_y=Oy({}.hasOwnProperty);Ed.exports=Object.hasOwn||function(e,t){return _y(Vy(e),t)}});var to=m((lM,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((cM,Ad)=>{"use strict";var Hy=J(),jy=eo(),Pd=Ge(),Gy=to(),Wy=Qn(),Yy=zn(),yr=Hy.Symbol,ro=jy("wks"),Qy=Yy?yr.for||yr:yr&&yr.withoutSetter||Gy;Ad.exports=function(a){return Pd(ro,a)||(ro[a]=Wy&&Pd(yr,a)?yr[a]:Qy("Symbol."+a)),ro[a]}});var $d=m((dM,Rd)=>{"use strict";var zy=Pe(),wd=Le(),kd=Kn(),Ky=li(),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(),Ka=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(Ka(e),t=Md(t),Ka(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(Ka(e),t=Md(t),Ka(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 pi=m((fM,Dd)=>{"use strict";Dd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Tr=m((mM,Bd)=>{"use strict";var uT=Me(),lT=jt(),cT=pi();Bd.exports=uT?function(a,e,t){return lT.f(a,e,cT(1,t))}:function(a,e,t){return a[e]=t,a}});var Ja=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 Xa=m((gM,_d)=>{"use strict";_d.exports={}});var po=m((SM,qd)=>{"use strict";var hT=Oc(),Fd=J(),fT=Le(),mT=Tr(),uo=Ge(),lo=ci(),bT=Ja(),gT=Xa(),Nd="Object already initialized",co=Fd.TypeError,ST=Fd.WeakMap,Za,hi,es,vT=function(a){return es(a)?hi(a):Za(a,{})},yT=function(a){return function(e){var t;if(!fT(e)||(t=hi(e)).type!==a)throw new co("Incompatible receiver, "+a+" required");return t}};hT||lo.state?(We=lo.state||(lo.state=new ST),We.get=We.get,We.has=We.has,We.set=We.set,Za=function(a,e){if(We.has(a))throw new co(Nd);return e.facade=a,We.set(a,e),e},hi=function(a){return We.get(a)||{}},es=function(a){return We.has(a)}):(Gt=bT("state"),gT[Gt]=!0,Za=function(a,e){if(uo(a,Gt))throw new co(Nd);return e.facade=a,mT(a,Gt,e),e},hi=function(a){return uo(a,Gt)?a[Gt]:{}},es=function(a){return uo(a,Gt)});var We,Gt;qd.exports={set:Za,get:hi,has:es,enforce:vT,getterFor:yT}});var ho=m((vM,Gd)=>{"use strict";var TT=ai(),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=br(),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 PT=Me(),AT=Pe(),wT=Kd(),kT=pi(),RT=Sr(),$T=io(),LT=Ge(),MT=Un(),Jd=Object.getOwnPropertyDescriptor;Xd.f=PT?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(!AT(wT.f,e,t),e[t])}});var mo=m((EM,ep)=>{"use strict";var CT=xe(),DT=K(),BT=/#|\.prototype\./,fi=function(a,e){var t=VT[OT(a)];return t===NT?!0:t===_T?!1:DT(e)?CT(e):!!e},OT=fi.normalize=function(a){return String(a).replace(BT,".").toLowerCase()},VT=fi.data={},_T=fi.NATIVE="N",NT=fi.POLYFILL="P";ep.exports=fi});var mi=m((xM,rp)=>{"use strict";var tp=fo(),FT=st(),qT=ai(),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((PM,ap)=>{"use strict";var bi=J(),HT=ho(),jT=fo(),GT=K(),WT=Zd().f,YT=mo(),Ir=Qa(),QT=mi(),Er=Tr(),ip=Ge();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?bi:i?bi[t]:bi[t]&&bi[t].prototype,o=r?Ir:Ir[t]||Er(Ir,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,S;for(p in e)l=YT(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&ip(n,p),f=o[p],c&&(a.dontCallGetSet?(S=WT(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=QT(h,bi):a.wrap&&c?g=zT(h):s&&GT(h)?g=jT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Er(g,"sham",!0),Er(o,p,g),s&&(d=t+"Prototype",ip(Ir,d)||Er(Ir,d,{}),Er(Ir[d],p,h),a.real&&u&&(l||!u[p])&&Er(u,p,h)))}});var op=m((AM,np)=>{"use strict";var bo=Me(),KT=Ge(),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 lp=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 ts=m((kM,cp)=>{"use strict";var rI=lp();cp.exports=function(a){var e=+a;return e!==e||e===0?0:rI(e)}});var pp=m((RM,dp)=>{"use strict";var iI=ts(),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=ts(),oI=Math.min;hp.exports=function(a){var e=nI(a);return e>0?oI(e,9007199254740991):0}});var rs=m((LM,mp)=>{"use strict";var uI=fp();mp.exports=function(a){return uI(a.length)}});var Sp=m((MM,gp)=>{"use strict";var lI=Sr(),cI=pp(),dI=rs(),bp=function(a){return function(e,t,r){var i=lI(e),s=dI(i);if(s===0)return!a&&-1;var n=cI(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=Ge(),hI=Sr(),fI=Sp().indexOf,mI=Xa(),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 Ap=m(Pp=>{"use strict";var SI=Me(),vI=Hn(),yI=jt(),TI=Ze(),II=Sr(),EI=xp();Pp.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 PI=Ze(),AI=Ap(),kp=vo(),wI=Xa(),kI=yo(),RI=Wa(),$I=Ja(),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},is,as=function(){try{is=new ActiveXObject("htmlfile")}catch(e){}as=typeof document!="undefined"?document.domain&&is?Lp(is):LI():Lp(is);for(var a=kp.length;a--;)delete as[Io][kp[a]];return as()};wI[Mp]=!0;Dp.exports=Object.create||function(e,t){var r;return e!==null?(To[Io]=PI(e),r=new To,To[Io]=null,r[Mp]=e):r=as(),t===void 0?r:AI.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 Ao=m((FM,_p)=>{"use strict";var CI=Ge(),DI=K(),BI=di(),OI=Ja(),VI=Op(),Vp=OI("IE_PROTO"),Po=Object,_I=Po.prototype;_p.exports=VI?Po.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 Po?_I:null}});var xr=m((qM,Np)=>{"use strict";var NI=Tr();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=Ao(),jI=xr(),GI=oe(),WI=je(),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 ss=m((HM,jp)=>{"use strict";var QI=oe(),zI=QI("toStringTag"),Hp={};Hp[zI]="z";jp.exports=String(Hp)==="[object z]"});var gi=m((jM,Gp)=>{"use strict";var KI=ss(),JI=K(),ns=br(),XI=oe(),ZI=XI("toStringTag"),eE=Object,tE=ns(function(){return arguments}())==="Arguments",rE=function(a,e){try{return a[e]}catch(t){}};Gp.exports=KI?ns:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=rE(e=eE(a),ZI))=="string"?t:tE?ns(e):(r=ns(e))==="Object"&&JI(e.callee)?"Arguments":r}});var Yp=m((GM,Wp)=>{"use strict";var iE=ss(),aE=gi();Wp.exports=iE?{}.toString:function(){return"[object "+aE(this)+"]"}});var Si=m((WM,zp)=>{"use strict";var sE=ss(),nE=jt().f,oE=Tr(),uE=Ge(),lE=Yp(),cE=oe(),Qp=cE("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",lE))}});var Jp=m((YM,Kp)=>{"use strict";var dE=$o().IteratorPrototype,pE=xo(),hE=pi(),fE=Si(),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(),PE=si(),AE=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 PE(i),AE(s),xE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var mh=m((XM,fh)=>{"use strict";var wE=Ce(),kE=Pe(),os=je(),ph=op(),RE=K(),$E=Jp(),sh=Ao(),nh=Lo(),LE=Si(),ME=Tr(),Mo=xr(),CE=oe(),oh=Ht(),hh=$o(),DE=ph.PROPER,BE=ph.CONFIGURABLE,uh=hh.IteratorPrototype,us=hh.BUGGY_SAFARI_ITERATORS,vi=CE("iterator"),lh="keys",yi="values",ch="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(!us&&S&&S in c)return c[S];switch(S){case lh:return function(){return new t(this,S)};case yi:return function(){return new t(this,S)};case ch:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[vi]||c["@@iterator"]||i&&c[i],p=!us&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=sh(h.call(new a)),f!==Object.prototype&&f.next&&(!os&&sh(f)!==uh&&(nh?nh(f,uh):RE(f[vi])||Mo(f,vi,dh)),LE(f,u,!0,!0),os&&(oh[u]=dh))),DE&&i===yi&&d&&d.name!==yi&&(!os&&BE?ME(c,"name",yi):(l=!0,p=function(){return kE(d,this)})),i)if(b={values:o(yi),keys:s?p:o(lh),entries:o(ch)},n)for(g in b)(us||l||!(g in c))&&Mo(c,g,b[g]);else wE({target:e,proto:!0,forced:us||l},b);return(!os||n)&&c[vi]!==p&&Mo(c,vi,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=Sr(),Co=_n(),Sh=Ht(),yh=po(),VE=jt().f,_E=mh(),ls=gh(),NE=je(),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,ls(void 0,!0);switch(a.kind){case"keys":return ls(t,!1);case"values":return ls(e[t],!1)}return ls([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,Ah)=>{"use strict";var YE=gi(),Ph=li(),QE=gr(),zE=Ht(),KE=oe(),JE=KE("iterator");Ah.exports=function(a){if(!QE(a))return Ph(a,JE)||Ph(a,"@@iterator")||zE[YE(a)]}});var kh=m((iC,wh)=>{"use strict";var XE=Pe(),ZE=st(),ex=Ze(),tx=ui(),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=Pe(),Rh=Ze(),sx=li();$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 ds=m((sC,Bh)=>{"use strict";var nx=mi(),ox=Pe(),ux=Ze(),lx=ui(),cx=xh(),dx=rs(),Mh=oi(),px=kh(),hx=Bo(),Ch=Lh(),fx=TypeError,cs=function(a,e){this.stopped=a,this.result=e},Dh=cs.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),l,c,d,p,h,f,b,g=function(T){return l&&Ch(l,"normal",T),new cs(!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)l=a.iterator;else if(n)l=a;else{if(c=hx(a),!c)throw new fx(lx(a)+" is not iterable");if(cx(c)){for(d=0,p=dx(a);p>d;d++)if(h=S(a[d]),h&&Mh(Dh,h))return h;return new cs(!1)}l=px(a,c)}for(f=s?a.next:l.next;!(b=ox(f,l)).done;){try{h=S(b.value)}catch(T){Ch(l,"throw",T)}if(typeof h=="object"&&h&&Mh(Dh,h))return h}return new cs(!1)}});var Vh=m((nC,Oh)=>{"use strict";var mx=Me(),bx=jt(),gx=pi();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=ds(),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((lC,Nh)=>{"use strict";Do();_h();var Tx=Qa();Nh.exports=Tx.Object.fromEntries});var Uh=m((cC,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=Si(),Hh=Ht();for(ps in Ix)xx(Ex[ps],ps),Hh[ps]=Hh.Array;var ps});var Wh=m((hC,Gh)=>{"use strict";var Px=Fh();jh();Gh.exports=Px});var Oo=m((fC,Yh)=>{"use strict";var Ax=Wh();Yh.exports=Ax});var Qh=m(()=>{"use strict"});var Vo=m((gC,zh)=>{"use strict";var Ti=J(),wx=vr(),kx=br(),hs=function(a){return wx.slice(0,a.length)===a};zh.exports=function(){return hs("Bun/")?"BUN":hs("Cloudflare-Workers")?"CLOUDFLARE":hs("Deno/")?"DENO":hs("Node.js/")?"NODE":Ti.Bun&&typeof Bun.version=="string"?"BUN":Ti.Deno&&typeof Deno.version=="object"?"DENO":kx(Ti.process)==="process"?"NODE":Ti.window&&Ti.document?"BROWSER":"REST"}()});var fs=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=oi(),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,cf)=>{"use strict";var Fx=fe(),qx=xe(),nf=K(),Ux=gi(),Hx=at(),jx=No(),of=function(){},uf=Hx("Reflect","construct"),Fo=/^\s*(?:class|function)\b/,Gx=Fx(Fo.exec),Wx=!Fo.test(of),Ii=function(e){if(!nf(e))return!1;try{return uf(of,[],e),!0}catch(t){return!1}},lf=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}};lf.sham=!0;cf.exports=!uf||qx(function(){var a;return Ii(Ii.call)||!Ii(Object)||!Ii(function(){a=!0})||a})?lf:Ii});var hf=m((xC,pf)=>{"use strict";var Yx=df(),Qx=ui(),zx=TypeError;pf.exports=function(a){if(Yx(a))return a;throw new zx(Qx(a)+" is not a constructor")}});var qo=m((PC,mf)=>{"use strict";var ff=Ze(),Kx=hf(),Jx=gr(),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((AC,bf)=>{"use strict";var eP=fe();bf.exports=eP([].slice)});var vf=m((wC,Sf)=>{"use strict";var tP=TypeError;Sf.exports=function(a,e){if(a<e)throw new tP("Not enough arguments");return a}});var Uo=m((kC,yf)=>{"use strict";var rP=vr();yf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(rP)});var Jo=m((RC,Rf)=>{"use strict";var Ae=J(),iP=ho(),aP=mi(),Tf=K(),sP=Ge(),kf=xe(),If=yo(),nP=gf(),Ef=Wa(),oP=vf(),uP=Uo(),lP=fs(),Qo=Ae.setImmediate,zo=Ae.clearImmediate,cP=Ae.process,Ho=Ae.Dispatch,dP=Ae.Function,xf=Ae.MessageChannel,pP=Ae.String,jo=0,Ei={},Pf="onreadystatechange",xi,Wt,Go,Wo;kf(function(){xi=Ae.location});var Ko=function(a){if(sP(Ei,a)){var e=Ei[a];delete Ei[a],e()}},Yo=function(a){return function(){Ko(a)}},Af=function(a){Ko(a.data)},wf=function(a){Ae.postMessage(pP(a),xi.protocol+"//"+xi.host)};(!Qo||!zo)&&(Qo=function(e){oP(arguments.length,1);var t=Tf(e)?e:dP(e),r=nP(arguments,1);return Ei[++jo]=function(){iP(t,void 0,r)},Wt(jo),jo},zo=function(e){delete Ei[e]},lP?Wt=function(a){cP.nextTick(Yo(a))}:Ho&&Ho.now?Wt=function(a){Ho.now(Yo(a))}:xf&&!uP?(Go=new xf,Wo=Go.port2,Go.port1.onmessage=Af,Wt=aP(Wo.postMessage,Wo)):Ae.addEventListener&&Tf(Ae.postMessage)&&!Ae.importScripts&&xi&&xi.protocol!=="file:"&&!kf(wf)?(Wt=wf,Ae.addEventListener("message",Af,!1)):Pf in Ef("script")?Wt=function(a){If.appendChild(Ef("script"))[Pf]=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(),hP=Me(),fP=Object.getOwnPropertyDescriptor;Lf.exports=function(a){if(!hP)return $f[a];var e=fP($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 mP=vr();Bf.exports=/ipad|iphone|ipod/i.test(mP)&&typeof Pebble!="undefined"});var _f=m((CC,Vf)=>{"use strict";var bP=vr();Vf.exports=/web0s(?!.*chrome)/i.test(bP)});var Gf=m((DC,jf)=>{"use strict";var Ar=J(),gP=Mf(),Nf=mi(),Zo=Jo().set,SP=Xo(),vP=Uo(),yP=Of(),TP=_f(),eu=fs(),Ff=Ar.MutationObserver||Ar.WebKitMutationObserver,qf=Ar.document,Uf=Ar.process,ms=Ar.Promise,iu=gP("queueMicrotask"),Pr,tu,ru,bs,Hf;iu||(Pi=new SP,Ai=function(){var a,e;for(eu&&(a=Uf.domain)&&a.exit();e=Pi.get();)try{e()}catch(t){throw Pi.head&&Pr(),t}a&&a.enter()},!vP&&!eu&&!TP&&Ff&&qf?(tu=!0,ru=qf.createTextNode(""),new Ff(Ai).observe(ru,{characterData:!0}),Pr=function(){ru.data=tu=!tu}):!yP&&ms&&ms.resolve?(bs=ms.resolve(void 0),bs.constructor=ms,Hf=Nf(bs.then,bs),Pr=function(){Hf(Ai)}):eu?Pr=function(){Uf.nextTick(Ai)}:(Zo=Nf(Zo,Ar),Pr=function(){Zo(Ai)}),iu=function(a){Pi.head||Pr(),Pi.add(a)});var Pi,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 gs=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 IP=J();zf.exports=IP.Promise});var wr=m((_C,Zf)=>{"use strict";var EP=J(),wi=Yt(),xP=K(),PP=mo(),AP=No(),wP=oe(),Kf=Vo(),kP=je(),au=Yn(),Jf=wi&&wi.prototype,RP=wP("species"),su=!1,Xf=xP(EP.PromiseRejectionEvent),$P=PP("Promise",function(){var a=AP(wi),e=a!==String(wi);if(!e&&au===66||kP&&!(Jf.catch&&Jf.finally))return!0;if(!au||au<51||!/native code/.test(a)){var t=new wi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[RP]=r,su=t.then(function(){})instanceof r,!su)return!0}return!e&&(Kf==="BROWSER"||Kf==="DENO")&&!Xf});Zf.exports={CONSTRUCTOR:$P,REJECTION_EVENT:Xf,SUBCLASSING:su}});var kr=m((NC,tm)=>{"use strict";var em=st(),LP=TypeError,MP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new LP("Bad Promise constructor");e=r,t=i}),this.resolve=em(e),this.reject=em(t)};tm.exports.f=function(a){return new MP(a)}});var ym=m(()=>{"use strict";var CP=Ce(),DP=je(),Ts=fs(),xt=J(),Mr=Pe(),rm=xr(),im=Lo(),BP=Si(),OP=tf(),VP=st(),ys=K(),_P=Le(),NP=af(),FP=qo(),um=Jo().set,cu=Gf(),qP=Yf(),UP=gs(),HP=Xo(),lm=po(),Is=Yt(),du=wr(),cm=kr(),Es="Promise",dm=du.CONSTRUCTOR,jP=du.REJECTION_EVENT,GP=du.SUBCLASSING,nu=lm.getterFor(Es),WP=lm.set,Rr=Is&&Is.prototype,Qt=Is,Ss=Rr,pm=xt.TypeError,ou=xt.document,pu=xt.process,uu=cm.f,YP=uu,QP=!!(ou&&ou.createEvent&&xt.dispatchEvent),hm="unhandledrejection",zP="rejectionhandled",am=0,fm=1,KP=2,hu=1,mm=2,vs,sm,JP,nm,bm=function(a){var e;return _P(a)&&ys(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,l,c;try{i?(r||(e.rejection===mm&&ZP(e),e.rejection=hu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new pm("Promise-chain cycle")):(l=bm(u))?Mr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Sm=function(a,e){a.notified||(a.notified=!0,cu(function(){for(var t=a.reactions,r;r=t.get();)gm(r,a);a.notified=!1,e&&!a.rejection&&XP(a)}))},vm=function(a,e,t){var r,i;QP?(r=ou.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),xt.dispatchEvent(r)):r={promise:e,reason:t},!jP&&(i=xt["on"+a])?i(r):a===hm&&qP("Unhandled promise rejection",t)},XP=function(a){Mr(um,xt,function(){var e=a.facade,t=a.value,r=om(a),i;if(r&&(i=UP(function(){Ts?pu.emit("unhandledRejection",t,e):vm(hm,e,t)}),a.rejection=Ts||om(a)?mm:hu,i.error))throw i.value})},om=function(a){return a.rejection!==hu&&!a.parent},ZP=function(a){Mr(um,xt,function(){var e=a.facade;Ts?pu.emit("rejectionHandled",e):vm(zP,e,a.value)})},$r=function(a,e,t){return function(r){a(e,r,t)}},Lr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=KP,Sm(a,!0))},lu=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?cu(function(){var i={done:!1};try{Mr(r,e,$r(lu,i,a),$r(Lr,i,a))}catch(s){Lr(i,s,a)}}):(a.value=e,a.state=fm,Sm(a,!1))}catch(i){Lr({done:!1},i,a)}}};if(dm&&(Qt=function(e){NP(this,Ss),VP(e),Mr(vs,this);var t=nu(this);try{e($r(lu,t),$r(Lr,t))}catch(r){Lr(t,r)}},Ss=Qt.prototype,vs=function(e){WP(this,{type:Es,done:!1,notified:!1,parent:!1,reactions:new HP,rejection:!1,state:am,value:void 0})},vs.prototype=rm(Ss,"then",function(e,t){var r=nu(this),i=uu(FP(this,Qt));return r.parent=!0,i.ok=ys(e)?e:!0,i.fail=ys(t)&&t,i.domain=Ts?pu.domain:void 0,r.state===am?r.reactions.add(i):cu(function(){gm(i,r)}),i.promise}),sm=function(){var a=new vs,e=nu(a);this.promise=a,this.resolve=$r(lu,e),this.reject=$r(Lr,e)},cm.f=uu=function(a){return a===Qt||a===JP?new sm(a):YP(a)},!DP&&ys(Is)&&Rr!==Object.prototype)){nm=Rr.then,GP||rm(Rr,"then",function(e,t){var r=this;return new Qt(function(i,s){Mr(nm,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Rr.constructor}catch(a){}im&&im(Rr,Ss)}CP({global:!0,constructor:!0,wrap:!0,forced:dm},{Promise:Qt});BP(Qt,Es,!1,!0);OP(Es)});var Pm=m((UC,xm)=>{"use strict";var eA=oe(),Im=eA("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,Am)=>{"use strict";var tA=Yt(),rA=Pm(),iA=wr().CONSTRUCTOR;Am.exports=iA||!rA(function(a){tA.all(a).then(void 0,function(){})})});var wm=m(()=>{"use strict";var aA=Ce(),sA=Pe(),nA=st(),oA=kr(),uA=gs(),lA=ds(),cA=mu();aA({target:"Promise",stat:!0,forced:cA},{all:function(e){var t=this,r=oA.f(t),i=r.resolve,s=r.reject,n=uA(function(){var o=nA(t.resolve),u=[],l=0,c=1;lA(e,function(d){var p=l++,h=!1;c++,sA(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 Rm=m(()=>{"use strict";var dA=Ce(),pA=je(),hA=wr().CONSTRUCTOR,gu=Yt(),fA=at(),mA=K(),bA=xr(),km=gu&&gu.prototype;dA({target:"Promise",proto:!0,forced:hA,real:!0},{catch:function(a){return this.then(void 0,a)}});!pA&&mA(gu)&&(bu=fA("Promise").prototype.catch,km.catch!==bu&&bA(km,"catch",bu,{unsafe:!0}));var bu});var $m=m(()=>{"use strict";var gA=Ce(),SA=Pe(),vA=st(),yA=kr(),TA=gs(),IA=ds(),EA=mu();gA({target:"Promise",stat:!0,forced:EA},{race:function(e){var t=this,r=yA.f(t),i=r.reject,s=TA(function(){var n=vA(t.resolve);IA(e,function(o){SA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Lm=m(()=>{"use strict";var xA=Ce(),PA=kr(),AA=wr().CONSTRUCTOR;xA({target:"Promise",stat:!0,forced:AA},{reject:function(e){var t=PA.f(this),r=t.reject;return r(e),t.promise}})});var Su=m((XC,Mm)=>{"use strict";var wA=Ze(),kA=Le(),RA=kr();Mm.exports=function(a,e){if(wA(a),kA(e)&&e.constructor===a)return e;var t=RA.f(a),r=t.resolve;return r(e),t.promise}});var Bm=m(()=>{"use strict";var $A=Ce(),LA=at(),Cm=je(),MA=Yt(),Dm=wr().CONSTRUCTOR,CA=Su(),DA=LA("Promise"),BA=Cm&&!Dm;$A({target:"Promise",stat:!0,forced:Cm||Dm},{resolve:function(e){return CA(BA&&this===DA?MA:this,e)}})});var Om=m(()=>{"use strict";ym();wm();Rm();$m();Lm();Bm()});var Fm=m(()=>{"use strict";var OA=Ce(),VA=je(),xs=Yt(),_A=xe(),_m=at(),Nm=K(),NA=qo(),Vm=Su(),FA=xr(),yu=xs&&xs.prototype,qA=!!xs&&_A(function(){yu.finally.call({then:function(){}},function(){})});OA({target:"Promise",proto:!0,real:!0,forced:qA},{finally:function(a){var e=NA(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)}});!VA&&Nm(xs)&&(vu=_m("Promise").prototype.finally,yu.finally!==vu&&FA(yu,"finally",vu,{unsafe:!0}));var vu});var Ps=m((sD,qm)=>{"use strict";var UA=at();qm.exports=UA});var Hm=m((nD,Um)=>{"use strict";Qh();Om();Fm();var HA=Ps();Um.exports=HA("Promise","finally")});var Gm=m((oD,jm)=>{"use strict";var jA=Hm();jm.exports=jA});var As=m((uD,Wm)=>{"use strict";var GA=Gm();Wm.exports=GA});var gb=m(()=>{"use strict";var yw=Ce(),Tw=di(),Iw=rs(),Ew=ts(),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 Pw=Ps();Sb.exports=Pw("Array","at")});var Tb=m((S0,yb)=>{"use strict";var Aw=vb();yb.exports=Aw});var Li=m((v0,Ib)=>{"use strict";var ww=Tb();Ib.exports=ww});var wg=m(()=>{"use strict"});var kg=m(()=>{"use strict"});var $g=m((A_,Rg)=>{"use strict";var Ck=Le(),Dk=br(),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=gi(),_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=Pe(),qk=Ge(),Uk=oi(),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=di(),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(l,c){var d;switch(Qu(c,0)){case"$":return"$";case"&":return a;case"`":return zu(e,0,t);case"'":return zu(e,n);case"<":d=i[zu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=Gk(p/10);return h===0?l:h<=o?r[h-1]===void 0?Qu(c,1):r[h-1]+Qu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var Ug=m(()=>{"use strict";var zk=Ce(),Kk=Pe(),Xu=fe(),Fg=si(),Jk=K(),Xk=gr(),Zk=$g(),Hr=Mg(),eR=li(),tR=Vg(),rR=Ng(),iR=oe(),aR=je(),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,l,c,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),l=Jk(t),l||(t=Hr(t)),c=u.length,d=uR(1,c),p=Ju(o,u);p!==-1;)h=l?Hr(t(u,p,o)):rR(u,o,p,[],void 0,t),b+=qg(o,f,p)+h,f=p+c,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 lR=Ps();Hg.exports=lR("String","replaceAll")});var Wg=m((D_,Gg)=>{"use strict";var cR=jg();Gg.exports=cR});var Qg=m((B_,Yg)=>{"use strict";var dR=Wg();Yg.exports=dR});var dc="2.0.111-dev.ae3e5b42.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 Ha=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Ha||{}),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 gc,assertNonNullable as Lv,isNonNullable as ja,ValueSubject as Dn,Subject as Mv,Subscription as Cv,merge as Dv,observableFrom as Bv,fromEvent as hc,map as fc,tap as mc,filterChanged as Ov,isNullable as Bn,ErrorCategory as bc}from"@vkontakte/videoplayer-shared";var pc=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 Ga=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=ja((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||pc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:bc.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(){ja(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(hc(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 gc(i.sessionState)}})).add(Dv(hc(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(mc(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),fc(i=>i.castState)),Bv([r.getCastState()])).pipe(Ov(),fc(Vv),mc(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=ja(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Lv(l);let c=l.getCastDevice(),d=(u=(o=l.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:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?ja(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:bc.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 gc(a)}};var GS=Xe(Oo(),1);var rb=Xe(As(),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 WA,Subject as ws,merge as Qm}from"@vkontakte/videoplayer-shared";var C=class{constructor(e){this.transitionStarted$=new ws;this.transitionEnded$=new ws;this.transitionUpdated$=new ws;this.forceChanged$=new ws;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||WA(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 YA}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 YA(a)}};import{assertNever as Cr,assertNonNullable as zt,debounce as Km,ErrorCategory as Jm,fromEvent as Kt,isNonNullable as Xm,map as Zm,merge as eb,observableFrom as QA,Subject as zA,Subscription as Iu,timeout as KA,getHighestQuality as JA}from"@vkontakte/videoplayer-shared";var XA=5,ZA=5,ew=500,tb=7e3,ki=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:Cr(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:Cr(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:Cr(e)}break}default:Cr(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 zA;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)>XA)&&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<ZA&&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:Cr(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$,QA(["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 l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];zt(c);let d=JA(Object.keys(c));zt(d);let p=c[d];zt(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];zt(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];zt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];zt(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];zt(c),r=ae(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Jm.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Cr(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 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(KA(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,Pu=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)),Pu.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=Pu.get(a);e==null||e.unsubscribe(),Pu.delete(a);let t=xu.get(a);xu.delete(a),t?ab(a):ib(a)};import{assertNonNullable as Ri,isNonNullable as tt,isNullable as ow,fromEvent as Dr,merge as sb,observableFrom as nb,filterChanged as ob,map as $i,Subject as ub,Subscription as uw,ValueSubject as lw,ErrorCategory as cw}from"@vkontakte/videoplayer-shared";import{isNonNullable as Au,isNullable as sw,Subscription as nw}from"@vkontakte/videoplayer-shared";var ks=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=sw(i),l=new nw;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},et=(a,e,t)=>ks(e,()=>a.loop,r=>{Au(r)&&(a.loop=r)},{onError:t}),ge=(a,e,t,r)=>ks(e,()=>({muted:a.muted,volume:a.volume}),i=>{Au(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)=>ks(e,()=>a.playbackRate,i=>{Au(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Pt=ks;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 lw(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:cw.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Pt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{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($i(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Pt(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($i(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Pt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Pt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ri(this.video);let{textTracks:e}=this.video;this.subscription.add(Dr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(sb(Dr(e,"addtrack"),Dr(e,"removetrack"),nb(["init"])).pipe($i(()=>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(Dr(e,"change"),nb(["init"])).pipe($i(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),$i(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(Dr(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(Dr(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){Ri(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){Ri(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){Ri(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){Ri(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)}},rt=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 lb=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},ku=a=>{let e=lb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},cb=a=>{let e=lb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Be,map as At,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=>Be(a,v).pipe(mb(void 0)),r=pb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>Be(a,v))).pipe(At(v=>v.type==="ended"?a.readyState<2:a.readyState<3),fw()),i=pb(Be(a,"progress"),Be(a,"timeupdate")).pipe(At(()=>db(a.buffered,a.currentTime))),s=vw.isSafari?bw({play:e("play").pipe(gw()),playing:e("playing")}).pipe(mb(void 0)):e("playing"),n=Be(a,"volumechange").pipe(At(()=>({muted:a.muted,volume:a.volume}))),o=Be(a,"ratechange").pipe(At(()=>a.playbackRate)),u=Be(a,"error").pipe(fb(()=>!!(a.error||a.played.length)),At(()=>{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}})),l=Be(a,"timeupdate").pipe(At(()=>a.currentTime)),c=new mw,d=.3,p;l.subscribe(v=>{a.loop&&hb(p)&&hb(v)&&p>=a.duration-d&&v<=d&&c.next(p),p=v});let h=e("pause").pipe(fb(()=>!a.error&&p!==a.duration)),f=Be(a,"enterpictureinpicture"),b=Be(a,"leavepictureinpicture"),g=new bb(cb(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new bb(ku(a));return Be(a,"fullscreenchange").pipe(At(()=>ku(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$:Be(a,"durationchange").pipe(At(()=>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(Li(),1);import{isNonNullable as ve,isNullable as $u,now as $b,isHigher as Lu,isHigherOrEqual as Ab,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,lt={},Eb=a=>{Ru=a},xb=()=>{lt={}},Pb=a=>{a(lt)},Mi=(a,e)=>{var t;Ru&&(lt.meta=(t=lt.meta)!=null?t:{},lt.meta[a]=e)},ue=class{constructor(e){this.name=e}next(e){var r,i;if(!Ru)return;lt.series=(r=lt.series)!=null?r:{};let t=(i=lt.series[this.name])!=null?i:[];t.push([Date.now(),e]),lt.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)),Ci=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',Rs=(a,e,t,r)=>{var u;let i=[...e].sort(Cu(1)),s=[...t].sort(Cu(1)),n=s.filter(l=>ve(l.bitrate)&&ve(a.bitrate)?a.bitrate/l.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
7
  [last ${n} selected] ${o}
8
- `}),s}return r==null||r.recordSwitch(t),t},Tt=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:c,visible:l,droppedVideoMaxQualityLimit:d,abrLogger:p})=>{var H,N,L,F,_;db(a,hb);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&&gw(f),g=r.considerPlaybackRate&&Se(o)?o:1,S=a.filter(w=>!ob(w.quality)).sort((w,x)=>vu(w.quality,x.quality)?-1:1),T=(N=(0,Ht.default)(S,-1))==null?void 0:N.quality,v=(L=(0,Ht.default)(S,0))==null?void 0:L.quality,y=Su(i)||Se(i.min)&&Se(i.max)&&yu(i.max,i.min)||Se(i.min)&&v&&vu(i.min,v)||Se(i.max)&&T&&yu(i.max,T),I=g*pb(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),$={},O=S.filter(w=>{if(!(b?yu(w.quality,b):!0))return $[w.quality]="FitsContainer",!1;if(!(Se(t)&&isFinite(t)&&Se(w.bitrate)?t-s>=w.bitrate*I:!0))return $[w.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&Se(r.minBufferToSwitchUp)&&u&&!ob(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&vu(w.quality,u.quality))return $[w.quality]="Buffer",!1;if(!!d&&nb(w.quality,d))return $[w.quality]="DroppedFramesLimit",!1;let X=y||(Su(i.max)||ub(w.quality,i.max))&&(Su(i.min)||nb(w.quality,i.min)),ce=Se(l)&&!l?ub(w.quality,r.backgroundVideoQualityLimit):!0;return!X||!ce?($[w.quality]="FitsQualityLimits",!1):!0})[0];O&&O.bitrate&&vw.next(O.bitrate);let C=(F=O!=null?O:S[Math.ceil((S.length-1)/2)])!=null?F:a[0];return C.quality!==((_=c==null?void 0:c.last)==null?void 0:_.quality)&&p({message:`
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:l,visible:c,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&&Ab(k.quality,d))return $[k.quality]="DroppedFramesLimit",!1;let Z=y||($u(i.max)||kb(k.quality,i.max))&&($u(i.min)||Ab(k.quality,i.min)),ce=ve(c)&&!c?kb(k.quality,r.backgroundVideoQualityLimit):!0;return!Z||!ce?($[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!==((_=l==null?void 0:l.last)==null?void 0:_.quality)&&p({message:`
9
9
  [VIDEO TRACKS ABR]
10
10
  [available video tracks]
11
- ${a.map(w=>`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate} }`).join(`
11
+ ${a.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
12
12
  `)}
13
13
 
14
14
  [tuning]
15
- ${Object.entries(r!=null?r:{}).map(([w,x])=>`${w}: ${x}`).join(`
15
+ ${Object.entries(r!=null?r:{}).map(([k,x])=>`${k}: ${x}`).join(`
16
16
  `)}
17
17
 
18
18
  [limit params]
@@ -30,12 +30,12 @@ var pv=Object.create;var gn=Object.defineProperty,hv=Object.defineProperties,fv=
30
30
  minQualityLimit: ${i==null?void 0:i.min},
31
31
 
32
32
  [limited video tracks]
33
- ${Object.entries($).map(([w,x])=>`${w}: ${x}`).join(`
33
+ ${Object.entries($).map(([k,x])=>`${k}: ${x}`).join(`
34
34
  `)||"All tracks are available"}
35
35
 
36
- [best video track] ${O==null?void 0:O.quality}
37
- [selected video track] ${C==null?void 0:C.quality}
38
- `}),fb(r,p,C,c)},mb=(a,e,t,{throughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var f;db(t,hb);let c=i.considerPlaybackRate&&Se(s)?s:1,l=[...t].sort(Tu(-1)),d=a.bitrate;Sw(d);let p=c*pb(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),h;return Se(r)&&isFinite(r)&&(h=l.find(b=>Se(b.bitrate)?r-d>=b.bitrate*p:!0)),h||(h=ps(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:`
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,l)},Bb=(a,e,t,{throughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var f;Lb(t,Cb);let l=i.considerPlaybackRate&&ve(s)?s:1,c=[...t].sort(Cu(-1)),d=a.bitrate;Rw(d);let p=l*Mb(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),h;return ve(r)&&isFinite(r)&&(h=c.find(b=>ve(b.bitrate)?r-d>=b.bitrate*p:!0)),h||(h=Rs(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
39
  [AUDIO TRACKS ABR]
40
40
  [available audio tracks]
41
41
  ${t.map(b=>`{ id: ${b.id}, bitrate: ${b.bitrate} }`).join(`
@@ -49,13 +49,13 @@ var pv=Object.create;var gn=Object.defineProperty,hv=Object.defineProperties,fv=
49
49
  throughput: ${r},
50
50
  reserve: ${d},
51
51
  playbackRate: ${s},
52
- playbackRateFactor: ${c},
52
+ playbackRateFactor: ${l},
53
53
  forwardBufferHealth: ${n},
54
54
  bitrateFactor: ${p},
55
55
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
56
56
 
57
57
  [selected audio track] ${h==null?void 0:h.id}
58
- `}),h&&fb(i,u,h,o)};var re=a=>new URL(a).hostname;import{assertNever as Tb,assertNonNullable as Ib,combine as Nw,debounce as Fw,ErrorCategory as Eb,filter as xb,filterChanged as qw,isNonNullable as Au,map as gs,merge as Pb,observableFrom as Uw,once as Hw,Subscription as jw,ValueSubject as wu,videoQualityToHeight as Gw,videoSizeToQuality as Ww}from"@vkontakte/videoplayer-shared";var bb=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},ve=a=>R(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!bb(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return bb(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as fs,isNullable as Iw,assertNonNullable as xi}from"@vkontakte/videoplayer-shared";import{isNonNullable as gb,assertNonNullable as hs,now as yw}from"@vkontakte/videoplayer-shared";function ie(){return yw()}function Iu(a){return ie()-a}function Eu(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 Sb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Pr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,c=0,l,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;hs(l);let L=Iu(l),F;if(L<b){F=b-L,setTimeout(g,F);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,$()},S=L=>(s=L,N),T=L=>(d=L,N),v=()=>(h="json",N),y=()=>{if(!u){if(--c>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=L=>(p=L,N),$=()=>{l=ie(),n=new i,n.open("get",a);let L=0,F,_=0,w=()=>(hs(l),Math.max(l,Math.max(F||0,_||0)));if(s&&n.addEventListener("progress",x=>{let D=ie();s.updateChunk&&x.loaded>L&&(s.updateChunk(w(),x.loaded-L),L=x.loaded,F=D)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;hs(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let D=n.response.byteLength-L;D&&s.updateChunk&&s.updateChunk(w(),D)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),p){let x=()=>{hs(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)=>(gb(L)&&(b=L),gb(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 Ii=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 Ei=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ie(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ie()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Pr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ie()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ie();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var ms=1e4,xu=3;var Ew=6e4,xw=10,Pw=1,Aw=500,Pi=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 Ii(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Eu(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=Eu(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||fs(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 Ei(xu,ms,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,c=null,l=!1,d=()=>{let y=s&&(!l||l===this.rep);return y||t("Not running!"),y},p=(y,I,$)=>{u&&u.abort(),u=Pr(this.urlResolver.resolve(y,!1),I,$,()=>this._retryCallback()).withTimeout(ms).withBitrateReporting(this.bitrateSwitcher).withRetryCount(xu).withFinally(()=>{u=null}).send()},h=(y,I,$)=>{xi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),I,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=y=>{let I=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${I}=>${y}`),r.playbackRate=y)},b=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let $=ie()-1e4,G=0;for(let C=0;C<this.bufferStates.length;C++){let H=this.bufferStates[C];y=Math.min(y,H.buf),H.ts<$&&G++}this.bufferStates.splice(0,G),t(`update playback rate; minBuffer=${y} drop=${G} jitter=${this.sourceJitter}`);let O=y-Pw;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?f(1.15):O>1?f(1.1):O>.3?f(1.05):f(1)}},S=y=>{let I,$=()=>I&&I.start?I.start.length:0,G=x=>I.start[x]/1e3,O=x=>I.dur[x]/1e3,C=x=>I.fragIndex+x,H=(x,D)=>({chunkIdx:C(x),startTS:G(x),dur:O(x),discontinuity:D}),N=()=>{let x=0;if(I&&I.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Q=D;this.sourceJitter>1&&(Q+=this.sourceJitter-1);let X=I.dur.length-1;for(;X>=0&&(Q-=I.dur[X],!(Q<=0));--X);x=Math.min(X,I.dur.length-1-W),x=Math.max(x,0)}return H(x,!0)},L=x=>{let D=$();if(!(D<=0)){if(fs(x)){for(let W=0;W<D;W++)if(G(W)>x)return H(W)}return N()}},F=x=>{let D=$(),W=x?x.chunkIdx+1:0,Q=W-I.fragIndex;if(!(D<=0)){if(!x||Q<0||Q-D>xw)return t(`Resync: offset=${Q} bChunks=${D} chunk=`+JSON.stringify(x)),N();if(!(Q>=D))return H(W-I.fragIndex,!1)}},_=(x,D,W)=>{c&&c.abort(),c=Pr(this.urlResolver.resolve(x,!0,this.lowLatency),D,W,()=>this._retryCallback()).withTimeout(ms).withRetryCount(xu).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(x,D)=>{_(y,W=>{if(!d())return;I=W;let Q=!!I.lowLatency;Q!==this.lowLatency&&b(Q);let X=0;for(let ce=0;ce<I.dur.length;++ce)X+=I.dur[ce];X>0&&(xi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(X/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,x(L(D))},()=>this._handleNetworkError())},nextChunk:F}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),xi(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:y=>{let{videoElement:I,logger:$}=this.params,G=S(e.jidxUrl),O,C,H,N,L=0,F,_,w,x=()=>{F&&(clearTimeout(F),F=void 0);let A=Math.max(Aw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),le=L+A,Ie=ie(),ke=Math.min(1e4,le-Ie);L=Ie;let pt=()=>{c||d()&&G.seek(()=>{d()&&(L=ie(),D(),x())})};ke>0?F=window.setTimeout(()=>{this.paused?x():pt()},ke):pt()},D=()=>{let A;for(;A=G.nextChunk(N);)N=A,kt(A);let le=G.nextChunk(H);if(le){if(H&&le.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?x():(T(),this._initPlayerWith(e));return}ce(le)}else x()},W=(A,le)=>{if(!d()||!this.sourceBuffer)return;let Ie,ke,pt,tr=ht=>{window.setTimeout(()=>{d()&&W(A,le)},ht)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),tr(100);else{let ht=ie(),Rt=I.currentTime;!this.paused&&I.buffered.length>1&&_===Rt&&ht-w>500&&($("Stall suspected; trying to fix"),this._fixupStall()),_!==Rt&&(_=Rt,w=ht);let rr=this._getBufferSizeSec();if(rr>30)$(`Buffered ${rr} seconds; delaying appendBuffer`),tr(2e3);else try{this.sourceBuffer.appendBuffer(A),this.videoPlayStarted?(this.bufferStates.push({ts:ht,buf:rr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),le&&le()}catch(qr){if(qr.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),pt=this.sourceBuffer.buffered.length,pt!==0&&(Ie=this.sourceBuffer.buffered.start(0),ke=Rt,ke-Ie>4&&this.sourceBuffer.remove(Ie,ke-3)),tr(1e3);else throw qr}}},Q=()=>{C&&O&&($([`Appending chunk, sz=${C.byteLength}:`,JSON.stringify(H)]),W(C,function(){C=null,D()}))},X=A=>e.fragUrlTemplate.replace("%%id%%",A.chunkIdx),ce=A=>{d()&&h(X(A),(le,Ie)=>{if(d()){if(Ie/=1e3,C=le,H=A,n=A.startTS,Ie){let ke=Math.min(10,A.dur/Ie);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ke:ke}Q()}},()=>this._handleNetworkError())},kt=A=>{d()&&(xi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(X(A),!1)))},dt=A=>{d()&&(e.cachedHeader=A,W(A,()=>{O=!0,Q()}))};s=!0,G.seek(A=>{if(d()){if(L=ie(),!A){x();return}N=A,!Iw(y)||A.startTS>y?ce(A):(H=A,D())}},y),e.cachedHeader?dt(e.cachedHeader):p(e.headerUrl,dt,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},l}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),fs(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,xi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return fs(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&&Iu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&c(),h},notifySwitch:d=>{let p=ie();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Pr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ms).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;ve(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,c)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Ew))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as ww,filter as vb,fromEvent as kw,interval as Rw,isHigher as $w,isInvariantQuality as Lw,isLower as Mw,merge as Cw,Subject as yb,Subscription as Dw}from"@vkontakte/videoplayer-shared";var Pu=class{constructor(){this.onDroopedVideoFramesLimit$=new yb;this.subscription=new Dw;this.playing=!1;this.tracks=[];this.forceChecker$=new yb;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&&!Lw(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&&$w(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(kw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Rw(this.droppedFramesChecker.checkTime).pipe(vb(()=>this.playing),vb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(ww(this.droppedFramesChecker.checkTime)),r=Cw(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>Mw(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}},bs=Pu;import{map as Bw,Observable as Ow}from"@vkontakte/videoplayer-shared";import{fromEvent as Vw}from"@vkontakte/videoplayer-shared";var Ai=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var _w=(a,e)=>new Ow(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ai()))},k(k({},r),e));i.observe(a);let s=Vw(document,"visibilitychange").pipe(Bw(n=>!document.hidden||Ai())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Be=_w;var Yw=["paused","playing","ready"],Qw=["paused","playing","ready"],wi=class{constructor(e){this.subscription=new jw;this.videoState=new M("stopped");this.representations$=new wu([]);this.textTracksManager=new Ce;this.droppedFramesManager=new bs;this.maxSeekBackTime$=new wu(1/0);this.zeroTime$=new wu(void 0);this.liveOffset=new rt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Eb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let c=(t=u.name)!=null?t:u.index.toString(10),l=(r=yt(u.name))!=null?r:Ww(u.video),d=u.bitrate/1e3,p=k({},u.video);if(!l)continue;let h={id:c,quality:l,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Au(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(Qw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Yw.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 Tb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Eb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Pb(this.videoState.stateChangeStarted$.pipe(gs(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(gs(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=fe(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=ge(this.video);this.subscription.add(this.representations$.pipe(gs(i=>i.map(({track:s})=>s)),xb(i=>!!i.length),Hw()).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(qw(),gs(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Nw({zeroTime:this.zeroTime$.pipe(xb(Au)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(Ke(this.video,this.params.desiredState.isLooped,t)).add(be(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Me(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&Gw(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 Tb(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$,Uw(["init"])).pipe(Fw(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 Pi({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&&Au(t)?t:Tt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;Ib(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;Ib(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 Ab=wi;var at=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as SR,assertNonNullable as vR,debounce as yR,ErrorCategory as tc,filter as Xg,filterChanged as rc,fromEvent as TR,isNonNullable as IR,map as Zg,merge as Us,observableFrom as ER,observeElementSize as xR,once as eS,Subscription as PR,ValueSubject as AR}from"@vkontakte/videoplayer-shared";var Ss=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Ar=class extends Ss{constructor(){super(),this.listeners||Ss.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},ki=class{constructor(){Object.defineProperty(this,"signal",{value:new Ar,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ki.prototype[Symbol.toStringTag]="AbortController",Ar.prototype[Symbol.toStringTag]="AbortSignal");function vs(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 ku(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!vs({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 Ri=vs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),wb=Ri?ku({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,st=Ri?wb.fetch:window.fetch,LB=Ri?wb.Request:window.Request,nt=Ri?ki:window.AbortController,MB=Ri?Ar:window.AbortSignal;var Fb=Qe(vi(),1);var ot=()=>window.ManagedMediaSource||window.MediaSource,ys=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},kb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Rb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Rs,clientChecker as ks}from"@vkontakte/videoplayer-shared";var Oe=document.createElement("video"),Jw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Xw='video/mp4; codecs="hev1.1.6.L93.B0"',qb='video/webm; codecs="vp09.00.10.08"',Ub='video/webm; codecs="av01.0.00M.08"',Zw='audio/mp4; codecs="mp4a.40.2"',ek='audio/webm; codecs="opus"',$b,Lb,jt={mms:ys(),mse:kb(),hls:!!(($b=Oe.canPlayType)!=null&&$b.call(Oe,"application/x-mpegurl")||(Lb=Oe.canPlayType)!=null&&Lb.call(Oe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Mb,Cb,ye={mp4:!!((Mb=Oe.canPlayType)!=null&&Mb.call(Oe,"video/mp4")),webm:!!((Cb=Oe.canPlayType)!=null&&Cb.call(Oe,"video/webm")),cmaf:!0},Is,Db,Es,Bb,xs,Ob,Ps,Vb,As,_b,ws,Nb,Te={h264:!!((Db=(Is=ot())==null?void 0:Is.isTypeSupported)!=null&&Db.call(Is,Jw)),h265:!!((Bb=(Es=ot())==null?void 0:Es.isTypeSupported)!=null&&Bb.call(Es,Xw)),vp9:!!((Ob=(xs=ot())==null?void 0:xs.isTypeSupported)!=null&&Ob.call(xs,qb)),av1:!!((Vb=(Ps=ot())==null?void 0:Ps.isTypeSupported)!=null&&Vb.call(Ps,Ub)),aac:!!((_b=(As=ot())==null?void 0:As.isTypeSupported)!=null&&_b.call(As,Zw)),opus:!!((Nb=(ws=ot())==null?void 0:ws.isTypeSupported)!=null&&Nb.call(ws,ek))},wr=(Te.h264||Te.h265)&&Te.aac,Gt,tk=()=>R(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(V(k({},a),{video:V(k({},a.video),{contentType:Ub})})),window.navigator.mediaCapabilities.decodingInfo(V(k({},a),{video:V(k({},a.video),{contentType:qb})}))]);Gt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{tk()}catch(a){console.error(a)}var kr=jt.hls&&ye.mp4,Hb=()=>Object.keys(Te).filter(a=>Te[a]),jb=(a,e=!1,t=!1)=>{let r=jt.mse||jt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&ye.mp4&&wr;case"DASH_WEBM":return r&&ye.webm&&Te.vp9&&Te.opus;case"DASH_WEBM_AV1":return r&&ye.webm&&Te.av1&&Te.opus;case"DASH_STREAMS":return r&&(ye.mp4&&wr||ye.webm&&(Te.vp9||Te.av1)&&(Te.opus||Te.aac));case"DASH_LIVE":return jt.mse&&ye.mp4&&wr;case"DASH_LIVE_CMAF":return r&&ye.mp4&&wr&&ye.cmaf;case"DASH_ONDEMAND":return r&&ye.mp4&&wr;case"HLS":case"HLS_ONDEMAND":return kr||e&&jt.mse&&ye.mp4&&wr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return kr;case"MPEG":return ye.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return jt.webrtc&&jt.ws&&Te.h264&&(ye.mp4||ye.webm);default:return Rs(i)}})},Ts=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Gt?Gt[t].smooth?[t,e]:Gt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Gt?Gt[t].powerEfficient?[t,e]:Gt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Rs(a)}return[e,t]},Gb=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Ts(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ks.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",...Ts(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ts(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ts(a),...i,"HLS","HLS_ONDEMAND"];default:Rs(e)}return kr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Wb=({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=ks.isMac&&ks.isSafari;if(ks.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:Rs(a)}else kr&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Ru=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Yb=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,Fb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as $i}from"@vkontakte/videoplayer-shared";var Qb=a=>{if(!a)return{id:"EmptyResponse",category:$i.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:$i.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:$i.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:$i.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:$i.PARSER,message:"Response is valid XML, but parser failed"}};var Rr=(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 Xu,assertNonNullable as Zt,combine as Os,ErrorCategory as Et,filter as Vs,filterChanged as Gg,fromEvent as Vr,interval as Zu,isNonNullable as Wg,map as ec,merge as _r,Subject as Yg,Subscription as Qg,tap as lR,throttle as dR,clientChecker as pR,ValueSubject as oe,flattenObject as sa,getTraceSubscriptionMethod as hR}from"@vkontakte/videoplayer-shared";var Br=Qe(vi(),1);var rk=(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)},ik=a=>window.clearTimeout(a),zb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",$u=zb?rk:window.requestIdleCallback,YB=zb?ik:window.cancelIdleCallback;var _g=Qe(cs(),1);import{assertNever as ak,ErrorCategory as Kb,clientChecker as Lu,Subject as Jb}from"@vkontakte/videoplayer-shared";var sk=16,Xb=!1;try{Xb=Lu.isSafari&&!!Lu.macVersion&&Lu.macVersion<=sk}catch(a){console.error(a)}var Mu=class{constructor(e){this.bufferFull$=new Jb;this.error$=new Jb;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:Kb.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;Xb&&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:Kb.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:ak(t)}}},Zb=Mu;var Cu=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 Dr,assertNonNullable as Ve,ErrorCategory as Kt,fromEvent as Wu,getExponentialDelay as Yu,isNonNullable as Qu,isNullable as _e,once as rR,Subject as iR,Subscription as aR,ValueSubject as Zi}from"@vkontakte/videoplayer-shared";var j=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var $r=class extends j{};var Li=class extends j{};var Mi=class extends j{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var Ci=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var J=class extends j{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Wt=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}};var Oi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends J{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ni=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Fi=class extends J{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var qi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Hi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Wi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yi=class extends J{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Qi=class extends J{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var zi=class extends J{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var ok={ftyp:Mi,moov:Ci,moof:Di,mdat:Bi,sidx:Wt,trak:Oi,mdia:qi,mfhd:Gi,tkhd:Ui,traf:Wi,tfhd:Yi,tfdt:Qi,trun:zi,minf:Hi,sv3d:Vi,st3d:_i,prhd:Ni,proj:ji,equi:Fi,uuid:Li,unknown:$r},Yt=class a{constructor(e={}){this.options=k({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=ok[e];return r?new r(t,new a):new $r(t,new a)}};var Lr=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 ck=new TextDecoder("ascii"),lk=a=>ck.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",dk=a=>{let e=new Wt(a,new Yt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},pk=(a,e)=>{let r=new Yt().parse(a),i=new Lr(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)},hk=(a,e)=>{let r=new Yt().parse(a),s=new Lr(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},fk=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Yt().parse(a),i=new Lr(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},eg={validateData:lk,parseInit:fk,getIndexRange:()=>{},parseSegments:dk,parseFeedableSegmentChunk:pk,getSegmentEndTime:hk};import{assertNonNullable as Bu,isNonNullable as ag,isNullable as bk}from"@vkontakte/videoplayer-shared";import{assertNever as mk}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"}},rg=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Ki(a,t),i=r in 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=Ki(u),d=c*Ye(2,(o-1)*8)+l,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Ki=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*Ye(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*Ye(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*Ye(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},je=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ki(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:mk(e)}},Qt=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=rg(r);if(!e(i))return;i.type==="master"&&Qt(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},ig=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=rg(a);return Qt(i.value,({tag:s,type:n,value:o})=>(s===17143?e=je(o,n):s===17026?t=je(o,n):s===17029&&(r=je(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var sg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],gk=[231,22612,22743,167,171,163,160,175],Sk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,c,l=!1,d=0;return Qt(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=je(f,h);c=Ki(g)}else p!==21420&&(c=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=je(f,h):p===17545?i=je(f,h):p===21420&&c===475249515?u=je(f,h):p===374648427?Qt(f,({tag:g,type:S,value:T})=>g===30321?(l=je(T,S)===1,!1):!0):s&&n&&sg.includes(p)&&(o=!0),!o}),Bu(e,"Failed to parse webm Segment start"),Bu(t,"Failed to parse webm Segment end"),Bu(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}}}},vk=a=>{if(bk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},yk=(a,e)=>{let t=!1,r=!1,i=o=>ag(o.time)&&ag(o.position),s=[],n;return Qt(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=je(c,u));break;case 183:break;case 241:n&&(n.position=je(c,u));break;default:t&&sg.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}}})},Tk=a=>{let e=0,t=!1;try{Qt(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):gk.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},ng={validateData:ig,parseInit:Sk,getIndexRange:vk,parseSegments:yk,parseFeedableSegmentChunk:Tk};var Mr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return ng;case"mp4":return eg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Uu=Qe(kg(),1);var qu=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 $g,isNullable as Lg}from"@vkontakte/videoplayer-shared";var Rg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Mg=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},zt=(a,e)=>{let t=a;t=(0,Uu.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,Uu.default)(t,n,(o,u)=>Lg(s)?o:Lg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Dg=(a,e)=>{var y,I,$,G,O,C,H,N,L,F,_,w,x,D,W,Q,X,ce,kt,dt,A,le,Ie,ke,pt,tr,ht,Rt,rr,qr,Sc,vc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc,Rc,$c,Lc,Mc,Cc,Dc,Bc,Oc,Vc;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=Mg(h);else if(f){let de=Mg(f);$g(de)&&(p=de)}else g&&(p=parseInt(g,10));let S=0,T=(O=(G=s.getAttribute("profiles"))==null?void 0:G.split(","))!=null?O:[];for(let de of u){let GS=(C=de.getAttribute("id"))!=null?C:"id"+(S++).toString(10),Ur=(H=de.getAttribute("mimeType"))!=null?H:"",an=(N=de.getAttribute("codecs"))!=null?N:"",sn=(L=de.getAttribute("contentType"))!=null?L:Ur==null?void 0:Ur.split("/")[0],WS=(_=(F=de.getAttribute("profiles"))==null?void 0:F.split(","))!=null?_:[],YS=(w=de.getAttribute("lang"))!=null?w:void 0,QS=(W=(D=(x=de.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:D.trim())!=null?W:void 0,zS=de.querySelectorAll("Representation"),KS=de.querySelector("SegmentTemplate"),JS=(X=(Q=de.querySelector("Role"))==null?void 0:Q.getAttribute("value"))!=null?X:void 0,Hr=sn,ee={id:GS,language:YS,isDefault:JS==="main",label:QS,codecs:an,hdr:Hr==="video"&&qu(an),mime:Ur,representations:[]};for(let Z of zS){let XS=(ce=Z.getAttribute("lang"))!=null?ce:void 0,ZS=(kt=Z.getAttribute("label"))!=null?kt:void 0,ev=(le=(A=(dt=Z.querySelector("BaseURL"))==null?void 0:dt.textContent)==null?void 0:A.trim())!=null?le:"",nn=new URL(ev||o,e).toString(),ir=(Ie=Z.getAttribute("mimeType"))!=null?Ie:Ur,ya=(pt=(ke=Z.getAttribute("codecs"))!=null?ke:an)!=null?pt:"",on;if(sn==="text"){let $t=Z.getAttribute("id")||"",un=$t.includes("_auto");on={id:$t,isAuto:un,kind:"text",url:nn}}else{let $t=(ht=(tr=Z.getAttribute("contentType"))!=null?tr:ir==null?void 0:ir.split("/")[0])!=null?ht:sn,un=(rr=(Rt=de.getAttribute("profiles"))==null?void 0:Rt.split(","))!=null?rr:[],tv=parseInt((qr=Z.getAttribute("width"))!=null?qr:"",10),_c=parseInt((Sc=Z.getAttribute("height"))!=null?Sc:"",10),Nc=parseInt((vc=Z.getAttribute("bandwidth"))!=null?vc:"",10)/1e3,Fc=(yc=Z.getAttribute("frameRate"))!=null?yc:"",rv=(Tc=Z.getAttribute("quality"))!=null?Tc:void 0,iv=Fc?Rg(Fc):void 0,av=(Ic=Z.getAttribute("id"))!=null?Ic:"id"+(S++).toString(10),sv=$t==="video"?`${_c}p`:$t==="audio"?`${Nc}Kbps`:ya,nv=`${av}@${sv}`,ov=[...T,...WS,...un],cn,uv=Z.querySelector("SegmentBase"),Lt=(Ec=Z.querySelector("SegmentTemplate"))!=null?Ec:KS;if(uv){let Mt=(Pc=(xc=Z.querySelector("SegmentBase Initialization"))==null?void 0:xc.getAttribute("range"))!=null?Pc:"",[Ct,dn]=Mt.split("-").map(ar=>parseInt(ar,10)),ft={from:Ct,to:dn},jr=(Ac=Z.querySelector("SegmentBase"))==null?void 0:Ac.getAttribute("indexRange"),[pn,Ta]=jr?jr.split("-").map(ar=>parseInt(ar,10)):[],Gr=jr?{from:pn,to:Ta}:void 0;cn={type:"byteRange",url:nn,initRange:ft,indexRange:Gr}}else if(Lt){let Mt={representationId:(wc=Z.getAttribute("id"))!=null?wc:void 0,bandwidth:(kc=Z.getAttribute("bandwidth"))!=null?kc:void 0},Ct=parseInt((Rc=Lt.getAttribute("timescale"))!=null?Rc:"",10),dn=($c=Lt.getAttribute("initialization"))!=null?$c:"",ft=Lt.getAttribute("media"),jr=(Mc=parseInt((Lc=Lt.getAttribute("startNumber"))!=null?Lc:"",10))!=null?Mc:1,pn=zt(dn,Mt);if(!ft)throw new ReferenceError("No media attribute in SegmentTemplate");let Ta=(Cc=Lt.querySelectorAll("SegmentTimeline S"))!=null?Cc:[],Gr=[],ar=0,hn="",fn=0;if(Ta.length){let Ia=jr,Ne=0;for(let sr of Ta){let We=parseInt((Dc=sr.getAttribute("d"))!=null?Dc:"",10),Dt=parseInt((Bc=sr.getAttribute("r"))!=null?Bc:"",10)||0,Ea=parseInt((Oc=sr.getAttribute("t"))!=null?Oc:"",10);Ne=Number.isFinite(Ea)?Ea:Ne;let mn=We/Ct*1e3,bn=Ne/Ct*1e3;for(let xa=0;xa<Dt+1;xa++){let lv=zt(ft,V(k({},Mt),{segmentNumber:Ia.toString(10),segmentTime:(Ne+xa*We).toString(10)})),qc=(bn!=null?bn:0)+xa*mn,dv=qc+mn;Ia++,Gr.push({time:{from:qc,to:dv},url:lv})}Ne+=(Dt+1)*We,ar+=(Dt+1)*mn}fn=Ne/Ct*1e3,hn=zt(ft,V(k({},Mt),{segmentNumber:Ia.toString(10),segmentTime:Ne.toString(10)}))}else if($g(p)){let Ne=parseInt((Vc=Lt.getAttribute("duration"))!=null?Vc:"",10)/Ct*1e3,sr=Math.ceil(p/Ne),We=0;for(let Dt=1;Dt<sr;Dt++){let Ea=zt(ft,V(k({},Mt),{segmentNumber:Dt.toString(10),segmentTime:We.toString(10)}));Gr.push({time:{from:We,to:We+Ne},url:Ea}),We+=Ne}fn=We,hn=zt(ft,V(k({},Mt),{segmentNumber:sr.toString(10),segmentTime:We.toString(10)}))}let cv={time:{from:fn,to:1/0},url:hn};cn={type:"template",baseUrl:nn,segmentTemplateUrl:ft,initUrl:pn,totalSegmentsDurationMs:ar,segments:Gr,nextSegmentBeyondManifest:cv,timescale:Ct}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!$t||!ir)continue;let ln={video:"video",audio:"audio",text:"text"}[$t];if(!ln)continue;Hr||(Hr=ln),on={id:nv,kind:ln,segmentReference:cn,profiles:ov,duration:p,bitrate:Nc,mime:ir,codecs:ya,width:tv,height:_c,fps:iv,quality:rv}}ee.language||(ee.language=XS),ee.label||(ee.label=ZS),ee.mime||(ee.mime=ir),ee.codecs||(ee.codecs=ya),ee.hdr||(ee.hdr=Hr==="video"&&qu(ya)),ee.representations.push(on)}Hr&&i[Hr].push(ee)}return{dynamic:c,liveAvailabilityStartTime:d,duration:p,streams:i}};var Ji=Qe(vi(),1);import{videoSizeToQuality as tR}from"@vkontakte/videoplayer-shared";var Bg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?yt(s):void 0)!=null?o:tR({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},Og=({id:a,bitrate:e})=>({id:a,bitrate:e}),$s=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Ji.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Ji.default)(t,-1)},Vg=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),ju=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Ji.default)(r.split("."),0),isDefault:i}),Gu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Ji.default)(i.split("."),0)}),Ls=a=>"url"in a,ut=a=>a.type==="template",Xi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ea=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new Zi(0);this.onLastSegment$=new Zi(!1);this.fullyBuffered$=new Zi(!1);this.playingRepresentation$=new Zi(void 0);this.playingRepresentationInit$=new Zi(void 0);this.error$=new iR;this.gaps=[];this.subscription=new aR;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new nt;this.destroyAbortController=new nt;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Dr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){let t=this.representations.get(e);Ve(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Zb(this.sourceBuffer),this.subscription.add(Wu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Kt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Kt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Wu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Kt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,Cu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=at(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,c<l)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Ve(r,"No init buffer for starting representation"),Ve(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=Dr(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);Ve(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(_e(s)||_e(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Ve(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();Qu(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),yield new vn(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Dr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){var u,c;let t=(u=e==null?void 0:e.flatMap(l=>l.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let d=t.find(f=>f.id===l);d&&this.representations.set(l,d);let p=this.representations.get(l);if(!p||!ut(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(c=this.switchingToRepresentationId)!=null?c:this.downloadingRepresentationId,i=this.representations.get(r);Ve(i);let s=this.segments.get(r);Ve(s,"No segments for starting representation");let n=this.initData.get(r);if(Ve(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.dynamic),this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new nt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;if(_e(e)||_e(this.downloadingRepresentationId)||_e(this.playingRepresentationId)||_e(this.sourceBuffer)||!_e(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ve(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((c=i==null?void 0:i.time.to)!=null?c:0)-((l=i==null?void 0:i.time.from)!=null?l:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=at(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&Cu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=at(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let p=(0,Br.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&at(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Br.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;Qu(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!ut(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>V(k({},p),{status:"none",size:void 0})),c=(i=this.segments.get(o.id))!=null?i:[],l=(n=(s=(0,Br.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;Ve(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!ut(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),c=zt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&!(Rr(this.sourceBuffer.buffered,p)&&Rr(this.sourceBuffer.buffered,h)))&&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 Dr(o,function(){return te(this,null,function*(){let l=Yu(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=Mr(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&c?yield Promise.all(c):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Xi(l)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return R(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Dr(n,function(){return te(this,null,function*(){let u=Yu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),Wu(window,"online").pipe(rR()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Xi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(ut(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Br.default)(e,0).byte.from,to:(0,Br.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Kt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ut(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,l)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Kt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Mr(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();Qu(y)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-y,this.bufferAccumulation.accumulated.push({segmentView:v,segmentProgress:l}),this.activeSegments.delete(l));let I=({segmentView:$,segmentProgress:G})=>this.sourceBufferTaskQueue.append($,s).then(O=>O&&!s.aborted?this.onSegmentFullyAppended(G,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(I),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||_e(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:Mr(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:Mr(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",Ls(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");Ve(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=$u(()=>(0,_g.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?Dr(this.destroyAbortController.signal,function(){return te(this,null,function*(){let o=Yu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mr(e.mime),i)).then(o=>R(this,null,function*(){if(!o)return;let{init:u,dataView:c,segments:l}=o,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d);let p=l;this.isLive&&ut(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Kt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return R(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return R(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||_e(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(k({},u.time)),i=n(i);let c=Ls(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)["none","partially_ejected"].includes(h.status)&&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||_e(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=Ls(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){if(!this.gapDetectionIdleCallback){Ve(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=$u(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Kt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(_e(this.sourceBuffer)||_e(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=10;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&&n<l.to-t||o>l.from+t&&o<=l.to);u||(c.length===1?i.status="partially_ejected":this.gaps.some(l=>l.from===i.time.from||l.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var ta=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Ng=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as ra,assertNever as Fg,fromEvent as qg,merge as sR,now as ia,Subscription as nR,ValueSubject as zu,flattenObject as Or}from"@vkontakte/videoplayer-shared";var Ms=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new zu(void 0);this.lastConnectionReused$=new zu(void 0);this.lastRequestFirstBytes$=new zu(void 0);this.abortAllController=new nt;this.subscription=new nR;this.fetchManifest=ra(this.abortAllController.signal,function(e){return te(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ta(r));let i=yield st(r,{signal:this.abortAllController.signal}).catch(aa);return i?(t.log("success",Or({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Or({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=ra(this.abortAllController.signal,function(c){return te(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var L,F;let l=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(l,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),l=_.toString();break}default:Fg(t)}this.requestQuic&&(l=ta(l));let h=this.abortAllController.signal,f;if(n){let _=new nt;if(f=sR(qg(this.abortAllController.signal,"abort"),qg(n,"abort")).subscribe(()=>{try{_.abort()}catch(w){aa(w)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(w){aa(w)}h=_.signal}let b=ia();p.log("startRequest",Or({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield st(l,{priority:s,headers:d,signal:h}).catch(aa),S=ia();if(!g)return p.error("error",{message:"No response in request"}),p.end(),f==null||f.unsubscribe(),null;if((L=this.throughputEstimator)==null||L.addRawRtt(S-b),!g.ok||!g.body){f==null||f.unsubscribe();let _=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:_}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let _=ia(),w={requestStartedAt:b,requestEndedAt:_,duration:_-b};return p.log("endRequest",Or(w)),p.end(),g.arrayBuffer()}let[T,v]=g.body.tee(),y=T.getReader();o&&((F=this.throughputEstimator)==null||F.trackStream(v,u));let I=0,$=new Uint8Array(0),G=!1,O=_=>{f==null||f.unsubscribe(),G=!0,aa(_)},C=ra(h,function(x){return te(this,arguments,function*({done:_,value:w}){if(I===0&&this.lastRequestFirstBytes$.next(ia()-b),h.aborted){f==null||f.unsubscribe();return}if(!_&&w){let D=new Uint8Array($.length+w.length);D.set($),D.set(w,$.length),$=D,I+=w.byteLength,i==null||i(new DataView($.buffer),I),yield y==null?void 0:y.read().then(C,O)}})}.bind(this));yield y==null?void 0:y.read().then(C,O),f==null||f.unsubscribe();let H=ia(),N={failed:G,requestStartedAt:b,requestEndedAt:H,duration:H-b};return G?(p.error("endRequest",Or(N)),p.end(),null):(p.log("endRequest",Or(N)),p.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=ra(this.abortAllController.signal,function(e,t,r){return te(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,i),o=Math.max(l,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(S=e.indexRange)!=null?S:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let T=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!T)return null;b=new DataView(T)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=ra(this.abortAllController.signal,function(e,t){return te(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>V(k({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=Ng(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:Fg(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},aa=a=>{if(!Xi(a))throw a};var Jt=(a,e,t)=>t*e+(1-t)*a,Ku=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Ug=(a,e,t,r)=>{let i=0,s=t,n=Ku(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 oR,ValueSubject as Hg}from"@vkontakte/videoplayer-shared";var It=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Hg(e.initial),this.debounced$=new Hg(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ne(`raw_${t}`),this.smoothedSeries$=new ne(`smoothed_${t}`),this.reportedSeries$=new ne(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Ye(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)&&(oR(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 Cs=class extends It{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Jt(this.slow,e,this.params.emaAlphaSlow),this.fast=Jt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ds=class extends It{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ku(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Jt(this.emaSmoothed,e,this.params.emaAlpha);let r=Ug(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Bs=class extends It{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Jt(this.smoothed,t,this.params.emaAlpha):t}};var Xt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Cs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Ds({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 Bs(k({initial:e,label:"liveEdgeDelay"},t))}};var Ju=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var zg=["timeupdate","progress","play","seeked","stalled","waiting"];var _s=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Qg;this.representationSubscription=new Qg;this.state$=new M("none");this.currentVideoRepresentation$=new oe(void 0);this.currentVideoRepresentationInit$=new oe(void 0);this.currentAudioRepresentation$=new oe(void 0);this.currentVideoSegmentLength$=new oe(0);this.currentAudioSegmentLength$=new oe(0);this.error$=new Yg;this.lastConnectionType$=new oe(void 0);this.lastConnectionReused$=new oe(void 0);this.lastRequestFirstBytes$=new oe(void 0);this.isLive$=new oe(!1);this.liveDuration$=new oe(0);this.liveAvailabilityStartTime$=new oe(void 0);this.bufferLength$=new oe(0);this.liveLoadBufferLength$=new oe(0);this.livePositionFromPlayer$=new oe(0);this.timeInWaiting=0;this.isActiveLowLatency$=new oe(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Yg;this.gapWatchdogActive=!1;this.destroyController=new nt;this.initManifest=Xu(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Et.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Xu(this.destroyController.signal,function(){return te(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Et.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t;try{t=Dg(e!=null?e:"",this.manifestUrlString)}catch(u){let c=(n=Qb(e))!=null?n:{id:"ManifestParsing",category:Et.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(c)}if(!t)return null;let r=(u,c,l)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,c)&&((f=(h=ot())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${c}; codecs="${l}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let l=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(l.map(({codecs:h})=>h)),p=Yb(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);pR.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=V(k({},t),{streams:i});return this.tracer.log("updateManifestEnd",sa(s)),s})}.bind(this));this.initRepresentations=Xu(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",sa({initialVideo:e,initialAudio:t,sourceHls:r})),Zt(this.manifest),Zt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Vr(p,"error").pipe(Vs(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Et.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Rb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ys())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new ea("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Wg(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new ea("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Zu(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=cu(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(_r(...zg.filter(p=>p!=="waiting").map(p=>Vr(this.element,p))).pipe(ec(p=>this.element?at(this.element.buffered,this.element.currentTime*1e3):0),Gg(),Vs(p=>!!p),lR(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Gg()).subscribe(h=>Ju(this.element,1))),this.representationSubscription.add(Os({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Vs(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(Os({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),Ju(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(Os({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(dR(1e3)).subscribe(b=>R(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(Zt(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,S=cu(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,$=isFinite(h)?h:f,G=this.isActiveLowLatency$.getValue(),O=T<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLowLatency$.next(G&&O);let C="none";if(G?C="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&O?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(H=>H.proceedLowLatencyLive()),C="active_low_latency"):S!==0&&$<v?C="live_forward_buffering":$<v+I&&(C="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),C==="live_forward_buffering"||C==="live_with_target_offset"){let H=p-(v+y),N=this.normolizeLiveOffset(Math.trunc(S+H/g)),L=Math.abs(N-S),F;!h||L<=this.tuning.dashCmafLive.offsetCalculationError?F=S:N>0&&L>this.tuning.dashCmafLive.offsetCalculationError?F=N:F=0,this.manifestUrlString=ae(this.manifestUrlString,F,2)}C!=="none"&&C!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=_r(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ec(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=_r(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ec(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(_r(this.forceEnded$,Os({allBuffersFull:u,someBufferEnded:c}).pipe(Vs(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:Et.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(_r(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let l=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),ut(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/1e3,this.audioBufferManager&&Wg(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=Zu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:Et.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Ms({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=Xt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,k({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return R(this,null,function*(){var r,i,s,n;Zt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ae(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio))})}initBuffer(){Zt(this.element),this.state$.setState("running"),this.subscription.add(_r(...zg.map(e=>Vr(this.element,e)),Vr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Et.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Vr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Vr(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Rr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var n,o;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s=V(k({},s),{liveLastSeekOffset:this.liveLastSeekOffset});else{let u=this.element.currentTime*1e3;(n=this.videoBufferManager)==null||n.maintain(u),(o=this.audioBufferManager)==null||o.maintain(u),s=V(k({},s),{position:u})}this.tracer.log("stallIntervalCallback",sa(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=Zu(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:Et.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return R(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u,c;Zt(this.element),Zt(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Rr(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=hR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return R(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=V(k({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",sa(t)))}}};var Ns=class{constructor(e,t){this.fov=e,this.orientation=t}};var Fs=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/Ye(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=k({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*Ye(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 Kg=`attribute vec2 a_vertex;
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 Ds,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 Ls,isNullable as Cw,assertNonNullable as Oi}from"@vkontakte/videoplayer-shared";import{isNonNullable as Vb,assertNonNullable as $s,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 l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function _b(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Br(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;$s(c);let L=Du(c),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(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=L=>(p=L,N),$=()=>{c=ie(),n=new i,n.open("get",a);let L=0,F,_=0,k=()=>($s(c),Math.max(c,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;$s(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=()=>{$s(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=>(l=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 Di=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Bi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ie(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ie()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Br(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=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 Ms=1e4,Ou=3;var Dw=6e4,Bw=10,Ow=1,Vw=500,Vi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new Di(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||Ls(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 Bi(Ou,Ms,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,I,$)=>{u&&u.abort(),u=Br(this.urlResolver.resolve(y,!1),I,$,()=>this._retryCallback()).withTimeout(Ms).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ou).withFinally(()=>{u=null}).send()},h=(y,I,$)=>{Oi(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(Ls(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)=>{l&&l.abort(),l=Br(this.urlResolver.resolve(x,!0,this.lowLatency),B,W,()=>this._retryCallback()).withTimeout(Ms).withRetryCount(Ou).withFinally(()=>{l=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 ce=0;ce<I.dur.length;++ce)Z+=I.dur[ce];Z>0&&(Oi(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(),l&&l.abort(),Oi(this.filesFetcher),this.filesFetcher.abortAll()};return c={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=()=>{l||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}ce(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 lr=this._getBufferSizeSec();if(lr>30)$(`Buffered ${lr} seconds; delaying appendBuffer`),ur(2e3);else try{this.sourceBuffer.appendBuffer(w),this.videoPlayStarted?(this.bufferStates.push({ts:vt,buf:lr}),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),ce=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()&&(Oi(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?ce(w):(H=w,B())}},y),e.cachedHeader?gt(e.cachedHeader):p(e.headerUrl,gt,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Ls(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,Oi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ls(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,l=()=>{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&&l(),h},notifySwitch:d=>{let p=ie();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Br(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ms).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,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))},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}},Cs=Vu;import{map as Ww,Observable as Yw}from"@vkontakte/videoplayer-shared";import{fromEvent as Qw}from"@vkontakte/videoplayer-shared";var _i=()=>{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||_i()))},P(P({},r),e));i.observe(a);let s=Qw(document,"visibilitychange").pipe(Ww(n=>!document.hidden||_i())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Oe=zw;var ak=["paused","playing","ready"],sk=["paused","playing","ready"],Ni=class{constructor(e){this.subscription=new tk;this.videoState=new C("stopped");this.representations$=new Nu([]);this.textTracksManager=new rt;this.droppedFramesManager=new Cs;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 l=(t=u.name)!=null?t:u.index.toString(10),c=(r=kt(u.name))!=null?r:ik(u.video),d=u.bitrate/1e3,p=P({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),_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(Ds(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ds(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Se(this.video);this.subscription.add(this.representations$.pipe(Ds(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(),Ds(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(Oe(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 Vi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var 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&&_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=Ni;var ct=(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 fl,filter as gS,filterChanged as ml,fromEvent as DR,isNonNullable as BR,map as SS,merge as nn,observableFrom as OR,observeElementSize as VR,once as vS,Subscription as _R,ValueSubject as NR}from"@vkontakte/videoplayer-shared";var Bs=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}},Or=class extends Bs{constructor(){super(),this.listeners||Bs.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)}},Fi=class{constructor(){Object.defineProperty(this,"signal",{value:new Or,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&&(Fi.prototype[Symbol.toStringTag]="AbortController",Or.prototype[Symbol.toStringTag]="AbortSignal");function Os(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(!Os({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 qi=Os({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Yb=qi?Fu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,dt=qi?Yb.fetch:window.fetch,jB=qi?Yb.Request:window.Request,pt=qi?Fi:window.AbortController,GB=qi?Or:window.AbortSignal;var ng=Xe(Li(),1);var ht=()=>window.ManagedMediaSource||window.MediaSource,Vs=()=>{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 Ws,clientChecker as Gs}from"@vkontakte/videoplayer-shared";var Ve=document.createElement("video"),uk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',lk='video/mp4; codecs="hev1.1.6.L93.B0"',og='video/webm; codecs="vp09.00.10.08"',ug='video/webm; codecs="av01.0.00M.08"',ck='audio/mp4; codecs="mp4a.40.2"',dk='audio/webm; codecs="opus"',Kb,Jb,Xt={mms:Vs(),mse:Qb(),hls:!!((Kb=Ve.canPlayType)!=null&&Kb.call(Ve,"application/x-mpegurl")||(Jb=Ve.canPlayType)!=null&&Jb.call(Ve,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Xb,Zb,Te={mp4:!!((Xb=Ve.canPlayType)!=null&&Xb.call(Ve,"video/mp4")),webm:!!((Zb=Ve.canPlayType)!=null&&Zb.call(Ve,"video/webm")),cmaf:!0},Ns,eg,Fs,tg,qs,rg,Us,ig,Hs,ag,js,sg,Ie={h264:!!((eg=(Ns=ht())==null?void 0:Ns.isTypeSupported)!=null&&eg.call(Ns,uk)),h265:!!((tg=(Fs=ht())==null?void 0:Fs.isTypeSupported)!=null&&tg.call(Fs,lk)),vp9:!!((rg=(qs=ht())==null?void 0:qs.isTypeSupported)!=null&&rg.call(qs,og)),av1:!!((ig=(Us=ht())==null?void 0:Us.isTypeSupported)!=null&&ig.call(Us,ug)),aac:!!((ag=(Hs=ht())==null?void 0:Hs.isTypeSupported)!=null&&ag.call(Hs,ck)),opus:!!((sg=(js=ht())==null?void 0:js.isTypeSupported)!=null&&sg.call(js,dk))},Vr=(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(P({},a),{video:M(P({},a.video),{contentType:ug})})),window.navigator.mediaCapabilities.decodingInfo(M(P({},a),{video:M(P({},a.video),{contentType:og})}))]);Zt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{pk()}catch(a){console.error(a)}var _r=Xt.hls&&Te.mp4,lg=()=>Object.keys(Ie).filter(a=>Ie[a]),cg=(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&&Vr;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&&Vr||Te.webm&&(Ie.vp9||Ie.av1)&&(Ie.opus||Ie.aac));case"DASH_LIVE":return Xt.mse&&Te.mp4&&Vr;case"DASH_LIVE_CMAF":return r&&Te.mp4&&Vr&&Te.cmaf;case"DASH_ONDEMAND":return r&&Te.mp4&&Vr;case"HLS":case"HLS_ONDEMAND":return _r||e&&Xt.mse&&Te.mp4&&Vr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return _r;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 Ws(i)}})},_s=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:Ws(a)}return[e,t]},dg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],..._s(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Gs.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",..._s(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[..._s(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",..._s(a),...i,"HLS","HLS_ONDEMAND"];default:Ws(e)}return _r?[...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=Gs.isMac&&Gs.isSafari;if(Gs.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:Ws(a)}else _r&&!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 Ui}from"@vkontakte/videoplayer-shared";var fg=a=>{if(!a)return{id:"EmptyResponse",category:Ui.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Ui.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:Ui.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:Ui.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ui.PARSER,message:"Response is valid XML, but parser failed"}};var Nr=(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 dl,assertNonNullable as nr,combine as Zs,ErrorCategory as Lt,filter as en,filterChanged as cS,fromEvent as Yr,interval as pl,isNonNullable as dS,map as hl,merge as Qr,Subject as pS,Subscription as hS,tap as ER,throttle as xR,clientChecker as PR,ValueSubject as se,flattenObject as Sa,getTraceSubscriptionMethod as AR}from"@vkontakte/videoplayer-shared";var Gr=Xe(Li(),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 iS=Xe(As(),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 Ne,ErrorCategory as ir,fromEvent as sl,getExponentialDelay as nl,isNonNullable as ol,isNullable as Fe,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,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};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=P({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],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,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"),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},Pk=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:Pk,getIndexRange:()=>{},parseSegments:Ik,parseFeedableSegmentChunk:Ek,getSegmentEndTime:xk};import{assertNonNullable as Yu,isNonNullable as xg,isNullable as wk}from"@vkontakte/videoplayer-shared";import{assertNever as Ak}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),l=n&255>>o,c=ua(u),d=l*Je(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},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},Ye=(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:Ak(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=Ye(o,n):s===17026?t=Ye(o,n):s===17029&&(r=Ye(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Pg=[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,l,c=!1,d=0;return rr(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Ye(f,h);l=ua(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=Ye(f,h):p===17545?i=Ye(f,h):p===21420&&l===475249515?u=Ye(f,h):p===374648427?rr(f,({tag:g,type:S,value:T})=>g===30321?(c=Ye(T,S)===1,!1):!0):s&&n&&Pg.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:c,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:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ye(l,u));break;case 183:break;case 241:n&&(n.position=Ye(l,u));break;default:t&&Pg.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}}})},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},Ag={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 Ag;case"mp4":return yg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var el=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,el.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,el.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,ce,Ot,gt,w,de,Ee,Re,St,ur,vt,Vt,lr,Jr,Ll,Ml,Cl,Dl,Bl,Ol,Vl,_l,Nl,Fl,ql,Ul,Hl,jl,Gl,Wl,Yl,Ql,zl,Kl,Jl,Xl,Zl,ec,tc,rc,ic,ac,sc,nc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=($=(I=(y=s.querySelector("BaseURL"))==null?void 0:y.textContent)==null?void 0:I.trim())!=null?$:"",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=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:"",Tn=(N=pe.getAttribute("codecs"))!=null?N:"",In=(L=pe.getAttribute("contentType"))!=null?L:Xr==null?void 0:Xr.split("/")[0],dv=(_=(F=pe.getAttribute("profiles"))==null?void 0:F.split(","))!=null?_:[],pv=(k=pe.getAttribute("lang"))!=null?k:void 0,hv=(W=(B=(x=pe.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:B.trim())!=null?W:void 0,fv=pe.querySelectorAll("Representation"),mv=pe.querySelector("SegmentTemplate"),bv=(Z=(z=pe.querySelector("Role"))==null?void 0:z.getAttribute("value"))!=null?Z:void 0,Zr=In,ee={id:cv,language:pv,isDefault:bv==="main",label:hv,codecs:Tn,hdr:Zr==="video"&&Zu(Tn),mime:Xr,representations:[]};for(let Q of fv){let gv=(ce=Q.getAttribute("lang"))!=null?ce:void 0,Sv=(Ot=Q.getAttribute("label"))!=null?Ot:void 0,vv=(de=(w=(gt=Q.querySelector("BaseURL"))==null?void 0:gt.textContent)==null?void 0:w.trim())!=null?de:"",En=new URL(vv||o,e).toString(),cr=(Ee=Q.getAttribute("mimeType"))!=null?Ee:Xr,Ca=(St=(Re=Q.getAttribute("codecs"))!=null?Re:Tn)!=null?St:"",xn;if(In==="text"){let _t=Q.getAttribute("id")||"",Pn=_t.includes("_auto"),Nt=Q.querySelector("SegmentTemplate");if(!Nt)throw new Error("Unknown MPD segment text referencing type");let ei={representationId:(ur=Q.getAttribute("id"))!=null?ur:void 0,bandwidth:(vt=Q.getAttribute("bandwidth"))!=null?vt:void 0},Da=parseInt((Vt=Q.getAttribute("bandwidth"))!=null?Vt:"",10)/1e3,Ba=(Jr=parseInt((lr=Nt.getAttribute("startNumber"))!=null?lr:"",10))!=null?Jr:1,dr=parseInt((Ll=Nt.getAttribute("timescale"))!=null?Ll:"",10),An=(Ml=Nt.querySelectorAll("SegmentTimeline S"))!=null?Ml:[],pr=Nt.getAttribute("media");if(!pr)throw new ReferenceError("No media attribute in SegmentTemplate");let Oa=[],Va=0,_a="",hr=0,ti=Ba,ne=0;for(let qe of An){let Ft=parseInt((Cl=qe.getAttribute("d"))!=null?Cl:"",10),$e=parseInt((Dl=qe.getAttribute("r"))!=null?Dl:"",10)||0,yt=parseInt((Bl=qe.getAttribute("t"))!=null?Bl:"",10);ne=Number.isFinite(yt)?yt:ne;let qt=Ft/dr*1e3,Tt=ne/dr*1e3;for(let ze=0;ze<$e+1;ze++){let It=ft(pr,M(P({},ei),{segmentNumber:ti.toString(10),segmentTime:(ne+ze*Ft).toString(10)})),fr=(Tt!=null?Tt:0)+ze*qt,ii=fr+qt;ti++,Oa.push({time:{from:fr,to:ii},url:It})}ne+=($e+1)*Ft,Va+=($e+1)*qt}hr=ne/dr*1e3,_a=ft(pr,M(P({},ei),{segmentNumber:ti.toString(10),segmentTime:ne.toString(10)}));let ri={time:{from:hr,to:1/0},url:_a},it={type:"template",baseUrl:En,segmentTemplateUrl:pr,initUrl:"",totalSegmentsDurationMs:Va,segments:Oa,nextSegmentBeyondManifest:ri,timescale:dr};xn={id:_t,kind:"text",segmentReference:it,profiles:[],duration:p,bitrate:Da,mime:"",codecs:"",width:0,height:0,isAuto:Pn}}else{let _t=(Vl=(Ol=Q.getAttribute("contentType"))!=null?Ol:cr==null?void 0:cr.split("/")[0])!=null?Vl:In,Pn=(Nl=(_l=pe.getAttribute("profiles"))==null?void 0:_l.split(","))!=null?Nl:[],Nt=parseInt((Fl=Q.getAttribute("width"))!=null?Fl:"",10),ei=parseInt((ql=Q.getAttribute("height"))!=null?ql:"",10),Da=parseInt((Ul=Q.getAttribute("bandwidth"))!=null?Ul:"",10)/1e3,Ba=(Hl=Q.getAttribute("frameRate"))!=null?Hl:"",dr=(jl=Q.getAttribute("quality"))!=null?jl:void 0,An=Ba?zg(Ba):void 0,pr=(Gl=Q.getAttribute("id"))!=null?Gl:"id"+(S++).toString(10),Oa=_t==="video"?`${ei}p`:_t==="audio"?`${Da}Kbps`:Ca,Va=`${pr}@${Oa}`,_a=[...T,...dv,...Pn],hr,ti=Q.querySelector("SegmentBase"),ne=(Wl=Q.querySelector("SegmentTemplate"))!=null?Wl:mv;if(ti){let it=(Ql=(Yl=Q.querySelector("SegmentBase Initialization"))==null?void 0:Yl.getAttribute("range"))!=null?Ql:"",[qe,Ft]=it.split("-").map(It=>parseInt(It,10)),$e={from:qe,to:Ft},yt=(zl=Q.querySelector("SegmentBase"))==null?void 0:zl.getAttribute("indexRange"),[qt,Tt]=yt?yt.split("-").map(It=>parseInt(It,10)):[],ze=yt?{from:qt,to:Tt}:void 0;hr={type:"byteRange",url:En,initRange:$e,indexRange:ze}}else if(ne){let it={representationId:(Kl=Q.getAttribute("id"))!=null?Kl:void 0,bandwidth:(Jl=Q.getAttribute("bandwidth"))!=null?Jl:void 0},qe=parseInt((Xl=ne.getAttribute("timescale"))!=null?Xl:"",10),Ft=(Zl=ne.getAttribute("initialization"))!=null?Zl:"",$e=ne.getAttribute("media"),yt=(tc=parseInt((ec=ne.getAttribute("startNumber"))!=null?ec:"",10))!=null?tc:1,qt=ft(Ft,it);if(!$e)throw new ReferenceError("No media attribute in SegmentTemplate");let Tt=(rc=ne.querySelectorAll("SegmentTimeline S"))!=null?rc:[],ze=[],It=0,fr="",ii=0;if(Tt.length){let Na=yt,Ue=0;for(let mr of Tt){let Ke=parseInt((ic=mr.getAttribute("d"))!=null?ic:"",10),Ut=parseInt((ac=mr.getAttribute("r"))!=null?ac:"",10)||0,Fa=parseInt((sc=mr.getAttribute("t"))!=null?sc:"",10);Ue=Number.isFinite(Fa)?Fa:Ue;let wn=Ke/qe*1e3,kn=Ue/qe*1e3;for(let qa=0;qa<Ut+1;qa++){let Tv=ft($e,M(P({},it),{segmentNumber:Na.toString(10),segmentTime:(Ue+qa*Ke).toString(10)})),oc=(kn!=null?kn:0)+qa*wn,Iv=oc+wn;Na++,ze.push({time:{from:oc,to:Iv},url:Tv})}Ue+=(Ut+1)*Ke,It+=(Ut+1)*wn}ii=Ue/qe*1e3,fr=ft($e,M(P({},it),{segmentNumber:Na.toString(10),segmentTime:Ue.toString(10)}))}else if(Kg(p)){let Ue=parseInt((nc=ne.getAttribute("duration"))!=null?nc:"",10)/qe*1e3,mr=Math.ceil(p/Ue),Ke=0;for(let Ut=1;Ut<mr;Ut++){let Fa=ft($e,M(P({},it),{segmentNumber:Ut.toString(10),segmentTime:Ke.toString(10)}));ze.push({time:{from:Ke,to:Ke+Ue},url:Fa}),Ke+=Ue}ii=Ke,fr=ft($e,M(P({},it),{segmentNumber:mr.toString(10),segmentTime:Ke.toString(10)}))}let yv={time:{from:ii,to:1/0},url:fr};hr={type:"template",baseUrl:En,segmentTemplateUrl:$e,initUrl:qt,totalSegmentsDurationMs:It,segments:ze,nextSegmentBeyondManifest:yv,timescale:qe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!_t||!cr)continue;let ri={video:"video",audio:"audio",text:"text"}[_t];if(!ri)continue;Zr||(Zr=ri),xn={id:Va,kind:ri,segmentReference:hr,profiles:_a,duration:p,bitrate:Da,mime:cr,codecs:Ca,width:Nt,height:ei,fps:An,quality:dr}}ee.language||(ee.language=gv),ee.label||(ee.label=Sv),ee.mime||(ee.mime=cr),ee.codecs||(ee.codecs=Ca),ee.hdr||(ee.hdr=Zr==="video"&&Zu(Ca)),ee.representations.push(xn)}Zr&&i[Zr].push(ee)}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,streams:i}};var la=Xe(Li(),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}),Ys=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,la.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,la.default)(t,-1)},rS=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),il=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,la.default)(r.split("."),0),isDefault:i}),al=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,la.default)(i.split("."),0)}),Qs=a=>"url"in a,_e=a=>a.type==="template",ca=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:l}){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);Ne(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(sl(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(sl(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 l=ct(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);Ne(r,"No init buffer for starting representation"),Ne(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);Ne(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Fe(s)||Fe(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Ne(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();ol(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),yield new Ln(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,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||!_e(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);Ne(i);let s=this.segments.get(r);Ne(s,"No segments for starting representation");let n=this.initData.get(r);if(Ne(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new pt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(Fe(e)||Fe(this.downloadingRepresentationId)||Fe(this.playingRepresentationId)||Fe(this.sourceBuffer)||!Fe(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ne(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=ct(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=ct(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&&ct(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;ol(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||!_e(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>M(P({},p),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Gr.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;Ne(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(!_e(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=ft(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),T=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&!(Nr(this.sourceBuffer.buffered,p)&&Nr(this.sourceBuffer.buffered,h)))&&g&&T});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 R(this,null,function*(){_e(t.segmentReference)?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:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield jr(o,function(){return te(this,null,function*(){let c=nl(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=Ur(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]),ca(c)||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=nl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),sl(window,"online").pipe(hR()).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),ca(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(_e(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(l){this.error$.next({id:"SegmentFeeding",category:ir.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!_e(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: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: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=Ur(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,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();ol(y)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-y,this.bufferAccumulation.accumulated.push({segmentView:v,segmentProgress:c}),this.activeSegments.delete(c));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||Fe(y))&&(I({segmentView:v,segmentProgress:c}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&!T&&(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:Ur(o.mime).parseFeedableSegmentChunk(v);y!=null&&y.byteLength&&(d.status="partially_fed",c.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(I=>{if(s.aborted)n();else if(I)c.fedBytes+=y.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.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 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:Ur(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",Qs(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");Ne(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Uu(()=>(0,iS.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=nl(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: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&&_e(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||Fe(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(P({},u.time)),i=n(i);let l=Qs(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)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}pruneBufferOld(e,t,r=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||Fe(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=Qs(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){if(!this.gapDetectionIdleCallback){Ne(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=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(Fe(this.sourceBuffer)||Fe(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var ha=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var aS=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 sS,fromEvent as nS,merge as bR,now as ma,Subscription as gR,ValueSubject as ul,flattenObject as Wr}from"@vkontakte/videoplayer-shared";var zs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new ul(void 0);this.lastConnectionReused$=new ul(void 0);this.lastRequestFirstBytes$=new ul(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(l){return te(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var L,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:sS(t)}this.requestQuic&&(c=ha(c));let h=this.abortAllController.signal,f;if(n){let _=new pt;if(f=bR(nS(this.abortAllController.signal,"abort"),nS(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:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield dt(c,{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,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 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(P({},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}=aS(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:sS(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ba=a=>{if(!ca(a))throw a};var ar=(a,e,t)=>t*e+(1-t)*a,ll=(a,e)=>a.reduce((t,r)=>t+r,0)/e,oS=(a,e,t,r)=>{let i=0,s=t,n=ll(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 uS}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 uS(e.initial),this.debounced$=new uS(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 Ks=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 Js=class extends $t{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ll(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ar(this.emaSmoothed,e,this.params.emaAlpha);let r=oS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Xs=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 Ks({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Js({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 Xs(P({initial:e,label:"liveEdgeDelay"},t))}};var cl=(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.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!vR(e))for(let r of this.representations){let i=r.segmentReference.segments.find(s=>s.time.from<=e&&s.time.to>=e);if(!i||((t=this.currentSegment)==null?void 0:t.time.from)===i.time.from&&this.currentSegment.time.to===i.time.to)return;this.currentSegment=i,this.currentRepresentation$.next(M(P({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(i.url,r.segmentReference.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations=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&&_e(t.segmentReference))}};var fS=["timeupdate","progress","play","seeked","stalled","waiting"];var tn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new hS;this.representationSubscription=new hS;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 pS;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 pS;this.gapWatchdogActive=!1;this.destroyController=new pt;this.initManifest=dl(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=dl(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 l=(n=fg(e))!=null?n:{id:"ManifestParsing",category:Lt.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=ht())==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=hg(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);PR.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=M(P({},t),{streams:i});return this.tracer.log("updateManifestEnd",Sa(s)),s})}.bind(this));this.initRepresentations=dl(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(en(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&&Vs())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new pa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],dS(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(pl(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(...fS.filter(p=>p!=="waiting").map(p=>Yr(this.element,p))).pipe(hl(p=>this.element?ct(this.element.buffered,this.element.currentTime*1e3):0),cS(),en(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=>cl(this.element,1))),this.representationSubscription.add(Zs({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(en(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(Zs({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),cl(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(Zs({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(hl(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=Qr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(hl(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Qr(this.forceEnded$,Zs({allBuffersFull:u,someBufferEnded:l}).pipe(en(({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 c=[(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),_e(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&dS(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=pl(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,P({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return R(this,null,function*(){var r,i,s;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(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){nr(this.element),this.state$.setState("running"),this.subscription.add(Qr(...fS.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&&Nr(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(P({},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(P({},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=pl(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,l;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),Nr(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(l=this.audioBufferManager)==null||l.maintain(r),this.element.currentTime=r/1e3,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=AR(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(P({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Sa(t)))}}};var rn=class{constructor(e,t){this.fov=e,this.orientation=t}};var an=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=P({},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 mS=`attribute vec2 a_vertex;
59
59
  attribute vec2 a_texel;
60
60
 
61
61
  varying vec2 v_texel;
@@ -66,7 +66,7 @@ void main(void) {
66
66
  // save texel vector to pass to fragment shader
67
67
  v_texel = a_texel;
68
68
  }
69
- `;var Jg=`#ifdef GL_ES
69
+ `;var bS=`#ifdef GL_ES
70
70
  precision highp float;
71
71
  precision highp int;
72
72
  #else
@@ -109,5 +109,5 @@ void main(void) {
109
109
  // sample using new coordinates
110
110
  gl_FragColor = texture2D(u_texture, tc);
111
111
  }
112
- `;var qs=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 Ns(this.params.fov,this.params.orientation),this.cameraRotationManager=new Fs(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(Kg,this.gl.VERTEX_SHADER),r=this.createShader(Jg,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,c=e+r,l=t+i,d=e-r,p=t+i;return[s,n,o,u,c,l,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var er=class{constructor(e){this.subscription=new PR;this.videoState=new M("stopped");this.elementSize$=new AR(void 0);this.textTracksManager=new Ce;this.droppedFramesManager=new bs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ti;this.audioTrackSwitchHistory=new Ti;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let c=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-c,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&E(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return SR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new qs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=fe(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new _s({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:tc.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(Xg(c=>!!c.length),eS()).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(Xg(IR),eS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Zg(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Ke(this.video,t.isLooped,i)),this.subscription.add(be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Me(this.video,t.playbackRate,r.playbackRateState$,i)),s(xR(this.video),this.elementSize$),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams();if(vR(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of l.audio){p.push(ju(h));let f=[];for(let b of h.representations){let g=Og(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(Gu(p));let h=[];for(let f of p.representations){let b=Bg(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=Vg(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:tc.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(Us(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$,TR(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(rc()).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(Gu(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(rc()).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(ju(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(Zg(({to:c})=>c==="ready"),rc());this.subscription.add(Us(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(Us(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Us(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ER(["init"])).pipe(yR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var $,G,O,C,H,N,L,F,_,w,x,D,W,Q,X,ce,kt,dt;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=($=e.videoTrack.getState())==null?void 0:$.id,n=[...this.videoTracksMap.keys()].find(({id:A})=>A===i),o=t.currentVideoTrack$.getValue(),u=((C=(O=e.videoStream.getState())!=null?O:n&&((G=this.videoTracksMap.get(n))==null?void 0:G.stream))!=null?C:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let c=[...this.videoStreamsMap.keys()].find(({id:A})=>A===u.id),l=c&&this.videoStreamsMap.get(c);if(!l)return;let d=at(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(H=e.audioStream.getState())!=null?H:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(N=[...this.audioStreamsMap.keys()].find(({id:A})=>A===(f==null?void 0:f.id)))!=null?N:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let A=ps(n,l,(L=this.audioStreamsMap.get(b))!=null?L:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(F=A==null?void 0:A.bitrate)!=null?F:-1/0)}else{let A=$s(n,l,(_=this.audioStreamsMap.get(b))!=null?_:[]);g=Math.max(g,(w=A==null?void 0:A.bitrate)!=null?w:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let A=ps(o,l,(x=this.audioStreamsMap.get(b))!=null?x:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(D=A==null?void 0:A.bitrate)!=null?D:-1/0)}else{let A=$s(o,l,(W=this.audioStreamsMap.get(b))!=null?W:[]);g=Math.max(g,(Q=A==null?void 0:A.bitrate)!=null?Q:-1/0)}}let S=Tt(l,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),T=r?S!=null?S:n:n!=null?n:S,v;this.params.tuning.useSeparateAudioVideoABR?v=b&&mb(T,l,(X=this.audioStreamsMap.get(b))!=null?X:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):v=b&&$s(T,l,(ce=this.audioStreamsMap.get(b))!=null?ce:[]);let y=(kt=this.videoTracksMap.get(T))==null?void 0:kt.representation,I=v&&((dt=this.audioTracksMap.get(v))==null?void 0:dt.representation);if(y&&I)return[y,I];if(y&&!I&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ve(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tc.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),me(this.video),this.tracer.end()}};var oa=class extends er{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as tS,interval as wR,map as kR}from"@vkontakte/videoplayer-shared";var ua=class extends er{constructor(e){super(e),this.liveOffset=new rt}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(tS({interval:wR(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(tS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(kR(({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 iS=Qe(cs(),1);import{assertNever as ca,assertNonNullable as rS,debounce as RR,ErrorCategory as Hs,filter as $R,isNonNullable as LR,isNullable as MR,map as js,merge as CR,Observable as DR,observableFrom as BR,Subscription as OR,videoSizeToQuality as VR}from"@vkontakte/videoplayer-shared";var Ge={};var Nr=(a,e)=>new DR(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),la=class{constructor(e){this.subscription=new OR;this.videoState=new M("initializing");this.textTracksManager=new Ce;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:ca(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ca(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ca(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ca(e)}break;default:ca(t)}};this.video=fe(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),me(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Hs.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,iS.default)(import("hls.js").then(i=>{e||(Ge.Hls=i.default,Ge.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){rS(Ge.Hls,"hls.js not loaded"),this.hls=new Ge.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){rS(Ge.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=c=>{t.error$.next({id:"HlsJsProvider",category:Hs.WTF,message:"HlsJsProvider internal logic error",thrown:c})},i=ge(this.video),s=(c,l)=>this.subscription.add(c.subscribe(l,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(Ke(this.video,e.isLooped,r)),this.subscription.add(be(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Me(this.video,e.playbackRate,i.playbackRateState$,r)),s(Be(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(js(c=>c.to)),this.params.output.playbackState$),this.subscription.add(Nr(this.hls,Ge.Events.ERROR).subscribe(c=>{var l;c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:Hs.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(Nr(this.hls,Ge.Events.MANIFEST_PARSED).pipe(js(({levels:c})=>c.reduce((l,d)=>{var T,v;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(v=yt((T=d.attrs.QUALITY)!=null?T:""))!=null?v:VR({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(Nr(this.hls,Ge.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(Nr(this.hls,Ge.Events.LEVEL_LOADING).pipe(js(({url:c})=>re(c))),t.hostname$),s(Nr(this.hls,Ge.Events.FRAG_CHANGED),c=>{var p,h,f,b;let{video:l,audio:d}=c.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=l==null?void 0:l.endPTS)!=null?p:0)-((h=l==null?void 0:l.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(gt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,c=>{this.hls.nextLevel=c?-1:this.hls.currentLevel,this.hls.loadLevel=c?-1:this.hls.loadLevel},{onError:r}));let n=c=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:d})=>d===c))==null?void 0:l.track},o=Nr(this.hls,Ge.Events.LEVEL_SWITCHED).pipe(js(({level:c})=>n(this.hls.levels[c])));o.pipe($R(LR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(gt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),c=>{var f;if(MR(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=CR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,BR(["init"])).pipe(RR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return R(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield ve(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Hs.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 aS="X-Playback-Duration",ic=a=>R(void 0,null,function*(){var i;let e=yield st(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(aS)?parseInt(e.headers.get(aS),10):void 0});import{assertNever as HR,combine as jR,debounce as GR,ErrorCategory as Ws,filter as WR,filterChanged as YR,isNonNullable as nS,isNullable as Ys,map as oS,merge as QR,observableFrom as zR,Subscription as KR,ValueSubject as nc,VideoQuality as JR}from"@vkontakte/videoplayer-shared";var sc=Qe(xo(),1);import{videoSizeToQuality as _R,getExponentialDelay as NR}from"@vkontakte/videoplayer-shared";var FR=a=>{let e=null;if(a.QUALITY&&(e=yt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=_R({width:t,height:r})}return e!=null?e:null},qR=(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=FR(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}},UR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),ac=0,sS=(r,...i)=>R(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield st(a)).text();ac+=1;try{let{qualityManifests:o,textTracks:u}=qR(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(ac<=t.manifestRetryMaxCount)return yield UR(NR(ac-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),sS(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Gs=sS;var da=class{constructor(e){this.subscription=new KR;this.videoState=new M("stopped");this.textTracksManager=new Ce;this.manifests$=new nc([]);this.liveOffset=new rt;this.manifestStartTime$=new nc(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 HR(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:JR.INVARIANT,url:this.params.source.url},Gs(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:Ws.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ws.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 nc((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:Ws.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=ge(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Me(this.video,t.playbackRate,i.playbackRateState$,r)),s(Be(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(YR(),oS(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&&nS(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(jR({startTime:this.manifestStartTime$.pipe(WR(nS)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(oS(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=QR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,zR(["init"])).pipe(GR(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(Ys(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(),ic(n).then(c=>{var l;if(!Ys(c))this.maxSeekBackTime$.next(c);else{let d=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();if(Ys(d)||!isFinite(d))try{st(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();ic(b).then(g=>{Ys(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){ve(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ws.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 XR,debounce as ZR,ErrorCategory as oc,fromEvent as uc,isNonNullable as e$,isNullable as t$,map as uS,merge as cS,observableFrom as lS,Subscription as r$,ValueSubject as i$,VideoQuality as a$,clientChecker as s$}from"@vkontakte/videoplayer-shared";var pa=class{constructor(e){this.subscription=new r$;this.videoState=new M("stopped");this.textTracksManager=new Ce;this.manifests$=new i$([]);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 XR(t)}};this.params=e,this.video=fe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a$.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),Gs(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:oc.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:oc.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(uS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ke(this.video,t.isLooped,r)),this.subscription.add(be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Me(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&e$(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(uS(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(cS(uc(o,"addtrack"),uc(o,"removetrack"),uc(o,"change"),lS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=cS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,lS(["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(t$(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[c,l]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(c||""));l&&c&&i.searchParams.set(l,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){ve(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:oc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as n$,assertNonNullable as dS,debounce as o$,ErrorCategory as pS,isHigher as u$,isHigherOrEqual as c$,isInvariantQuality as hS,isLowerOrEqual as l$,isNonNullable as d$,merge as p$,observableFrom as h$,Subscription as f$,map as m$}from"@vkontakte/videoplayer-shared";var ha=class{constructor(e){this.subscription=new f$;this.videoState=new M("stopped");this.trackUrls={};this.textTracksManager=new Ce;this.syncPlayback=()=>{var u,c,l;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((l=(c=this.trackUrls[n.to.id])==null?void 0:c.track)==null?void 0:l.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return n$(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:pS.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(m$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ke(this.video,t.isLooped,r)),this.subscription.add(be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Me(this.video,t.playbackRate,i.playbackRateState$,r)),s(Be(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,c;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&d$(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=p$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,h$(["init"])).pipe(o$(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;dS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];dS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ta(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(re(t))}playIfAllowed(){ve(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pS.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=>!hS(d.track.quality)&&l$(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&&c$(l.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!hS(h.track.quality)&&u$(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(c=>c.track);t=Tt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as mS,debounce as v$,merge as bS,observableFrom as y$,Subscription as T$,map as gS,ValueSubject as I$,ErrorCategory as lc,VideoQuality as E$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as b$}from"@vkontakte/videoplayer-shared";var fS=["stun:videostun.mycdn.me:80"],g$=1e3,S$=3,cc=()=>null,Qs=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=cc;this.externalStopCallback=cc;this.externalErrorCallback=cc;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:fS}]};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:b$.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),g$)}normalizeOptions(e={}){let t={stunServerList:fS,maxRetryNumber:S$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var fa=class{constructor(e){this.videoState=new M("stopped");this.maxSeekBackTime$=new I$(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 mS(e)}};this.subscription=new T$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=fe(e.container,e.tuning),this.liveStreamClient=new Qs(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:lc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};bS(this.videoState.stateChangeStarted$.pipe(gS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(gS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=ge(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Be(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(be(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return mS(n.to)}},r)).add(bS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,y$(["init"])).pipe(v$(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:E$.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:lc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ve(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:lc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ma=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Sa,assertNonNullable as xt,ErrorCategory as Ks,filter as $$,isNonNullable as ES,isNullable as L$,map as M$,merge as C$,once as D$,Subject as Ae,Subscription as xS,ValueSubject as B,flattenObject as PS}from"@vkontakte/videoplayer-shared";import{Observable as x$,map as SS,Subscription as P$,Subject as A$}from"@vkontakte/videoplayer-shared";var vS=a=>new x$(e=>{let t=new P$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(SS(({from:c,to:l})=>`${c}-${l}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(SS(({type:c})=>c!==void 0)),n=new A$,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 yS,Subscription as w$,combine as k$,filter as TS,once as IS}from"@vkontakte/videoplayer-shared";var ba=null,zs=null;function dc(){return ba||(ba=new(window.AudioContext||window.webkitAudioContext)),zs||(zs=new GainNode(ba,{gain:1}),zs.connect(ba.destination)),{audioCtx:ba,gainNode:zs}}import{clientChecker as R$}from"@vkontakte/videoplayer-shared";var Fr=class Fr{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new w$;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe(TS(n=>!!n.type),IS()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){R$.isSafari&&e!=="MPEG"||this.subscriptions.add(k$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(TS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),IS()).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}=dc(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Fr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Fr.errorId,category:yS.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:Fr.errorId,category:yS.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=dc();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Fr.errorId="VolumeMultiplierManager";var ga=Fr;var B$={chunkDuration:5e3,maxParallelRequests:5},va=class{constructor(e){this.current$=new B({type:void 0});this.providerError$=new Ae;this.noAvailableProvidersError$=new Ae;this.volumeMultiplierError$=new Ae;this.providerOutput={position$:new B(0),duration$:new B(1/0),volume$:new B({muted:!1,volume:1}),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableVideoTracks$:new B([]),currentVideoTrack$:new B(void 0),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0),isAudioAvailable$:new B(!0),autoVideoTrackLimitingAvailable$:new B(!1),autoVideoTrackLimits$:new B(void 0),currentBuffer$:new B(void 0),isBuffering$:new B(!0),error$:new Ae,warning$:new Ae,willSeekEvent$:new Ae,seekedEvent$:new Ae,loopedEvent$:new Ae,endedEvent$:new Ae,firstBytesEvent$:new Ae,loadedMetadataEvent$:new Ae,firstFrameEvent$:new Ae,canplay$:new Ae,isLive$:new B(void 0),isLowLatency$:new B(!1),canChangePlaybackSpeed$:new B(!0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),inPiP$:new B(!1),inFullscreen$:new B(!1),element$:new B(void 0),elementVisible$:new B(!0),availableSources$:new B(void 0),is3DVideo$:new B(!1),playbackState$:new B("")};this.subscription=new xS;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=jb([...Wb(this.params.tuning),...Gb(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>ES(e.sources[u])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(u=>!i.includes(u)),...t.filter(u=>i.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",PS(s)),this.screenFormatsIterator=new ma(s);let n=[...Ru(!0),...Ru(!1)];this.chromecastFormatsIterator=new ma(n.filter(u=>ES(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new ga(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy(),this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(L$(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Ks.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Sa(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return xt(o),new oa(V(k({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return xt(o),new ua(V(k({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return xt(o),kr||!this.params.tuning.useHlsJs?new pa(V(k({},n),{source:o})):new la(V(k({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return xt(o),new da(V(k({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return xt(o),new ha(V(k({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return xt(o),new Ab(V(k({},n),{source:o,config:V(k({},B$),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return xt(o),new fa({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Sa(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return xt(o),new bi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Sa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Sa(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Sa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return V(k({},e),{url:r(e.url)})}return(0,AS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new xS,t=!1,r=0;return e.add(C$(this.providerOutput.error$,vS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(M$(i=>({id:`ProviderHangup:${i}`,category:Ks.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($$(({to:s})=>s==="playing"),D$()).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===Ks.NETWORK,u=i.category===Ks.FATAL,c=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!u,d=c&&!u&&(o&&t||!l);n=V(k({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:c,tryFailover:d,canReinitProvider:l}),d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",PS(n))})),e}};import{fromEvent as Js,once as O$,combine as V$,Subscription as wS,ValueSubject as pc,map as _$,filter as N$,isNonNullable as Xs,now as we,safeStorage as hc}from"@vkontakte/videoplayer-shared";var F$=5e3,kS="one_video_throughput",RS="one_video_rtt",ct=window.navigator.connection,$S=()=>{let a=ct==null?void 0:ct.downlink;if(Xs(a)&&a!==10)return a*1e3},LS=()=>{let a=ct==null?void 0:ct.rtt;if(Xs(a)&&a!==3e3)return a},MS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},fc=class a{constructor(e){this.subscription=new wS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(kS)||(e.useBrowserEstimation?$S():void 0)||F$,r=(s=(i=a.load(RS))!=null?i:e.useBrowserEstimation?LS():void 0)!=null?s:0;if(this.throughput$=new pc(t),this.rtt$=new pc(r),this.rttAdjustedThroughput$=new pc(MS(t,r,e.rttPenaltyRequestSize)),this.throughput=Xt.getSmoothedValue(t,-1,e),this.rtt=Xt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=$S();u&&this.throughput.next(u);let c=LS();Xs(c)&&this.rtt.next(c)};ct&&"onchange"in ct&&this.subscription.add(Js(ct,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{hc.set(kS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{hc.set(RS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(V$({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(_$(({throughput:n,rtt:o})=>MS(n,o,e.rttPenaltyRequestSize)),N$(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=we(),i=new wS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Js(e,"progress").pipe(O$()).subscribe(s=>{t=s.loaded,r=we()}));break;case 1:case 0:i.add(Js(e,"loadstart").subscribe(()=>{t=0,r=we()}));break}i.add(Js(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=we(),u=n-t,c=o-r;this.addRawSpeed(u,c,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=we(),n=0,o=we(),u=l=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},c=p=>R(this,[p],function*({done:l,value:d}){if(l)!t&&this.addRawSpeed(i,we()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=we();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=we()}else n+=d.byteLength;o=we()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&we()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,we()-o,this.concurrentDownloads.size),n=0,o=we());yield r==null?void 0:r.read().then(c,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(c,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=hc.get(e);if(Xs(t))return(r=parseInt(t,10))!=null?r:void 0}},CS=fc;import{fillWithDefault as q$,VideoQuality as DS}from"@vkontakte/videoplayer-shared";var BS={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:DS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:DS.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,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},OS=a=>{var e;return V(k({},q$(a,BS)),{configName:[...(e=a.configName)!=null?e:[],...BS.configName]})};import{assertNonNullable as Zs,combine as Pt,ErrorCategory as en,filter as ue,filterChanged as U,fromEvent as bc,isNonNullable as Q$,isNullable as z$,Logger as K$,map as q,mapTo as FS,merge as At,now as tn,once as lt,Subject as Y,Subscription as qS,tap as US,ValueSubject as P,isHigher as J$,isInvariantQuality as HS,flattenObject as wt,throttle as gc,getTraceSubscriptionMethod as jS,Tracer as X$}from"@vkontakte/videoplayer-shared";import{merge as U$,map as H$,filter as VS,isNonNullable as j$}from"@vkontakte/videoplayer-shared";var mc=({seekState:a,position$:e})=>U$(a.stateChangeEnded$.pipe(H$(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),VS(j$)),e.pipe(VS(()=>a.getState().state==="none")));import{assertNonNullable as G$}from"@vkontakte/videoplayer-shared";var _S=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return G$(e,`Wrong container or containerId {${a.container}}`),e};import{filter as W$,once as Y$}from"@vkontakte/videoplayer-shared";var NS=(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(W$(i=>i.length>0),Y$()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var rn=class{constructor(e={configName:[]},t=X$.createRootTracer(!1)){this.subscription=new qS;this.logger=new K$;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new M("stopped"),seekState:new M({state:"none"}),volume:new M({volume:1,muted:!1}),videoTrack:new M(void 0),videoStream:new M(void 0),audioStream:new M(void 0),autoVideoTrackSwitching:new M(!0),autoVideoTrackLimits:new M({}),isLooped:new M(!1),playbackRate:new M(1),externalTextTracks:new M([]),internalTextTracks:new M([]),currentTextTrack:new M(void 0),textTrackCuesSettings:new M({}),cameraOrientation:new M({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new Y,ready$:new Y,started$:new Y,playing$:new Y,paused$:new Y,stopped$:new Y,willStart$:new Y,willResume$:new Y,willPause$:new Y,willStop$:new Y,willDestruct$:new Y,watchCoverageRecord$:new Y,watchCoverageLive$:new Y,managedError$:new Y,fatalError$:new Y,ended$:new Y,looped$:new Y,seeked$:new Y,willSeek$:new Y,firstBytes$:new Y,loadedMetadata$:new Y,firstFrame$:new Y,canplay$:new Y,log$:new Y};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:sb};if(this.initLogs(),this.tuning=OS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ka({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new CS(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:en.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o;this.config=e;let i=e,{container:t}=i,r=jc(i,["container"]);return this.tracer.log("initVideo",wt(r)),this.domContainer=_S(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new va({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&&!Ai()?(this.tracer.log("request play from hidden tab"),bc(document,"visibilitychange").pipe(lt()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Zs(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ue(r=>r.length>0),lt()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",wt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Zs(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",wt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>k({type:"external"},t))),this}selectTextTrack(e){var t;return NS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",k({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(z$(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return Q$(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(At(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(q(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ue(({from:e})=>e==="stopped"),lt()).subscribe(()=>{this.initedAt=tn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",wt(n)),n.state==="requested"?this.desiredState.seekState.setState(V(k({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:en.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",wt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(q(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(q(n=>n.destination),U()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(q(n=>n.map(({quality:o})=>o).sort((o,u)=>HS(o)?1:HS(u)?-1:J$(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(U()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(U((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(U((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(U()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(U()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(U()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(q(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Pt({hasLiveOffsetByPaused:At(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(q(n=>n.to),U(),q(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Pt({atLiveEdge:Pt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:mc({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(),US(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(q(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Pt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(q(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),U(),US(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(mc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(At(e.providerOutput.endedEvent$.pipe(FS(!0)),e.providerOutput.seekedEvent$.pipe(FS(!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:en.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(lt(),q(n=>n!=null?n:tn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(lt(),q(()=>tn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(lt(),q(()=>tn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ue(({to:n})=>n==="playing"),lt()).subscribe(()=>r.next(!1)));let i=0,s=At(e.providerOutput.isBuffering$,t,r).pipe(q(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),U());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(At(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,c;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(c=n==null?void 0:n.size)==null?void 0:c.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(At(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),c=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),d;l==="CONNECTED"?d="second_screen":u?c?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(q(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new qS;this.subscription.add(t),this.subscription.add(e.current$.pipe(U((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ue(r=>r.length>0),lt()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t,r=(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=Tt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(At(this.desiredState.videoTrack.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(q(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Zs(this.providerContainer),Zs(e),ab(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>ib(r)),this.providerContainer.current$.subscribe(({type:r})=>yi("provider",r)),e.duration$.subscribe(r=>yi("duration",r)),e.availableVideoTracks$.pipe(ue(r=>!!r.length),lt()).subscribe(r=>yi("tracks",r)),this.events.fatalError$.subscribe(new ne("fatalError")),this.events.managedError$.subscribe(new ne("managedError")),e.position$.subscribe(new ne("position")),e.currentVideoTrack$.pipe(q(r=>r==null?void 0:r.quality)).subscribe(new ne("quality")),this.info.currentBuffer$.subscribe(new ne("buffer")),e.isBuffering$.subscribe(new ne("isBuffering"))].forEach(r=>this.subscription.add(r)),yi("codecs",Hb())}initTracerSubscription(){let e=jS(this.tracer.log.bind(this.tracer)),t=jS(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(U()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Pt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ue(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),U((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ue(r=>r>0),U()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ue(r=>r>0),U()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Pt({currentBuffer:this.info.currentBuffer$.pipe(ue(r=>r.end>0),U((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(U())}).pipe(gc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(U()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(U()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(U()).subscribe(e("canChangePlaybackSpeed"))).add(Pt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ue(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),gc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(U(),ue(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(U(),ue(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(U()).subscribe(e("muted"))).add(this.info.volume$.pipe(U()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(U(),ue(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Pt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ue(({throughputEstimation:r,rtt:i})=>!!r&&!!i),gc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(U(),ue(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>R(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:en.DOM,message:String(i)})})});this.subscription.add(At(bc(document,"visibilitychange"),bc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",wt({quality:t,availableTracks:wt(e),track:wt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as iW,Observable as aW,Subject as sW,ValueSubject as nW,VideoQuality as oW}from"@vkontakte/videoplayer-shared";var uW=`@vkontakte/videoplayer-core@${Gc}`;export{Aa as ChromecastState,yn as HttpConnectionType,aW as Observable,pe as PlaybackState,rn as Player,uW as SDK_VERSION,sW as Subject,iW as Subscription,Tn as Surface,Gc as VERSION,nW as ValueSubject,mt as VideoFormat,oW as VideoQuality};
112
+ `;var sn=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new rn(this.params.fov,this.params.orientation),this.cameraRotationManager=new an(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(mS,this.gl.VERTEX_SHADER),r=this.createShader(bS,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 or=class{constructor(e){this.subscription=new _R;this.videoState=new C("stopped");this.elementSize$=new NR(void 0);this.droppedFramesManager=new Cs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ci;this.audioTrackSwitchHistory=new Ci;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 LR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new sn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new tn({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:fl.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(gS(l=>!!l.length),vS()).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(gS(BR),vS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(SS(l=>l.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(Oe(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;let c=this.player.getStreams();if(MR(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(il(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 c.video){d.push(al(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),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)}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=l=>e.error$.next({id:"RepresentationSwitch",category:fl.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(nn(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 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(ml()).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(al(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ml()).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(il(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));let o=t.playbackState.stateChangeStarted$.pipe(SS(({to:l})=>l==="ready"),ml());this.subscription.add(nn(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(nn(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=nn(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,ce,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 l=[...this.videoStreamsMap.keys()].find(({id:w})=>w===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=ct(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=Rs(n,c,(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=Ys(n,c,(_=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=Rs(o,c,(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=Ys(o,c,(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(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,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,c,(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&&Ys(T,c,(ce=this.audioStreamsMap.get(b))!=null?ce:[]);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:fl.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),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 yS,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(yS({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(yS({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=rS(i);this.params.output.availableTextTracks$.next([s])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var IS=Xe(As(),1);import{assertNever as Ia,assertNonNullable as TS,debounce as UR,ErrorCategory as on,filter as HR,isNonNullable as jR,isNullable as GR,map as un,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 rt;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:on.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,IS.default)(import("hls.js").then(i=>{e||(Qe.Hls=i.default,Qe.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){TS(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(){TS(Qe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:on.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Se(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(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(Oe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(un(l=>l.to)),this.params.output.playbackState$),this.subscription.add(zr(this.hls,Qe.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:on.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(zr(this.hls,Qe.Events.MANIFEST_PARSED).pipe(un(({levels:l})=>l.reduce((c,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 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(zr(this.hls,Qe.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(zr(this.hls,Qe.Events.LEVEL_LOADING).pipe(un(({url:l})=>re(l))),t.hostname$),s(zr(this.hls,Qe.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(Pt(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=zr(this.hls,Qe.Events.LEVEL_SWITCHED).pipe(un(({level:l})=>n(this.hls.levels[l])));o.pipe(HR(jR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Pt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(GR(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=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:on.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 ES="X-Playback-Duration",bl=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(ES)?parseInt(e.headers.get(ES),10):void 0});import{assertNever as r$,combine as i$,debounce as a$,ErrorCategory as cn,filter as s$,filterChanged as n$,isNonNullable as PS,isNullable as dn,map as AS,merge as o$,observableFrom as u$,Subscription as l$,ValueSubject as vl,VideoQuality as c$}from"@vkontakte/videoplayer-shared";var Sl=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],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,Sl.default)(l[1].split(",").map(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(c){let d=(0,Sl.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}},t$=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),gl=0,xS=(r,...i)=>R(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield dt(a)).text();gl+=1;try{let{qualityManifests:o,textTracks:u}=e$(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(gl<=t.manifestRetryMaxCount)return yield t$(XR(gl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),xS(a,e,t)}return{qualityManifests:[],textTracks:[]}}),ln=xS;var xa=class{constructor(e){this.subscription=new l$;this.videoState=new C("stopped");this.textTracksManager=new rt;this.manifests$=new vl([]);this.liveOffset=new ut;this.manifestStartTime$=new vl(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 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:c$.INVARIANT,url:this.params.source.url},ln(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:cn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:cn.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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new vl((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:cn.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(Oe(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(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&PS(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(re(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(i$({startTime:this.manifestStartTime$.pipe(s$(PS)),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: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=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(dn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ae(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),bl(n).then(l=>{var c;if(!dn(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(dn(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();bl(b).then(g=>{dn(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:cn.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 yl,fromEvent as Tl,isNonNullable as h$,isNullable as f$,map as wS,merge as kS,observableFrom as RS,Subscription as m$,ValueSubject as b$,VideoQuality as g$,clientChecker as S$}from"@vkontakte/videoplayer-shared";var Pa=class{constructor(e){this.subscription=new m$;this.videoState=new C("stopped");this.textTracksManager=new rt;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 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 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),ln(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:yl.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:yl.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(wS(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(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&h$(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(f=>f.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(re(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let 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(wS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!S$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(kS(Tl(o,"addtrack"),Tl(o,"removetrack"),Tl(o,"change"),RS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=kS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,RS(["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[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(){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:yl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as v$,assertNonNullable as $S,debounce as y$,ErrorCategory as LS,isHigher as T$,isHigherOrEqual as I$,isInvariantQuality as MS,isLowerOrEqual as E$,isNonNullable as x$,merge as P$,observableFrom as A$,Subscription as w$,map as k$}from"@vkontakte/videoplayer-shared";var Aa=class{constructor(e){this.subscription=new w$;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new rt;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 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:LS.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(Oe(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&&x$(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=P$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,A$(["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;$S(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];$S(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:LS.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=>!MS(d.track.quality)&&E$(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&&I$(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!MS(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(l=>l.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 DS,debounce as M$,merge as BS,observableFrom as C$,Subscription as D$,map as OS,ValueSubject as B$,ErrorCategory as El,VideoQuality as O$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as R$}from"@vkontakte/videoplayer-shared";var CS=["stun:videostun.mycdn.me:80"],$$=1e3,L$=3,Il=()=>null,pn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=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 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:CS}]};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:CS,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 DS(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 pn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),be(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:El.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};BS(this.videoState.stateChangeStarted$.pipe(OS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(OS(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(Oe(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 DS(n.to)}},r)).add(BS(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:El.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:El.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 fn,filter as H$,isNonNullable as US,isNullable as j$,map as G$,merge as W$,once as Y$,Subject as we,Subscription as HS,ValueSubject as O,flattenObject as jS}from"@vkontakte/videoplayer-shared";import{Observable as V$,map as VS,Subscription as _$,Subject as N$}from"@vkontakte/videoplayer-shared";var _S=a=>new V$(e=>{let t=new _$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(VS(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(VS(({type:l})=>l!==void 0)),n=new N$,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 NS,Subscription as F$,combine as q$,filter as FS,once as qS}from"@vkontakte/videoplayer-shared";var Ra=null,hn=null;function xl(){return Ra||(Ra=new(window.AudioContext||window.webkitAudioContext)),hn||(hn=new GainNode(Ra,{gain:1}),hn.connect(Ra.destination)),{audioCtx:Ra,gainNode:hn}}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(FS(n=>!!n.type),qS()).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(FS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),qS()).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}=xl(),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:NS.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:NS.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=xl();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 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=cg([...pg(this.params.tuning),...dg(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>US(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",jS(s)),this.screenFormatsIterator=new ka(s);let n=[...qu(!0),...qu(!1)];this.chromecastFormatsIterator=new ka(n.filter(u=>US(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:fn.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(P({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Ta(M(P({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Mt(o),_r||!this.params.tuning.useHlsJs?new Pa(M(P({},n),{source:o})):new Ea(M(P({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Mt(o),new xa(M(P({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Aa(M(P({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Wb(M(P({},n),{source:o,config:M(P({},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 ki({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(P({},e),{url:r(e.url)})}return(0,GS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new HS,t=!1,r=0;return e.add(W$(this.providerOutput.error$,_S({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(G$(i=>({id:`ProviderHangup:${i}`,category:fn.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===fn.NETWORK,u=i.category===fn.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=M(P({},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",jS(n))})),e}};import{fromEvent as mn,once as z$,combine as K$,Subscription as WS,ValueSubject as Pl,map as J$,filter as X$,isNonNullable as bn,now as ke,safeStorage as Al}from"@vkontakte/videoplayer-shared";var Z$=5e3,YS="one_video_throughput",QS="one_video_rtt",mt=window.navigator.connection,zS=()=>{let a=mt==null?void 0:mt.downlink;if(bn(a)&&a!==10)return a*1e3},KS=()=>{let a=mt==null?void 0:mt.rtt;if(bn(a)&&a!==3e3)return a},JS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},wl=class a{constructor(e){this.subscription=new WS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(YS)||(e.useBrowserEstimation?zS():void 0)||Z$,r=(s=(i=a.load(QS))!=null?i:e.useBrowserEstimation?KS():void 0)!=null?s:0;if(this.throughput$=new Pl(t),this.rtt$=new Pl(r),this.rttAdjustedThroughput$=new Pl(JS(t,r,e.rttPenaltyRequestSize)),this.throughput=sr.getSmoothedValue(t,-1,e),this.rtt=sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=zS();u&&this.throughput.next(u);let l=KS();bn(l)&&this.rtt.next(l)};mt&&"onchange"in mt&&this.subscription.add(mn(mt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Al.set(YS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Al.set(QS,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})=>JS(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 WS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(mn(e,"progress").pipe(z$()).subscribe(s=>{t=s.loaded,r=ke()}));break;case 1:case 0:i.add(mn(e,"loadstart").subscribe(()=>{t=0,r=ke()}));break}i.add(mn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=ke(),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=ke(),n=0,o=ke(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>R(this,[p],function*({done:c,value:d}){if(c)!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(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=Al.get(e);if(bn(t))return(r=parseInt(t,10))!=null?r:void 0}},XS=wl;import{fillWithDefault as eL,VideoQuality as ZS}from"@vkontakte/videoplayer-shared";var ev={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:ZS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ZS.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,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},tv=a=>{var e;return M(P({},eL(a,ev)),{configName:[...(e=a.configName)!=null?e:[],...ev.configName]})};import{assertNonNullable as gn,combine as Ct,ErrorCategory as Sn,filter as le,filterChanged as U,fromEvent as Rl,isNonNullable as oL,isNullable as uL,Logger as lL,map as q,mapTo as sv,merge as Dt,now as vn,once as bt,Subject as Y,Subscription as nv,tap as ov,ValueSubject as A,isHigher as cL,isInvariantQuality as uv,flattenObject as Bt,throttle as $l,getTraceSubscriptionMethod as lv,Tracer as dL}from"@vkontakte/videoplayer-shared";import{merge as tL,map as rL,filter as rv,isNonNullable as iL}from"@vkontakte/videoplayer-shared";var kl=({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}),rv(iL)),e.pipe(rv(()=>a.getState().state==="none")));import{assertNonNullable as aL}from"@vkontakte/videoplayer-shared";var iv=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 av=(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 yn=class{constructor(e={configName:[]},t=dL.createRootTracer(!1)){this.subscription=new nv;this.logger=new lL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new A(!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 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 Y,ready$:new Y,started$:new Y,playing$:new Y,paused$:new Y,stopped$:new Y,willStart$:new Y,willResume$:new Y,willPause$:new Y,willStop$:new Y,willDestruct$:new Y,watchCoverageRecord$:new Y,watchCoverageLive$:new Y,managedError$:new Y,fatalError$:new Y,ended$:new Y,looped$:new Y,seeked$:new Y,willSeek$:new Y,firstBytes$:new Y,loadedMetadata$:new Y,firstFrame$:new Y,canplay$:new Y,log$:new Y};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:Pb};if(this.initLogs(),this.tuning=tv(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ga({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new XS(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:Sn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o;this.config=e;let i=e,{container:t}=i,r=cc(i,["container"]);return this.tracer.log("initVideo",Bt(r)),this.domContainer=iv(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&&!_i()?(this.tracer.log("request play from hidden tab"),Rl(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){gn(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),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;gn(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=>P({type:"external"},t))),this}selectTextTrack(e){var t;return av(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",P({},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(le(({from:e})=>e==="stopped"),bt()).subscribe(()=>{this.initedAt=vn(),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(P({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Sn.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)=>uv(o)?1:uv(u)?-1:cL(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:kl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(q(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),U(),ov(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(),ov(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(kl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Dt(e.providerOutput.endedEvent$.pipe(sv(!0)),e.providerOutput.seekedEvent$.pipe(sv(!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:Sn.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:vn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(bt(),q(()=>vn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(bt(),q(()=>vn()-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"),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,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(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(),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(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 nv;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(le(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;gn(this.providerContainer),gn(e),xb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Eb(r)),this.providerContainer.current$.subscribe(({type:r})=>Mi("provider",r)),e.duration$.subscribe(r=>Mi("duration",r)),e.availableVideoTracks$.pipe(le(r=>!!r.length),bt()).subscribe(r=>Mi("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)),Mi("codecs",lg())}initTracerSubscription(){let e=lv(this.tracer.log.bind(this.tracer)),t=lv(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(le(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),U((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(le(r=>r>0),U()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(le(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(le(r=>r.end>0),U((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(U())}).pipe($l(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(le(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),$l(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(U(),le(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(U(),le(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(),le(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ct({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(le(({throughputEstimation:r,rtt:i})=>!!r&&!!i),$l(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(U(),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=()=>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:Sn.DOM,message:String(i)})})});this.subscription.add(Dt(Rl(document,"visibilitychange"),Rl(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 MW,Observable as CW,Subject as DW,ValueSubject as BW,VideoQuality as OW}from"@vkontakte/videoplayer-shared";var VW=`@vkontakte/videoplayer-core@${dc}`;export{Ha as ChromecastState,Mn as HttpConnectionType,CW as Observable,he as PlaybackState,yn as Player,VW as SDK_VERSION,DW as Subject,MW as Subscription,Cn as Surface,dc as VERSION,BW as ValueSubject,Et as VideoFormat,OW as VideoQuality};