@vkontakte/videoplayer-core 2.0.113-dev.95abd0e7.0 → 2.0.113-dev.cde1b449.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +10 -10
- package/es2015.esm.js +9 -9
- package/es2018.cjs.js +10 -10
- package/es2018.esm.js +10 -10
- package/esnext.cjs.js +21 -21
- package/esnext.esm.js +20 -20
- package/evergreen.esm.js +17 -17
- package/package.json +2 -2
- package/types/providers/DashProvider/lib/buffer.d.ts +3 -0
- package/types/providers/DashProvider/lib/types.d.ts +1 -0
- package/types/utils/VolumeMultiplierManager/VolumeMultiplierManager.d.ts +4 -2
- package/types/utils/tuningConfig.d.ts +2 -0
package/es2018.esm.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.113-dev.
|
|
3
|
-
* Tue, 08 Oct 2024 11:
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.113-dev.cde1b449.0
|
|
3
|
+
* Tue, 08 Oct 2024 11:11:35 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-113/doc/
|
|
5
5
|
*/
|
|
6
|
-
var hv=Object.create;var el=Object.defineProperty;var fv=Object.getOwnPropertyDescriptor;var mv=Object.getOwnPropertyNames;var bv=Object.getPrototypeOf,gv=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Sv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of mv(e))!gv.call(a,i)&&i!==t&&el(a,i,{get:()=>e[i],enumerable:!(r=fv(e,i))||r.enumerable});return a};var Qe=(a,e,t)=>(t=a!=null?hv(bv(a)):{},Sv(e||!a||!a.__esModule?el(t,"default",{value:a,enumerable:!0}):t,a));var ye=m((gL,ul)=>{"use strict";ul.exports=function(a){try{return!!a()}catch(e){return!0}}});var Zr=m((SL,cl)=>{"use strict";var Av=ye();cl.exports=!Av(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var le=m((vL,pl)=>{"use strict";var ll=Zr(),dl=Function.prototype,wn=dl.call,wv=ll&&dl.bind.bind(wn,wn);pl.exports=ll?wv:function(a){return function(){return wn.apply(a,arguments)}}});var dr=m((yL,fl)=>{"use strict";var hl=le(),kv=hl({}.toString),Rv=hl("".slice);fl.exports=function(a){return Rv(kv(a),8,-1)}});var bl=m((TL,ml)=>{"use strict";var $v=le(),Lv=ye(),Mv=dr(),kn=Object,Cv=$v("".split);ml.exports=Lv(function(){return!kn("z").propertyIsEnumerable(0)})?function(a){return Mv(a)==="String"?Cv(a,""):kn(a)}:kn});var pr=m((IL,gl)=>{"use strict";gl.exports=function(a){return a==null}});var ei=m((EL,Sl)=>{"use strict";var Dv=pr(),Bv=TypeError;Sl.exports=function(a){if(Dv(a))throw new Bv("Can't call method on "+a);return a}});var hr=m((xL,vl)=>{"use strict";var Ov=bl(),Vv=ei();vl.exports=function(a){return Ov(Vv(a))}});var Rn=m((PL,yl)=>{"use strict";yl.exports=function(){}});var _t=m((AL,Tl)=>{"use strict";Tl.exports={}});var Q=m(($n,Il)=>{"use strict";var ti=function(a){return a&&a.Math===Math&&a};Il.exports=ti(typeof globalThis=="object"&&globalThis)||ti(typeof window=="object"&&window)||ti(typeof self=="object"&&self)||ti(typeof global=="object"&&global)||ti(typeof $n=="object"&&$n)||function(){return this}()||Function("return this")()});var Y=m((wL,El)=>{"use strict";var Ln=typeof document=="object"&&document.all;El.exports=typeof Ln=="undefined"&&Ln!==void 0?function(a){return typeof a=="function"||a===Ln}:function(a){return typeof a=="function"}});var Al=m((kL,Pl)=>{"use strict";var _v=Q(),Nv=Y(),xl=_v.WeakMap;Pl.exports=Nv(xl)&&/native code/.test(String(xl))});var ke=m((RL,wl)=>{"use strict";var Fv=Y();wl.exports=function(a){return typeof a=="object"?a!==null:Fv(a)}});var Re=m(($L,kl)=>{"use strict";var qv=ye();kl.exports=!qv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ha=m((LL,$l)=>{"use strict";var Uv=Q(),Rl=ke(),Mn=Uv.document,Hv=Rl(Mn)&&Rl(Mn.createElement);$l.exports=function(a){return Hv?Mn.createElement(a):{}}});var Cn=m((ML,Ll)=>{"use strict";var jv=Re(),Gv=ye(),Wv=Ha();Ll.exports=!jv&&!Gv(function(){return Object.defineProperty(Wv("div"),"a",{get:function(){return 7}}).a!==7})});var Dn=m((CL,Ml)=>{"use strict";var Yv=Re(),Qv=ye();Ml.exports=Yv&&Qv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ze=m((DL,Cl)=>{"use strict";var zv=ke(),Kv=String,Jv=TypeError;Cl.exports=function(a){if(zv(a))return a;throw new Jv(Kv(a)+" is not an object")}});var Te=m((BL,Dl)=>{"use strict";var Xv=Zr(),ja=Function.prototype.call;Dl.exports=Xv?ja.bind(ja):function(){return ja.apply(ja,arguments)}});var Ga=m((OL,Bl)=>{"use strict";Bl.exports={}});var et=m((VL,Vl)=>{"use strict";var Bn=Ga(),On=Q(),Zv=Y(),Ol=function(a){return Zv(a)?a:void 0};Vl.exports=function(a,e){return arguments.length<2?Ol(Bn[a])||Ol(On[a]):Bn[a]&&Bn[a][e]||On[a]&&On[a][e]}});var ri=m((_L,_l)=>{"use strict";var ey=le();_l.exports=ey({}.isPrototypeOf)});var fr=m((NL,ql)=>{"use strict";var ty=Q(),Nl=ty.navigator,Fl=Nl&&Nl.userAgent;ql.exports=Fl?String(Fl):""});var _n=m((FL,Yl)=>{"use strict";var Wl=Q(),Vn=fr(),Ul=Wl.process,Hl=Wl.Deno,jl=Ul&&Ul.versions||Hl&&Hl.version,Gl=jl&&jl.v8,Fe,Wa;Gl&&(Fe=Gl.split("."),Wa=Fe[0]>0&&Fe[0]<4?1:+(Fe[0]+Fe[1]));!Wa&&Vn&&(Fe=Vn.match(/Edge\/(\d+)/),(!Fe||Fe[1]>=74)&&(Fe=Vn.match(/Chrome\/(\d+)/),Fe&&(Wa=+Fe[1])));Yl.exports=Wa});var Nn=m((qL,zl)=>{"use strict";var Ql=_n(),ry=ye(),iy=Q(),ay=iy.String;zl.exports=!!Object.getOwnPropertySymbols&&!ry(function(){var a=Symbol("symbol detection");return!ay(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Ql&&Ql<41})});var Fn=m((UL,Kl)=>{"use strict";var sy=Nn();Kl.exports=sy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var qn=m((HL,Jl)=>{"use strict";var ny=et(),oy=Y(),uy=ri(),cy=Fn(),ly=Object;Jl.exports=cy?function(a){return typeof a=="symbol"}:function(a){var e=ny("Symbol");return oy(e)&&uy(e.prototype,ly(a))}});var ii=m((jL,Xl)=>{"use strict";var dy=String;Xl.exports=function(a){try{return dy(a)}catch(e){return"Object"}}});var tt=m((GL,Zl)=>{"use strict";var py=Y(),hy=ii(),fy=TypeError;Zl.exports=function(a){if(py(a))return a;throw new fy(hy(a)+" is not a function")}});var ai=m((WL,ed)=>{"use strict";var my=tt(),by=pr();ed.exports=function(a,e){var t=a[e];return by(t)?void 0:my(t)}});var rd=m((YL,td)=>{"use strict";var Un=Te(),Hn=Y(),jn=ke(),gy=TypeError;td.exports=function(a,e){var t,r;if(e==="string"&&Hn(t=a.toString)&&!jn(r=Un(t,a))||Hn(t=a.valueOf)&&!jn(r=Un(t,a))||e!=="string"&&Hn(t=a.toString)&&!jn(r=Un(t,a)))return r;throw new gy("Can't convert object to primitive value")}});var qe=m((QL,id)=>{"use strict";id.exports=!0});var nd=m((zL,sd)=>{"use strict";var ad=Q(),Sy=Object.defineProperty;sd.exports=function(a,e){try{Sy(ad,a,{value:e,configurable:!0,writable:!0})}catch(t){ad[a]=e}return e}});var si=m((KL,cd)=>{"use strict";var vy=qe(),yy=Q(),Ty=nd(),od="__core-js_shared__",ud=cd.exports=yy[od]||Ty(od,{});(ud.versions||(ud.versions=[])).push({version:"3.38.0",mode:vy?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Gn=m((JL,dd)=>{"use strict";var ld=si();dd.exports=function(a,e){return ld[a]||(ld[a]=e||{})}});var ni=m((XL,pd)=>{"use strict";var Iy=ei(),Ey=Object;pd.exports=function(a){return Ey(Iy(a))}});var Ue=m((ZL,hd)=>{"use strict";var xy=le(),Py=ni(),Ay=xy({}.hasOwnProperty);hd.exports=Object.hasOwn||function(e,t){return Ay(Py(e),t)}});var Wn=m((eM,fd)=>{"use strict";var wy=le(),ky=0,Ry=Math.random(),$y=wy(1 .toString);fd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+$y(++ky+Ry,36)}});var ie=m((tM,bd)=>{"use strict";var Ly=Q(),My=Gn(),md=Ue(),Cy=Wn(),Dy=Nn(),By=Fn(),mr=Ly.Symbol,Yn=My("wks"),Oy=By?mr.for||mr:mr&&mr.withoutSetter||Cy;bd.exports=function(a){return md(Yn,a)||(Yn[a]=Dy&&md(mr,a)?mr[a]:Oy("Symbol."+a)),Yn[a]}});var yd=m((rM,vd)=>{"use strict";var Vy=Te(),gd=ke(),Sd=qn(),_y=ai(),Ny=rd(),Fy=ie(),qy=TypeError,Uy=Fy("toPrimitive");vd.exports=function(a,e){if(!gd(a)||Sd(a))return a;var t=_y(a,Uy),r;if(t){if(e===void 0&&(e="default"),r=Vy(t,a,e),!gd(r)||Sd(r))return r;throw new qy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ny(a,e)}});var Qn=m((iM,Td)=>{"use strict";var Hy=yd(),jy=qn();Td.exports=function(a){var e=Hy(a,"string");return jy(e)?e:e+""}});var Nt=m(Ed=>{"use strict";var Gy=Re(),Wy=Cn(),Yy=Dn(),Ya=ze(),Id=Qn(),Qy=TypeError,zn=Object.defineProperty,zy=Object.getOwnPropertyDescriptor,Kn="enumerable",Jn="configurable",Xn="writable";Ed.f=Gy?Yy?function(e,t,r){if(Ya(e),t=Id(t),Ya(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Xn in r&&!r[Xn]){var i=zy(e,t);i&&i[Xn]&&(e[t]=r.value,r={configurable:Jn in r?r[Jn]:i[Jn],enumerable:Kn in r?r[Kn]:i[Kn],writable:!1})}return zn(e,t,r)}:zn:function(e,t,r){if(Ya(e),t=Id(t),Ya(r),Wy)try{return zn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Qy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var oi=m((sM,xd)=>{"use strict";xd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var br=m((nM,Pd)=>{"use strict";var Ky=Re(),Jy=Nt(),Xy=oi();Pd.exports=Ky?function(a,e,t){return Jy.f(a,e,Xy(1,t))}:function(a,e,t){return a[e]=t,a}});var Qa=m((oM,wd)=>{"use strict";var Zy=Gn(),eT=Wn(),Ad=Zy("keys");wd.exports=function(a){return Ad[a]||(Ad[a]=eT(a))}});var za=m((uM,kd)=>{"use strict";kd.exports={}});var ro=m((cM,Ld)=>{"use strict";var tT=Al(),$d=Q(),rT=ke(),iT=br(),Zn=Ue(),eo=si(),aT=Qa(),sT=za(),Rd="Object already initialized",to=$d.TypeError,nT=$d.WeakMap,Ka,ui,Ja,oT=function(a){return Ja(a)?ui(a):Ka(a,{})},uT=function(a){return function(e){var t;if(!rT(e)||(t=ui(e)).type!==a)throw new to("Incompatible receiver, "+a+" required");return t}};tT||eo.state?(He=eo.state||(eo.state=new nT),He.get=He.get,He.has=He.has,He.set=He.set,Ka=function(a,e){if(He.has(a))throw new to(Rd);return e.facade=a,He.set(a,e),e},ui=function(a){return He.get(a)||{}},Ja=function(a){return He.has(a)}):(Ft=aT("state"),sT[Ft]=!0,Ka=function(a,e){if(Zn(a,Ft))throw new to(Rd);return e.facade=a,iT(a,Ft,e),e},ui=function(a){return Zn(a,Ft)?a[Ft]:{}},Ja=function(a){return Zn(a,Ft)});var He,Ft;Ld.exports={set:Ka,get:ui,has:Ja,enforce:oT,getterFor:uT}});var io=m((lM,Bd)=>{"use strict";var cT=Zr(),Dd=Function.prototype,Md=Dd.apply,Cd=Dd.call;Bd.exports=typeof Reflect=="object"&&Reflect.apply||(cT?Cd.bind(Md):function(){return Cd.apply(Md,arguments)})});var ao=m((dM,Od)=>{"use strict";var lT=dr(),dT=le();Od.exports=function(a){if(lT(a)==="Function")return dT(a)}});var Fd=m(Nd=>{"use strict";var Vd={}.propertyIsEnumerable,_d=Object.getOwnPropertyDescriptor,pT=_d&&!Vd.call({1:2},1);Nd.f=pT?function(e){var t=_d(this,e);return!!t&&t.enumerable}:Vd});var Hd=m(Ud=>{"use strict";var hT=Re(),fT=Te(),mT=Fd(),bT=oi(),gT=hr(),ST=Qn(),vT=Ue(),yT=Cn(),qd=Object.getOwnPropertyDescriptor;Ud.f=hT?qd:function(e,t){if(e=gT(e),t=ST(t),yT)try{return qd(e,t)}catch(r){}if(vT(e,t))return bT(!fT(mT.f,e,t),e[t])}});var so=m((fM,jd)=>{"use strict";var TT=ye(),IT=Y(),ET=/#|\.prototype\./,ci=function(a,e){var t=PT[xT(a)];return t===wT?!0:t===AT?!1:IT(e)?TT(e):!!e},xT=ci.normalize=function(a){return String(a).replace(ET,".").toLowerCase()},PT=ci.data={},AT=ci.NATIVE="N",wT=ci.POLYFILL="P";jd.exports=ci});var li=m((mM,Wd)=>{"use strict";var Gd=ao(),kT=tt(),RT=Zr(),$T=Gd(Gd.bind);Wd.exports=function(a,e){return kT(a),e===void 0?a:RT?$T(a,e):function(){return a.apply(e,arguments)}}});var $e=m((bM,Qd)=>{"use strict";var di=Q(),LT=io(),MT=ao(),CT=Y(),DT=Hd().f,BT=so(),gr=Ga(),OT=li(),Sr=br(),Yd=Ue();si();var VT=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return LT(a,this,arguments)};return e.prototype=a.prototype,e};Qd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?di:i?di[t]:di[t]&&di[t].prototype,o=r?gr:gr[t]||Sr(gr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,v;for(p in e)l=BT(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Yd(n,p),f=o[p],c&&(a.dontCallGetSet?(v=DT(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=OT(h,di):a.wrap&&c?g=VT(h):s&&CT(h)?g=MT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Sr(g,"sham",!0),Sr(o,p,g),s&&(d=t+"Prototype",Yd(gr,d)||Sr(gr,d,{}),Sr(gr[d],p,h),a.real&&u&&(l||!u[p])&&Sr(u,p,h)))}});var Jd=m((gM,Kd)=>{"use strict";var no=Re(),_T=Ue(),zd=Function.prototype,NT=no&&Object.getOwnPropertyDescriptor,oo=_T(zd,"name"),FT=oo&&function(){}.name==="something",qT=oo&&(!no||no&&NT(zd,"name").configurable);Kd.exports={EXISTS:oo,PROPER:FT,CONFIGURABLE:qT}});var Zd=m((SM,Xd)=>{"use strict";var UT=Math.ceil,HT=Math.floor;Xd.exports=Math.trunc||function(e){var t=+e;return(t>0?HT:UT)(t)}});var Xa=m((vM,ep)=>{"use strict";var jT=Zd();ep.exports=function(a){var e=+a;return e!==e||e===0?0:jT(e)}});var rp=m((yM,tp)=>{"use strict";var GT=Xa(),WT=Math.max,YT=Math.min;tp.exports=function(a,e){var t=GT(a);return t<0?WT(t+e,0):YT(t,e)}});var ap=m((TM,ip)=>{"use strict";var QT=Xa(),zT=Math.min;ip.exports=function(a){var e=QT(a);return e>0?zT(e,9007199254740991):0}});var Za=m((IM,sp)=>{"use strict";var KT=ap();sp.exports=function(a){return KT(a.length)}});var up=m((EM,op)=>{"use strict";var JT=hr(),XT=rp(),ZT=Za(),np=function(a){return function(e,t,r){var i=JT(e),s=ZT(i);if(s===0)return!a&&-1;var n=XT(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};op.exports={includes:np(!0),indexOf:np(!1)}});var dp=m((xM,lp)=>{"use strict";var eI=le(),uo=Ue(),tI=hr(),rI=up().indexOf,iI=za(),cp=eI([].push);lp.exports=function(a,e){var t=tI(a),r=0,i=[],s;for(s in t)!uo(iI,s)&&uo(t,s)&&cp(i,s);for(;e.length>r;)uo(t,s=e[r++])&&(~rI(i,s)||cp(i,s));return i}});var co=m((PM,pp)=>{"use strict";pp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var fp=m((AM,hp)=>{"use strict";var aI=dp(),sI=co();hp.exports=Object.keys||function(e){return aI(e,sI)}});var bp=m(mp=>{"use strict";var nI=Re(),oI=Dn(),uI=Nt(),cI=ze(),lI=hr(),dI=fp();mp.f=nI&&!oI?Object.defineProperties:function(e,t){cI(e);for(var r=lI(t),i=dI(t),s=i.length,n=0,o;s>n;)uI.f(e,o=i[n++],r[o]);return e}});var lo=m((kM,gp)=>{"use strict";var pI=et();gp.exports=pI("document","documentElement")});var mo=m((RM,xp)=>{"use strict";var hI=ze(),fI=bp(),Sp=co(),mI=za(),bI=lo(),gI=Ha(),SI=Qa(),vp=">",yp="<",ho="prototype",fo="script",Ip=SI("IE_PROTO"),po=function(){},Ep=function(a){return yp+fo+vp+a+yp+"/"+fo+vp},Tp=function(a){a.write(Ep("")),a.close();var e=a.parentWindow.Object;return a=null,e},vI=function(){var a=gI("iframe"),e="java"+fo+":",t;return a.style.display="none",bI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Ep("document.F=Object")),t.close(),t.F},es,ts=function(){try{es=new ActiveXObject("htmlfile")}catch(e){}ts=typeof document!="undefined"?document.domain&&es?Tp(es):vI():Tp(es);for(var a=Sp.length;a--;)delete ts[ho][Sp[a]];return ts()};mI[Ip]=!0;xp.exports=Object.create||function(e,t){var r;return e!==null?(po[ho]=hI(e),r=new po,po[ho]=null,r[Ip]=e):r=ts(),t===void 0?r:fI.f(r,t)}});var Ap=m(($M,Pp)=>{"use strict";var yI=ye();Pp.exports=!yI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var go=m((LM,kp)=>{"use strict";var TI=Ue(),II=Y(),EI=ni(),xI=Qa(),PI=Ap(),wp=xI("IE_PROTO"),bo=Object,AI=bo.prototype;kp.exports=PI?bo.getPrototypeOf:function(a){var e=EI(a);if(TI(e,wp))return e[wp];var t=e.constructor;return II(t)&&e instanceof t?t.prototype:e instanceof bo?AI:null}});var vr=m((MM,Rp)=>{"use strict";var wI=br();Rp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:wI(a,e,t),a}});var To=m((CM,Mp)=>{"use strict";var kI=ye(),RI=Y(),$I=ke(),LI=mo(),$p=go(),MI=vr(),CI=ie(),DI=qe(),yo=CI("iterator"),Lp=!1,rt,So,vo;[].keys&&(vo=[].keys(),"next"in vo?(So=$p($p(vo)),So!==Object.prototype&&(rt=So)):Lp=!0);var BI=!$I(rt)||kI(function(){var a={};return rt[yo].call(a)!==a});BI?rt={}:DI&&(rt=LI(rt));RI(rt[yo])||MI(rt,yo,function(){return this});Mp.exports={IteratorPrototype:rt,BUGGY_SAFARI_ITERATORS:Lp}});var rs=m((DM,Dp)=>{"use strict";var OI=ie(),VI=OI("toStringTag"),Cp={};Cp[VI]="z";Dp.exports=String(Cp)==="[object z]"});var pi=m((BM,Bp)=>{"use strict";var _I=rs(),NI=Y(),is=dr(),FI=ie(),qI=FI("toStringTag"),UI=Object,HI=is(function(){return arguments}())==="Arguments",jI=function(a,e){try{return a[e]}catch(t){}};Bp.exports=_I?is:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=jI(e=UI(a),qI))=="string"?t:HI?is(e):(r=is(e))==="Object"&&NI(e.callee)?"Arguments":r}});var Vp=m((OM,Op)=>{"use strict";var GI=rs(),WI=pi();Op.exports=GI?{}.toString:function(){return"[object "+WI(this)+"]"}});var hi=m((VM,Np)=>{"use strict";var YI=rs(),QI=Nt().f,zI=br(),KI=Ue(),JI=Vp(),XI=ie(),_p=XI("toStringTag");Np.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(KI(i,_p)||QI(i,_p,{configurable:!0,value:e}),r&&!YI&&zI(i,"toString",JI))}});var qp=m((_M,Fp)=>{"use strict";var ZI=To().IteratorPrototype,eE=mo(),tE=oi(),rE=hi(),iE=_t(),aE=function(){return this};Fp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=eE(ZI,{next:tE(+!r,t)}),rE(a,i,!1,!0),iE[i]=aE,a}});var Hp=m((NM,Up)=>{"use strict";var sE=le(),nE=tt();Up.exports=function(a,e,t){try{return sE(nE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Gp=m((FM,jp)=>{"use strict";var oE=ke();jp.exports=function(a){return oE(a)||a===null}});var Yp=m((qM,Wp)=>{"use strict";var uE=Gp(),cE=String,lE=TypeError;Wp.exports=function(a){if(uE(a))return a;throw new lE("Can't set "+cE(a)+" as a prototype")}});var Io=m((UM,Qp)=>{"use strict";var dE=Hp(),pE=ke(),hE=ei(),fE=Yp();Qp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=dE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return hE(i),fE(s),pE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var sh=m((HM,ah)=>{"use strict";var mE=$e(),bE=Te(),as=qe(),rh=Jd(),gE=Y(),SE=qp(),zp=go(),Kp=Io(),vE=hi(),yE=br(),Eo=vr(),TE=ie(),Jp=_t(),ih=To(),IE=rh.PROPER,EE=rh.CONFIGURABLE,Xp=ih.IteratorPrototype,ss=ih.BUGGY_SAFARI_ITERATORS,fi=TE("iterator"),Zp="keys",mi="values",eh="entries",th=function(){return this};ah.exports=function(a,e,t,r,i,s,n){SE(t,e,r);var o=function(v){if(v===i&&p)return p;if(!ss&&v&&v in c)return c[v];switch(v){case Zp:return function(){return new t(this,v)};case mi:return function(){return new t(this,v)};case eh:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[fi]||c["@@iterator"]||i&&c[i],p=!ss&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=zp(h.call(new a)),f!==Object.prototype&&f.next&&(!as&&zp(f)!==Xp&&(Kp?Kp(f,Xp):gE(f[fi])||Eo(f,fi,th)),vE(f,u,!0,!0),as&&(Jp[u]=th))),IE&&i===mi&&d&&d.name!==mi&&(!as&&EE?yE(c,"name",mi):(l=!0,p=function(){return bE(d,this)})),i)if(b={values:o(mi),keys:s?p:o(Zp),entries:o(eh)},n)for(g in b)(ss||l||!(g in c))&&Eo(c,g,b[g]);else mE({target:e,proto:!0,forced:ss||l},b);return(!as||n)&&c[fi]!==p&&Eo(c,fi,p,{name:i}),Jp[e]=p,b}});var oh=m((jM,nh)=>{"use strict";nh.exports=function(a,e){return{value:a,done:e}}});var Po=m((GM,ph)=>{"use strict";var xE=hr(),xo=Rn(),uh=_t(),lh=ro(),PE=Nt().f,AE=sh(),ns=oh(),wE=qe(),kE=Re(),dh="Array Iterator",RE=lh.set,$E=lh.getterFor(dh);ph.exports=AE(Array,"Array",function(a,e){RE(this,{type:dh,target:xE(a),index:0,kind:e})},function(){var a=$E(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ns(void 0,!0);switch(a.kind){case"keys":return ns(t,!1);case"values":return ns(e[t],!1)}return ns([t,e[t]],!1)},"values");var ch=uh.Arguments=uh.Array;xo("keys");xo("values");xo("entries");if(!wE&&kE&&ch.name!=="values")try{PE(ch,"name",{value:"values"})}catch(a){}});var fh=m((WM,hh)=>{"use strict";var LE=ie(),ME=_t(),CE=LE("iterator"),DE=Array.prototype;hh.exports=function(a){return a!==void 0&&(ME.Array===a||DE[CE]===a)}});var Ao=m((YM,bh)=>{"use strict";var BE=pi(),mh=ai(),OE=pr(),VE=_t(),_E=ie(),NE=_E("iterator");bh.exports=function(a){if(!OE(a))return mh(a,NE)||mh(a,"@@iterator")||VE[BE(a)]}});var Sh=m((QM,gh)=>{"use strict";var FE=Te(),qE=tt(),UE=ze(),HE=ii(),jE=Ao(),GE=TypeError;gh.exports=function(a,e){var t=arguments.length<2?jE(a):e;if(qE(t))return UE(FE(t,a));throw new GE(HE(a)+" is not iterable")}});var Th=m((zM,yh)=>{"use strict";var WE=Te(),vh=ze(),YE=ai();yh.exports=function(a,e,t){var r,i;vh(a);try{if(r=YE(a,"return"),!r){if(e==="throw")throw t;return t}r=WE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return vh(r),t}});var us=m((KM,Ph)=>{"use strict";var QE=li(),zE=Te(),KE=ze(),JE=ii(),XE=fh(),ZE=Za(),Ih=ri(),ex=Sh(),tx=Ao(),Eh=Th(),rx=TypeError,os=function(a,e){this.stopped=a,this.result=e},xh=os.prototype;Ph.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=QE(e,r),l,c,d,p,h,f,b,g=function(I){return l&&Eh(l,"normal",I),new os(!0,I)},v=function(I){return i?(KE(I),o?u(I[0],I[1],g):u(I[0],I[1])):o?u(I,g):u(I)};if(s)l=a.iterator;else if(n)l=a;else{if(c=tx(a),!c)throw new rx(JE(a)+" is not iterable");if(XE(c)){for(d=0,p=ZE(a);p>d;d++)if(h=v(a[d]),h&&Ih(xh,h))return h;return new os(!1)}l=ex(a,c)}for(f=s?a.next:l.next;!(b=zE(f,l)).done;){try{h=v(b.value)}catch(I){Eh(l,"throw",I)}if(typeof h=="object"&&h&&Ih(xh,h))return h}return new os(!1)}});var wh=m((JM,Ah)=>{"use strict";var ix=Re(),ax=Nt(),sx=oi();Ah.exports=function(a,e,t){ix?ax.f(a,e,sx(0,t)):a[e]=t}});var kh=m(()=>{"use strict";var nx=$e(),ox=us(),ux=wh();nx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return ox(e,function(r,i){ux(t,r,i)},{AS_ENTRIES:!0}),t}})});var $h=m((eC,Rh)=>{"use strict";Po();kh();var cx=Ga();Rh.exports=cx.Object.fromEntries});var Mh=m((tC,Lh)=>{"use strict";Lh.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var Dh=m(()=>{"use strict";Po();var lx=Mh(),dx=Q(),px=hi(),Ch=_t();for(cs in lx)px(dx[cs],cs),Ch[cs]=Ch.Array;var cs});var Oh=m((aC,Bh)=>{"use strict";var hx=$h();Dh();Bh.exports=hx});var wo=m((sC,Vh)=>{"use strict";var fx=Oh();Vh.exports=fx});var _h=m(()=>{"use strict"});var ko=m((uC,Nh)=>{"use strict";var bi=Q(),mx=fr(),bx=dr(),ls=function(a){return mx.slice(0,a.length)===a};Nh.exports=function(){return ls("Bun/")?"BUN":ls("Cloudflare-Workers")?"CLOUDFLARE":ls("Deno/")?"DENO":ls("Node.js/")?"NODE":bi.Bun&&typeof Bun.version=="string"?"BUN":bi.Deno&&typeof Deno.version=="object"?"DENO":bx(bi.process)==="process"?"NODE":bi.window&&bi.document?"BROWSER":"REST"}()});var ds=m((cC,Fh)=>{"use strict";var gx=ko();Fh.exports=gx==="NODE"});var Uh=m((lC,qh)=>{"use strict";var Sx=Nt();qh.exports=function(a,e,t){return Sx.f(a,e,t)}});var Gh=m((dC,jh)=>{"use strict";var vx=et(),yx=Uh(),Tx=ie(),Ix=Re(),Hh=Tx("species");jh.exports=function(a){var e=vx(a);Ix&&e&&!e[Hh]&&yx(e,Hh,{configurable:!0,get:function(){return this}})}});var Yh=m((pC,Wh)=>{"use strict";var Ex=ri(),xx=TypeError;Wh.exports=function(a,e){if(Ex(e,a))return a;throw new xx("Incorrect invocation")}});var $o=m((hC,Qh)=>{"use strict";var Px=le(),Ax=Y(),Ro=si(),wx=Px(Function.toString);Ax(Ro.inspectSource)||(Ro.inspectSource=function(a){return wx(a)});Qh.exports=Ro.inspectSource});var ef=m((fC,Zh)=>{"use strict";var kx=le(),Rx=ye(),zh=Y(),$x=pi(),Lx=et(),Mx=$o(),Kh=function(){},Jh=Lx("Reflect","construct"),Lo=/^\s*(?:class|function)\b/,Cx=kx(Lo.exec),Dx=!Lo.test(Kh),gi=function(e){if(!zh(e))return!1;try{return Jh(Kh,[],e),!0}catch(t){return!1}},Xh=function(e){if(!zh(e))return!1;switch($x(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Dx||!!Cx(Lo,Mx(e))}catch(t){return!0}};Xh.sham=!0;Zh.exports=!Jh||Rx(function(){var a;return gi(gi.call)||!gi(Object)||!gi(function(){a=!0})||a})?Xh:gi});var rf=m((mC,tf)=>{"use strict";var Bx=ef(),Ox=ii(),Vx=TypeError;tf.exports=function(a){if(Bx(a))return a;throw new Vx(Ox(a)+" is not a constructor")}});var Mo=m((bC,sf)=>{"use strict";var af=ze(),_x=rf(),Nx=pr(),Fx=ie(),qx=Fx("species");sf.exports=function(a,e){var t=af(a).constructor,r;return t===void 0||Nx(r=af(t)[qx])?e:_x(r)}});var of=m((gC,nf)=>{"use strict";var Ux=le();nf.exports=Ux([].slice)});var cf=m((SC,uf)=>{"use strict";var Hx=TypeError;uf.exports=function(a,e){if(a<e)throw new Hx("Not enough arguments");return a}});var Co=m((vC,lf)=>{"use strict";var jx=fr();lf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(jx)});var Uo=m((yC,vf)=>{"use strict";var Ie=Q(),Gx=io(),Wx=li(),df=Y(),Yx=Ue(),Sf=ye(),pf=lo(),Qx=of(),hf=Ha(),zx=cf(),Kx=Co(),Jx=ds(),No=Ie.setImmediate,Fo=Ie.clearImmediate,Xx=Ie.process,Do=Ie.Dispatch,Zx=Ie.Function,ff=Ie.MessageChannel,eP=Ie.String,Bo=0,Si={},mf="onreadystatechange",vi,qt,Oo,Vo;Sf(function(){vi=Ie.location});var qo=function(a){if(Yx(Si,a)){var e=Si[a];delete Si[a],e()}},_o=function(a){return function(){qo(a)}},bf=function(a){qo(a.data)},gf=function(a){Ie.postMessage(eP(a),vi.protocol+"//"+vi.host)};(!No||!Fo)&&(No=function(e){zx(arguments.length,1);var t=df(e)?e:Zx(e),r=Qx(arguments,1);return Si[++Bo]=function(){Gx(t,void 0,r)},qt(Bo),Bo},Fo=function(e){delete Si[e]},Jx?qt=function(a){Xx.nextTick(_o(a))}:Do&&Do.now?qt=function(a){Do.now(_o(a))}:ff&&!Kx?(Oo=new ff,Vo=Oo.port2,Oo.port1.onmessage=bf,qt=Wx(Vo.postMessage,Vo)):Ie.addEventListener&&df(Ie.postMessage)&&!Ie.importScripts&&vi&&vi.protocol!=="file:"&&!Sf(gf)?(qt=gf,Ie.addEventListener("message",bf,!1)):mf in hf("script")?qt=function(a){pf.appendChild(hf("script"))[mf]=function(){pf.removeChild(this),qo(a)}}:qt=function(a){setTimeout(_o(a),0)});vf.exports={set:No,clear:Fo}});var If=m((TC,Tf)=>{"use strict";var yf=Q(),tP=Re(),rP=Object.getOwnPropertyDescriptor;Tf.exports=function(a){if(!tP)return yf[a];var e=rP(yf,a);return e&&e.value}});var Ho=m((IC,xf)=>{"use strict";var Ef=function(){this.head=null,this.tail=null};Ef.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}}};xf.exports=Ef});var Af=m((EC,Pf)=>{"use strict";var iP=fr();Pf.exports=/ipad|iphone|ipod/i.test(iP)&&typeof Pebble!="undefined"});var kf=m((xC,wf)=>{"use strict";var aP=fr();wf.exports=/web0s(?!.*chrome)/i.test(aP)});var Bf=m((PC,Df)=>{"use strict";var Tr=Q(),sP=If(),Rf=li(),jo=Uo().set,nP=Ho(),oP=Co(),uP=Af(),cP=kf(),Go=ds(),$f=Tr.MutationObserver||Tr.WebKitMutationObserver,Lf=Tr.document,Mf=Tr.process,ps=Tr.Promise,Qo=sP("queueMicrotask"),yr,Wo,Yo,hs,Cf;Qo||(yi=new nP,Ti=function(){var a,e;for(Go&&(a=Mf.domain)&&a.exit();e=yi.get();)try{e()}catch(t){throw yi.head&&yr(),t}a&&a.enter()},!oP&&!Go&&!cP&&$f&&Lf?(Wo=!0,Yo=Lf.createTextNode(""),new $f(Ti).observe(Yo,{characterData:!0}),yr=function(){Yo.data=Wo=!Wo}):!uP&&ps&&ps.resolve?(hs=ps.resolve(void 0),hs.constructor=ps,Cf=Rf(hs.then,hs),yr=function(){Cf(Ti)}):Go?yr=function(){Mf.nextTick(Ti)}:(jo=Rf(jo,Tr),yr=function(){jo(Ti)}),Qo=function(a){yi.head||yr(),yi.add(a)});var yi,Ti;Df.exports=Qo});var Vf=m((AC,Of)=>{"use strict";Of.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var fs=m((wC,_f)=>{"use strict";_f.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ut=m((kC,Nf)=>{"use strict";var lP=Q();Nf.exports=lP.Promise});var Ir=m((RC,Hf)=>{"use strict";var dP=Q(),Ii=Ut(),pP=Y(),hP=so(),fP=$o(),mP=ie(),Ff=ko(),bP=qe(),zo=_n(),qf=Ii&&Ii.prototype,gP=mP("species"),Ko=!1,Uf=pP(dP.PromiseRejectionEvent),SP=hP("Promise",function(){var a=fP(Ii),e=a!==String(Ii);if(!e&&zo===66||bP&&!(qf.catch&&qf.finally))return!0;if(!zo||zo<51||!/native code/.test(a)){var t=new Ii(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[gP]=r,Ko=t.then(function(){})instanceof r,!Ko)return!0}return!e&&(Ff==="BROWSER"||Ff==="DENO")&&!Uf});Hf.exports={CONSTRUCTOR:SP,REJECTION_EVENT:Uf,SUBCLASSING:Ko}});var Er=m(($C,Gf)=>{"use strict";var jf=tt(),vP=TypeError,yP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new vP("Bad Promise constructor");e=r,t=i}),this.resolve=jf(e),this.reject=jf(t)};Gf.exports.f=function(a){return new yP(a)}});var lm=m(()=>{"use strict";var TP=$e(),IP=qe(),Ss=ds(),Tt=Q(),wr=Te(),Wf=vr(),Yf=Io(),EP=hi(),xP=Gh(),PP=tt(),gs=Y(),AP=ke(),wP=Yh(),kP=Mo(),Xf=Uo().set,tu=Bf(),RP=Vf(),$P=fs(),LP=Ho(),Zf=ro(),vs=Ut(),ru=Ir(),em=Er(),ys="Promise",tm=ru.CONSTRUCTOR,MP=ru.REJECTION_EVENT,CP=ru.SUBCLASSING,Jo=Zf.getterFor(ys),DP=Zf.set,xr=vs&&vs.prototype,Ht=vs,ms=xr,rm=Tt.TypeError,Xo=Tt.document,iu=Tt.process,Zo=em.f,BP=Zo,OP=!!(Xo&&Xo.createEvent&&Tt.dispatchEvent),im="unhandledrejection",VP="rejectionhandled",Qf=0,am=1,_P=2,au=1,sm=2,bs,zf,NP,Kf,nm=function(a){var e;return AP(a)&&gs(e=a.then)?e:!1},om=function(a,e){var t=e.value,r=e.state===am,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===sm&&qP(e),e.rejection=au),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new rm("Promise-chain cycle")):(l=nm(u))?wr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},um=function(a,e){a.notified||(a.notified=!0,tu(function(){for(var t=a.reactions,r;r=t.get();)om(r,a);a.notified=!1,e&&!a.rejection&&FP(a)}))},cm=function(a,e,t){var r,i;OP?(r=Xo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Tt.dispatchEvent(r)):r={promise:e,reason:t},!MP&&(i=Tt["on"+a])?i(r):a===im&&RP("Unhandled promise rejection",t)},FP=function(a){wr(Xf,Tt,function(){var e=a.facade,t=a.value,r=Jf(a),i;if(r&&(i=$P(function(){Ss?iu.emit("unhandledRejection",t,e):cm(im,e,t)}),a.rejection=Ss||Jf(a)?sm:au,i.error))throw i.value})},Jf=function(a){return a.rejection!==au&&!a.parent},qP=function(a){wr(Xf,Tt,function(){var e=a.facade;Ss?iu.emit("rejectionHandled",e):cm(VP,e,a.value)})},Pr=function(a,e,t){return function(r){a(e,r,t)}},Ar=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=_P,um(a,!0))},eu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new rm("Promise can't be resolved itself");var r=nm(e);r?tu(function(){var i={done:!1};try{wr(r,e,Pr(eu,i,a),Pr(Ar,i,a))}catch(s){Ar(i,s,a)}}):(a.value=e,a.state=am,um(a,!1))}catch(i){Ar({done:!1},i,a)}}};if(tm&&(Ht=function(e){wP(this,ms),PP(e),wr(bs,this);var t=Jo(this);try{e(Pr(eu,t),Pr(Ar,t))}catch(r){Ar(t,r)}},ms=Ht.prototype,bs=function(e){DP(this,{type:ys,done:!1,notified:!1,parent:!1,reactions:new LP,rejection:!1,state:Qf,value:void 0})},bs.prototype=Wf(ms,"then",function(e,t){var r=Jo(this),i=Zo(kP(this,Ht));return r.parent=!0,i.ok=gs(e)?e:!0,i.fail=gs(t)&&t,i.domain=Ss?iu.domain:void 0,r.state===Qf?r.reactions.add(i):tu(function(){om(i,r)}),i.promise}),zf=function(){var a=new bs,e=Jo(a);this.promise=a,this.resolve=Pr(eu,e),this.reject=Pr(Ar,e)},em.f=Zo=function(a){return a===Ht||a===NP?new zf(a):BP(a)},!IP&&gs(vs)&&xr!==Object.prototype)){Kf=xr.then,CP||Wf(xr,"then",function(e,t){var r=this;return new Ht(function(i,s){wr(Kf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete xr.constructor}catch(a){}Yf&&Yf(xr,ms)}TP({global:!0,constructor:!0,wrap:!0,forced:tm},{Promise:Ht});EP(Ht,ys,!1,!0);xP(ys)});var mm=m((CC,fm)=>{"use strict";var UP=ie(),pm=UP("iterator"),hm=!1;try{dm=0,su={next:function(){return{done:!!dm++}},return:function(){hm=!0}},su[pm]=function(){return this},Array.from(su,function(){throw 2})}catch(a){}var dm,su;fm.exports=function(a,e){try{if(!e&&!hm)return!1}catch(i){return!1}var t=!1;try{var r={};r[pm]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var nu=m((DC,bm)=>{"use strict";var HP=Ut(),jP=mm(),GP=Ir().CONSTRUCTOR;bm.exports=GP||!jP(function(a){HP.all(a).then(void 0,function(){})})});var gm=m(()=>{"use strict";var WP=$e(),YP=Te(),QP=tt(),zP=Er(),KP=fs(),JP=us(),XP=nu();WP({target:"Promise",stat:!0,forced:XP},{all:function(e){var t=this,r=zP.f(t),i=r.resolve,s=r.reject,n=KP(function(){var o=QP(t.resolve),u=[],l=0,c=1;JP(e,function(d){var p=l++,h=!1;c++,YP(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 vm=m(()=>{"use strict";var ZP=$e(),eA=qe(),tA=Ir().CONSTRUCTOR,uu=Ut(),rA=et(),iA=Y(),aA=vr(),Sm=uu&&uu.prototype;ZP({target:"Promise",proto:!0,forced:tA,real:!0},{catch:function(a){return this.then(void 0,a)}});!eA&&iA(uu)&&(ou=rA("Promise").prototype.catch,Sm.catch!==ou&&aA(Sm,"catch",ou,{unsafe:!0}));var ou});var ym=m(()=>{"use strict";var sA=$e(),nA=Te(),oA=tt(),uA=Er(),cA=fs(),lA=us(),dA=nu();sA({target:"Promise",stat:!0,forced:dA},{race:function(e){var t=this,r=uA.f(t),i=r.reject,s=cA(function(){var n=oA(t.resolve);lA(e,function(o){nA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Tm=m(()=>{"use strict";var pA=$e(),hA=Er(),fA=Ir().CONSTRUCTOR;pA({target:"Promise",stat:!0,forced:fA},{reject:function(e){var t=hA.f(this),r=t.reject;return r(e),t.promise}})});var cu=m((HC,Im)=>{"use strict";var mA=ze(),bA=ke(),gA=Er();Im.exports=function(a,e){if(mA(a),bA(e)&&e.constructor===a)return e;var t=gA.f(a),r=t.resolve;return r(e),t.promise}});var Pm=m(()=>{"use strict";var SA=$e(),vA=et(),Em=qe(),yA=Ut(),xm=Ir().CONSTRUCTOR,TA=cu(),IA=vA("Promise"),EA=Em&&!xm;SA({target:"Promise",stat:!0,forced:Em||xm},{resolve:function(e){return TA(EA&&this===IA?yA:this,e)}})});var Am=m(()=>{"use strict";lm();gm();vm();ym();Tm();Pm()});var $m=m(()=>{"use strict";var xA=$e(),PA=qe(),Ts=Ut(),AA=ye(),km=et(),Rm=Y(),wA=Mo(),wm=cu(),kA=vr(),du=Ts&&Ts.prototype,RA=!!Ts&&AA(function(){du.finally.call({then:function(){}},function(){})});xA({target:"Promise",proto:!0,real:!0,forced:RA},{finally:function(a){var e=wA(this,km("Promise")),t=Rm(a);return this.then(t?function(r){return wm(e,a()).then(function(){return r})}:a,t?function(r){return wm(e,a()).then(function(){throw r})}:a)}});!PA&&Rm(Ts)&&(lu=km("Promise").prototype.finally,du.finally!==lu&&kA(du,"finally",lu,{unsafe:!0}));var lu});var Is=m((KC,Lm)=>{"use strict";var $A=et();Lm.exports=$A});var Cm=m((JC,Mm)=>{"use strict";_h();Am();$m();var LA=Is();Mm.exports=LA("Promise","finally")});var Bm=m((XC,Dm)=>{"use strict";var MA=Cm();Dm.exports=MA});var Es=m((ZC,Om)=>{"use strict";var CA=Bm();Om.exports=CA});var ob=m(()=>{"use strict";var uw=$e(),cw=ni(),lw=Za(),dw=Xa(),pw=Rn();uw({target:"Array",proto:!0},{at:function(e){var t=cw(this),r=lw(t),i=dw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});pw("at")});var cb=m((u0,ub)=>{"use strict";ob();var hw=Is();ub.exports=hw("Array","at")});var db=m((c0,lb)=>{"use strict";var fw=cb();lb.exports=fw});var Ai=m((l0,pb)=>{"use strict";var mw=db();pb.exports=mw});var gg=m(()=>{"use strict"});var Sg=m(()=>{"use strict"});var yg=m((l_,vg)=>{"use strict";var Tk=ke(),Ik=dr(),Ek=ie(),xk=Ek("match");vg.exports=function(a){var e;return Tk(a)&&((e=a[xk])!==void 0?!!e:Ik(a)==="RegExp")}});var Ig=m((d_,Tg)=>{"use strict";var Pk=pi(),Ak=String;Tg.exports=function(a){if(Pk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Ak(a)}});var xg=m((p_,Eg)=>{"use strict";var wk=ze();Eg.exports=function(){var a=wk(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var wg=m((h_,Ag)=>{"use strict";var kk=Te(),Rk=Ue(),$k=ri(),Lk=xg(),Pg=RegExp.prototype;Ag.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Pg)&&!Rk(a,"flags")&&$k(Pg,a)?kk(Lk,a):e}});var Rg=m((f_,kg)=>{"use strict";var qu=le(),Mk=ni(),Ck=Math.floor,Nu=qu("".charAt),Dk=qu("".replace),Fu=qu("".slice),Bk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Ok=/\$([$&'`]|\d{1,2})/g;kg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=Ok;return i!==void 0&&(i=Mk(i),u=Bk),Dk(s,u,function(l,c){var d;switch(Nu(c,0)){case"$":return"$";case"&":return a;case"`":return Fu(e,0,t);case"'":return Fu(e,n);case"<":d=i[Fu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=Ck(p/10);return h===0?l:h<=o?r[h-1]===void 0?Nu(c,1):r[h-1]+Nu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var Mg=m(()=>{"use strict";var Vk=$e(),_k=Te(),Hu=le(),$g=ei(),Nk=Y(),Fk=pr(),qk=yg(),_r=Ig(),Uk=ai(),Hk=wg(),jk=Rg(),Gk=ie(),Wk=qe(),Yk=Gk("replace"),Qk=TypeError,Uu=Hu("".indexOf),zk=Hu("".replace),Lg=Hu("".slice),Kk=Math.max;Vk({target:"String",proto:!0},{replaceAll:function(e,t){var r=$g(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!Fk(e)){if(i=qk(e),i&&(s=_r($g(Hk(e))),!~Uu(s,"g")))throw new Qk("`.replaceAll` does not allow non-global regexes");if(n=Uk(e,Yk),n)return _k(n,e,r,t);if(Wk&&i)return zk(_r(r),e,t)}for(o=_r(r),u=_r(e),l=Nk(t),l||(t=_r(t)),c=u.length,d=Kk(1,c),p=Uu(o,u);p!==-1;)h=l?_r(t(u,p,o)):jk(u,o,p,[],void 0,t),b+=Lg(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Uu(o,u,p+d);return f<o.length&&(b+=Lg(o,f)),b}})});var Dg=m((g_,Cg)=>{"use strict";gg();Sg();Mg();var Jk=Is();Cg.exports=Jk("String","replaceAll")});var Og=m((S_,Bg)=>{"use strict";var Xk=Dg();Bg.exports=Xk});var _g=m((v_,Vg)=>{"use strict";var Zk=Og();Vg.exports=Zk});var tl="2.0.113-dev.95abd0e7.0";var ce=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ce||{}),yt=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(yt||{});var Fa=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Fa||{}),En=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(En||{});var xn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(xn||{});import{assertNever as ol,assertNonNullable as vv,isNonNullable as qa,ValueSubject as Pn,Subject as yv,Subscription as Tv,merge as Iv,observableFrom as Ev,fromEvent as il,map as al,tap as sl,filterChanged as xv,isNullable as An,ErrorCategory as nl}from"@vkontakte/videoplayer-shared";var rl=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 Ua=class{constructor(e){this.connection$=new Pn(void 0);this.castState$=new Pn("NOT_AVAILABLE");this.errorEvent$=new yv;this.realCastState$=new Pn("NOT_AVAILABLE");this.subscription=new Tv;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=qa((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||rl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:nl.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(){qa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();An(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();An(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(il(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 ol(i.sessionState)}})).add(Iv(il(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(sl(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),al(i=>i.castState)),Ev([r.getCastState()])).pipe(xv(),al(Pv),sl(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=qa(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();vv(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(An(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"?qa(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:nl.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Pv=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return ol(a)}};var BS=Qe(wo(),1);var Wm=Qe(Es(),1);import{assertNever as Vm}from"@vkontakte/videoplayer-shared";var ee=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Vm(t)}return a},pu=(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:Vm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as DA,Subject as xs,merge as _m}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new xs;this.transitionEnded$=new xs;this.transitionUpdated$=new xs;this.forceChanged$=new xs;this.stateChangeStarted$=_m(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=_m(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||DA(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as BA}from"@vkontakte/videoplayer-shared";var Nm=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return BA(a)}};import{assertNever as kr,assertNonNullable as jt,debounce as Fm,ErrorCategory as qm,fromEvent as Gt,isNonNullable as Um,map as Hm,merge as jm,observableFrom as OA,Subject as VA,Subscription as hu,timeout as _A,getHighestQuality as NA}from"@vkontakte/videoplayer-shared";var FA=5,qA=5,UA=500,Gm=7e3,Ei=class{constructor(e){this.subscription=new hu;this.loadMediaTimeoutSubscription=new hu;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:kr(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:kr(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:kr(e)}break}default:kr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Nm(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 hu;this.subscription.add(e),this.subscription.add(jm(this.videoState.stateChangeStarted$.pipe(Hm(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Hm(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new VA;e.add(i.pipe(Fm(UA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>FA)&&i.next(o),s=o})),e.add(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<qA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:kr(n)}}),t(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=jm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,OA(["init"])).pipe(Fm(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&E(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];jt(c);let d=NA(Object.keys(c));jt(d);let p=c[d];jt(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];jt(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];jt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];jt(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];jt(c),r=ee(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:qm.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return kr(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 Um(o)&&(n.metadata.title=o),Um(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(_A(Gm).subscribe(()=>s(`timeout(${Gm})`)))});(0,Wm.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:qm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Qm}from"@vkontakte/videoplayer-shared";import{clearVideoElement as HA}from"@vkontakte/videoplayer-shared";var Ym=a=>{try{a.pause(),a.playbackRate=0,HA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as jA,Subscription as GA}from"@vkontakte/videoplayer-shared";var fu=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)}},mu=window.WeakMap?new WeakMap:new fu,bu=window.WeakMap?new WeakMap:new Map,WA=(a,e=20)=>{let t=0;return jA(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},de=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Qm(t):(t=document.createElement("video"),a.appendChild(t)),mu.set(t,r);let i=new GA;return i.add(WA(t,e)),bu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},pe=a=>{let e=bu.get(a);e==null||e.unsubscribe(),bu.delete(a);let t=mu.get(a);mu.delete(a),t?Qm(a):Ym(a)};import{assertNonNullable as xi,isNonNullable as Je,isNullable as zA,fromEvent as Rr,merge as zm,observableFrom as Km,filterChanged as Jm,map as Pi,Subject as Xm,Subscription as KA,ValueSubject as JA,ErrorCategory as XA}from"@vkontakte/videoplayer-shared";import{isNonNullable as gu,isNullable as YA,Subscription as QA}from"@vkontakte/videoplayer-shared";var Ps=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=YA(i),l=new QA;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},Ke=(a,e,t)=>Ps(e,()=>a.loop,r=>{gu(r)&&(a.loop=r)},{onError:t}),he=(a,e,t,r)=>Ps(e,()=>({muted:a.muted,volume:a.volume}),i=>{gu(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Le=(a,e,t,r)=>Ps(e,()=>a.playbackRate,i=>{gu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),It=Ps;var ZA=a=>["__",a.language,a.label].join("|"),ew=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Su=class a{constructor(){this.available$=new Xm;this.current$=new JA(void 0);this.error$=new Xm;this.subscription=new KA;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:XA.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(It(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(Pi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(It(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(Pi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(It(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(It(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){xi(this.video);let{textTracks:e}=this.video;this.subscription.add(Rr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(zm(Rr(e,"addtrack"),Rr(e,"removetrack"),Km(["init"])).pipe(Pi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Jm((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(zm(Rr(e,"change"),Km(["init"])).pipe(Pi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Pi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Jm()).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(Rr(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(Rr(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){xi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,i=e.id?e.id:ZA(e),s=this.externalTracks.has(i),n=i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(i))==null?void 0:o.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(i))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){xi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(zA(e)||!ew(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){xi(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){xi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Me=Su;var at=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 Zm=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},vu=a=>{let e=Zm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},eb=a=>{let e=Zm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ce,map as Et,merge as rb,filterChanged as rw,isNonNullable as ib,Subject as iw,filter as ab,mapTo as sb,combine as aw,once as sw,ErrorCategory as nw,ValueSubject as nb,clientChecker as ow}from"@vkontakte/videoplayer-shared";var tw=3,tb=(a,e,t=tw)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var fe=a=>{let e=S=>Ce(a,S).pipe(sb(void 0)),r=rb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>Ce(a,S))).pipe(Et(S=>S.type==="ended"?a.readyState<2:a.readyState<3),rw()),i=rb(Ce(a,"progress"),Ce(a,"timeupdate")).pipe(Et(()=>tb(a.buffered,a.currentTime))),s=ow.isSafari?aw({play:e("play").pipe(sw()),playing:e("playing")}).pipe(sb(void 0)):e("playing"),n=Ce(a,"volumechange").pipe(Et(()=>({muted:a.muted,volume:a.volume}))),o=Ce(a,"ratechange").pipe(Et(()=>a.playbackRate)),u=Ce(a,"error").pipe(ab(()=>!!(a.error||a.played.length)),Et(()=>{var y;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:nw.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(y=a.error)!=null?y:void 0}})),l=Ce(a,"timeupdate").pipe(Et(()=>a.currentTime)),c=new iw,d=.3,p;l.subscribe(S=>{a.loop&&ib(p)&&ib(S)&&p>=a.duration-d&&S<=d&&c.next(p),p=S});let h=e("pause").pipe(ab(()=>!a.error&&p!==a.duration)),f=Ce(a,"enterpictureinpicture"),b=Ce(a,"leavepictureinpicture"),g=new nb(eb(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new nb(vu(a));return Ce(a,"fullscreenchange").pipe(Et(()=>vu(a))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ce(a,"durationchange").pipe(Et(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v}};import{VideoQuality as xt}from"@vkontakte/videoplayer-shared";var Pt=a=>{switch(a){case"mobile":return xt.Q_144P;case"lowest":return xt.Q_240P;case"low":return xt.Q_360P;case"sd":case"medium":return xt.Q_480P;case"hd":case"high":return xt.Q_720P;case"fullhd":case"full":return xt.Q_1080P;case"quadhd":case"quad":return xt.Q_1440P;case"ultrahd":case"ultra":return xt.Q_2160P}};var Wt=Qe(Ai(),1);import{isNonNullable as me,isNullable as Tu,now as yb,isHigher as Iu,isHigherOrEqual as bb,isInvariantQuality as gb,isLower as Eu,isLowerOrEqual as Sb,videoSizeToQuality as bw,assertNotEmptyArray as Tb,assertNonNullable as gw}from"@vkontakte/videoplayer-shared";var yu=!1,st={},hb=a=>{yu=a},fb=()=>{st={}},mb=a=>{a(st)},wi=(a,e)=>{var t;yu&&(st.meta=(t=st.meta)!=null?t:{},st.meta[a]=e)},ae=class{constructor(e){this.name=e}next(e){var r,i;if(!yu)return;st.series=(r=st.series)!=null?r:{};let t=(i=st.series[this.name])!=null?i:[];t.push([Date.now(),e]),st.series[this.name]=t}};var Sw=new ae("best_bitrate"),Ib=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var xu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),ki=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=yb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Eb='Assertion "ABR Tracks is empty array" failed',As=(a,e,t,r)=>{var u;let i=[...e].sort(xu(1)),s=[...t].sort(xu(1)),n=s.filter(l=>me(l.bitrate)&&me(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Wt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Wt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Wt.default)(n,-1):(0,Wt.default)(s,0)},vb=a=>"quality"in a,xb=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&yb()-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=vb(s)?"video":"audio",o=vb(s)?s.quality:s.bitrate;return e({message:`
|
|
6
|
+
var hv=Object.create;var ec=Object.defineProperty;var fv=Object.getOwnPropertyDescriptor;var mv=Object.getOwnPropertyNames;var bv=Object.getPrototypeOf,gv=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Sv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of mv(e))!gv.call(a,i)&&i!==t&&ec(a,i,{get:()=>e[i],enumerable:!(r=fv(e,i))||r.enumerable});return a};var Fe=(a,e,t)=>(t=a!=null?hv(bv(a)):{},Sv(e||!a||!a.__esModule?ec(t,"default",{value:a,enumerable:!0}):t,a));var ye=m((gL,uc)=>{"use strict";uc.exports=function(a){try{return!!a()}catch(e){return!0}}});var ti=m((SL,lc)=>{"use strict";var Av=ye();lc.exports=!Av(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var ce=m((vL,pc)=>{"use strict";var cc=ti(),dc=Function.prototype,kn=dc.call,wv=cc&&dc.bind.bind(kn,kn);pc.exports=cc?wv:function(a){return function(){return kn.apply(a,arguments)}}});var pr=m((yL,fc)=>{"use strict";var hc=ce(),kv=hc({}.toString),Rv=hc("".slice);fc.exports=function(a){return Rv(kv(a),8,-1)}});var bc=m((TL,mc)=>{"use strict";var $v=ce(),Lv=ye(),Mv=pr(),Rn=Object,Cv=$v("".split);mc.exports=Lv(function(){return!Rn("z").propertyIsEnumerable(0)})?function(a){return Mv(a)==="String"?Cv(a,""):Rn(a)}:Rn});var hr=m((IL,gc)=>{"use strict";gc.exports=function(a){return a==null}});var ri=m((EL,Sc)=>{"use strict";var Dv=hr(),Bv=TypeError;Sc.exports=function(a){if(Dv(a))throw new Bv("Can't call method on "+a);return a}});var fr=m((xL,vc)=>{"use strict";var Ov=bc(),Vv=ri();vc.exports=function(a){return Ov(Vv(a))}});var $n=m((PL,yc)=>{"use strict";yc.exports=function(){}});var Nt=m((AL,Tc)=>{"use strict";Tc.exports={}});var Q=m((Ln,Ic)=>{"use strict";var ii=function(a){return a&&a.Math===Math&&a};Ic.exports=ii(typeof globalThis=="object"&&globalThis)||ii(typeof window=="object"&&window)||ii(typeof self=="object"&&self)||ii(typeof global=="object"&&global)||ii(typeof Ln=="object"&&Ln)||function(){return this}()||Function("return this")()});var Y=m((wL,Ec)=>{"use strict";var Mn=typeof document=="object"&&document.all;Ec.exports=typeof Mn=="undefined"&&Mn!==void 0?function(a){return typeof a=="function"||a===Mn}:function(a){return typeof a=="function"}});var Ac=m((kL,Pc)=>{"use strict";var _v=Q(),Nv=Y(),xc=_v.WeakMap;Pc.exports=Nv(xc)&&/native code/.test(String(xc))});var Re=m((RL,wc)=>{"use strict";var Fv=Y();wc.exports=function(a){return typeof a=="object"?a!==null:Fv(a)}});var $e=m(($L,kc)=>{"use strict";var Uv=ye();kc.exports=!Uv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ja=m((LL,$c)=>{"use strict";var qv=Q(),Rc=Re(),Cn=qv.document,Hv=Rc(Cn)&&Rc(Cn.createElement);$c.exports=function(a){return Hv?Cn.createElement(a):{}}});var Dn=m((ML,Lc)=>{"use strict";var jv=$e(),Gv=ye(),Wv=ja();Lc.exports=!jv&&!Gv(function(){return Object.defineProperty(Wv("div"),"a",{get:function(){return 7}}).a!==7})});var Bn=m((CL,Mc)=>{"use strict";var Yv=$e(),Qv=ye();Mc.exports=Yv&&Qv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ze=m((DL,Cc)=>{"use strict";var zv=Re(),Kv=String,Jv=TypeError;Cc.exports=function(a){if(zv(a))return a;throw new Jv(Kv(a)+" is not an object")}});var Te=m((BL,Dc)=>{"use strict";var Xv=ti(),Ga=Function.prototype.call;Dc.exports=Xv?Ga.bind(Ga):function(){return Ga.apply(Ga,arguments)}});var Wa=m((OL,Bc)=>{"use strict";Bc.exports={}});var et=m((VL,Vc)=>{"use strict";var On=Wa(),Vn=Q(),Zv=Y(),Oc=function(a){return Zv(a)?a:void 0};Vc.exports=function(a,e){return arguments.length<2?Oc(On[a])||Oc(Vn[a]):On[a]&&On[a][e]||Vn[a]&&Vn[a][e]}});var ai=m((_L,_c)=>{"use strict";var ey=ce();_c.exports=ey({}.isPrototypeOf)});var mr=m((NL,Uc)=>{"use strict";var ty=Q(),Nc=ty.navigator,Fc=Nc&&Nc.userAgent;Uc.exports=Fc?String(Fc):""});var Nn=m((FL,Yc)=>{"use strict";var Wc=Q(),_n=mr(),qc=Wc.process,Hc=Wc.Deno,jc=qc&&qc.versions||Hc&&Hc.version,Gc=jc&&jc.v8,Ue,Ya;Gc&&(Ue=Gc.split("."),Ya=Ue[0]>0&&Ue[0]<4?1:+(Ue[0]+Ue[1]));!Ya&&_n&&(Ue=_n.match(/Edge\/(\d+)/),(!Ue||Ue[1]>=74)&&(Ue=_n.match(/Chrome\/(\d+)/),Ue&&(Ya=+Ue[1])));Yc.exports=Ya});var Fn=m((UL,zc)=>{"use strict";var Qc=Nn(),ry=ye(),iy=Q(),ay=iy.String;zc.exports=!!Object.getOwnPropertySymbols&&!ry(function(){var a=Symbol("symbol detection");return!ay(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Qc&&Qc<41})});var Un=m((qL,Kc)=>{"use strict";var sy=Fn();Kc.exports=sy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var qn=m((HL,Jc)=>{"use strict";var ny=et(),oy=Y(),uy=ai(),ly=Un(),cy=Object;Jc.exports=ly?function(a){return typeof a=="symbol"}:function(a){var e=ny("Symbol");return oy(e)&&uy(e.prototype,cy(a))}});var si=m((jL,Xc)=>{"use strict";var dy=String;Xc.exports=function(a){try{return dy(a)}catch(e){return"Object"}}});var tt=m((GL,Zc)=>{"use strict";var py=Y(),hy=si(),fy=TypeError;Zc.exports=function(a){if(py(a))return a;throw new fy(hy(a)+" is not a function")}});var ni=m((WL,ed)=>{"use strict";var my=tt(),by=hr();ed.exports=function(a,e){var t=a[e];return by(t)?void 0:my(t)}});var rd=m((YL,td)=>{"use strict";var Hn=Te(),jn=Y(),Gn=Re(),gy=TypeError;td.exports=function(a,e){var t,r;if(e==="string"&&jn(t=a.toString)&&!Gn(r=Hn(t,a))||jn(t=a.valueOf)&&!Gn(r=Hn(t,a))||e!=="string"&&jn(t=a.toString)&&!Gn(r=Hn(t,a)))return r;throw new gy("Can't convert object to primitive value")}});var qe=m((QL,id)=>{"use strict";id.exports=!0});var nd=m((zL,sd)=>{"use strict";var ad=Q(),Sy=Object.defineProperty;sd.exports=function(a,e){try{Sy(ad,a,{value:e,configurable:!0,writable:!0})}catch(t){ad[a]=e}return e}});var oi=m((KL,ld)=>{"use strict";var vy=qe(),yy=Q(),Ty=nd(),od="__core-js_shared__",ud=ld.exports=yy[od]||Ty(od,{});(ud.versions||(ud.versions=[])).push({version:"3.38.0",mode:vy?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Wn=m((JL,dd)=>{"use strict";var cd=oi();dd.exports=function(a,e){return cd[a]||(cd[a]=e||{})}});var ui=m((XL,pd)=>{"use strict";var Iy=ri(),Ey=Object;pd.exports=function(a){return Ey(Iy(a))}});var He=m((ZL,hd)=>{"use strict";var xy=ce(),Py=ui(),Ay=xy({}.hasOwnProperty);hd.exports=Object.hasOwn||function(e,t){return Ay(Py(e),t)}});var Yn=m((eM,fd)=>{"use strict";var wy=ce(),ky=0,Ry=Math.random(),$y=wy(1 .toString);fd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+$y(++ky+Ry,36)}});var ae=m((tM,bd)=>{"use strict";var Ly=Q(),My=Wn(),md=He(),Cy=Yn(),Dy=Fn(),By=Un(),br=Ly.Symbol,Qn=My("wks"),Oy=By?br.for||br:br&&br.withoutSetter||Cy;bd.exports=function(a){return md(Qn,a)||(Qn[a]=Dy&&md(br,a)?br[a]:Oy("Symbol."+a)),Qn[a]}});var yd=m((rM,vd)=>{"use strict";var Vy=Te(),gd=Re(),Sd=qn(),_y=ni(),Ny=rd(),Fy=ae(),Uy=TypeError,qy=Fy("toPrimitive");vd.exports=function(a,e){if(!gd(a)||Sd(a))return a;var t=_y(a,qy),r;if(t){if(e===void 0&&(e="default"),r=Vy(t,a,e),!gd(r)||Sd(r))return r;throw new Uy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ny(a,e)}});var zn=m((iM,Td)=>{"use strict";var Hy=yd(),jy=qn();Td.exports=function(a){var e=Hy(a,"string");return jy(e)?e:e+""}});var Ft=m(Ed=>{"use strict";var Gy=$e(),Wy=Dn(),Yy=Bn(),Qa=ze(),Id=zn(),Qy=TypeError,Kn=Object.defineProperty,zy=Object.getOwnPropertyDescriptor,Jn="enumerable",Xn="configurable",Zn="writable";Ed.f=Gy?Yy?function(e,t,r){if(Qa(e),t=Id(t),Qa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Zn in r&&!r[Zn]){var i=zy(e,t);i&&i[Zn]&&(e[t]=r.value,r={configurable:Xn in r?r[Xn]:i[Xn],enumerable:Jn in r?r[Jn]:i[Jn],writable:!1})}return Kn(e,t,r)}:Kn:function(e,t,r){if(Qa(e),t=Id(t),Qa(r),Wy)try{return Kn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Qy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var li=m((sM,xd)=>{"use strict";xd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var gr=m((nM,Pd)=>{"use strict";var Ky=$e(),Jy=Ft(),Xy=li();Pd.exports=Ky?function(a,e,t){return Jy.f(a,e,Xy(1,t))}:function(a,e,t){return a[e]=t,a}});var za=m((oM,wd)=>{"use strict";var Zy=Wn(),eT=Yn(),Ad=Zy("keys");wd.exports=function(a){return Ad[a]||(Ad[a]=eT(a))}});var Ka=m((uM,kd)=>{"use strict";kd.exports={}});var io=m((lM,Ld)=>{"use strict";var tT=Ac(),$d=Q(),rT=Re(),iT=gr(),eo=He(),to=oi(),aT=za(),sT=Ka(),Rd="Object already initialized",ro=$d.TypeError,nT=$d.WeakMap,Ja,ci,Xa,oT=function(a){return Xa(a)?ci(a):Ja(a,{})},uT=function(a){return function(e){var t;if(!rT(e)||(t=ci(e)).type!==a)throw new ro("Incompatible receiver, "+a+" required");return t}};tT||to.state?(je=to.state||(to.state=new nT),je.get=je.get,je.has=je.has,je.set=je.set,Ja=function(a,e){if(je.has(a))throw new ro(Rd);return e.facade=a,je.set(a,e),e},ci=function(a){return je.get(a)||{}},Xa=function(a){return je.has(a)}):(Ut=aT("state"),sT[Ut]=!0,Ja=function(a,e){if(eo(a,Ut))throw new ro(Rd);return e.facade=a,iT(a,Ut,e),e},ci=function(a){return eo(a,Ut)?a[Ut]:{}},Xa=function(a){return eo(a,Ut)});var je,Ut;Ld.exports={set:Ja,get:ci,has:Xa,enforce:oT,getterFor:uT}});var ao=m((cM,Bd)=>{"use strict";var lT=ti(),Dd=Function.prototype,Md=Dd.apply,Cd=Dd.call;Bd.exports=typeof Reflect=="object"&&Reflect.apply||(lT?Cd.bind(Md):function(){return Cd.apply(Md,arguments)})});var so=m((dM,Od)=>{"use strict";var cT=pr(),dT=ce();Od.exports=function(a){if(cT(a)==="Function")return dT(a)}});var Fd=m(Nd=>{"use strict";var Vd={}.propertyIsEnumerable,_d=Object.getOwnPropertyDescriptor,pT=_d&&!Vd.call({1:2},1);Nd.f=pT?function(e){var t=_d(this,e);return!!t&&t.enumerable}:Vd});var Hd=m(qd=>{"use strict";var hT=$e(),fT=Te(),mT=Fd(),bT=li(),gT=fr(),ST=zn(),vT=He(),yT=Dn(),Ud=Object.getOwnPropertyDescriptor;qd.f=hT?Ud:function(e,t){if(e=gT(e),t=ST(t),yT)try{return Ud(e,t)}catch(r){}if(vT(e,t))return bT(!fT(mT.f,e,t),e[t])}});var no=m((fM,jd)=>{"use strict";var TT=ye(),IT=Y(),ET=/#|\.prototype\./,di=function(a,e){var t=PT[xT(a)];return t===wT?!0:t===AT?!1:IT(e)?TT(e):!!e},xT=di.normalize=function(a){return String(a).replace(ET,".").toLowerCase()},PT=di.data={},AT=di.NATIVE="N",wT=di.POLYFILL="P";jd.exports=di});var pi=m((mM,Wd)=>{"use strict";var Gd=so(),kT=tt(),RT=ti(),$T=Gd(Gd.bind);Wd.exports=function(a,e){return kT(a),e===void 0?a:RT?$T(a,e):function(){return a.apply(e,arguments)}}});var Le=m((bM,Qd)=>{"use strict";var hi=Q(),LT=ao(),MT=so(),CT=Y(),DT=Hd().f,BT=no(),Sr=Wa(),OT=pi(),vr=gr(),Yd=He();oi();var VT=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return LT(a,this,arguments)};return e.prototype=a.prototype,e};Qd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?hi:i?hi[t]:hi[t]&&hi[t].prototype,o=r?Sr:Sr[t]||vr(Sr,t,{})[t],u=o.prototype,c,l,d,p,h,f,b,g,v;for(p in e)c=BT(r?p:t+(i?".":"#")+p,a.forced),l=!c&&n&&Yd(n,p),f=o[p],l&&(a.dontCallGetSet?(v=DT(n,p),b=v&&v.value):b=n[p]),h=l&&b?b:e[p],!(!c&&!s&&typeof f==typeof h)&&(a.bind&&l?g=OT(h,hi):a.wrap&&l?g=VT(h):s&&CT(h)?g=MT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&vr(g,"sham",!0),vr(o,p,g),s&&(d=t+"Prototype",Yd(Sr,d)||vr(Sr,d,{}),vr(Sr[d],p,h),a.real&&u&&(c||!u[p])&&vr(u,p,h)))}});var Jd=m((gM,Kd)=>{"use strict";var oo=$e(),_T=He(),zd=Function.prototype,NT=oo&&Object.getOwnPropertyDescriptor,uo=_T(zd,"name"),FT=uo&&function(){}.name==="something",UT=uo&&(!oo||oo&&NT(zd,"name").configurable);Kd.exports={EXISTS:uo,PROPER:FT,CONFIGURABLE:UT}});var Zd=m((SM,Xd)=>{"use strict";var qT=Math.ceil,HT=Math.floor;Xd.exports=Math.trunc||function(e){var t=+e;return(t>0?HT:qT)(t)}});var Za=m((vM,ep)=>{"use strict";var jT=Zd();ep.exports=function(a){var e=+a;return e!==e||e===0?0:jT(e)}});var rp=m((yM,tp)=>{"use strict";var GT=Za(),WT=Math.max,YT=Math.min;tp.exports=function(a,e){var t=GT(a);return t<0?WT(t+e,0):YT(t,e)}});var ap=m((TM,ip)=>{"use strict";var QT=Za(),zT=Math.min;ip.exports=function(a){var e=QT(a);return e>0?zT(e,9007199254740991):0}});var es=m((IM,sp)=>{"use strict";var KT=ap();sp.exports=function(a){return KT(a.length)}});var up=m((EM,op)=>{"use strict";var JT=fr(),XT=rp(),ZT=es(),np=function(a){return function(e,t,r){var i=JT(e),s=ZT(i);if(s===0)return!a&&-1;var n=XT(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};op.exports={includes:np(!0),indexOf:np(!1)}});var dp=m((xM,cp)=>{"use strict";var eI=ce(),lo=He(),tI=fr(),rI=up().indexOf,iI=Ka(),lp=eI([].push);cp.exports=function(a,e){var t=tI(a),r=0,i=[],s;for(s in t)!lo(iI,s)&&lo(t,s)&&lp(i,s);for(;e.length>r;)lo(t,s=e[r++])&&(~rI(i,s)||lp(i,s));return i}});var co=m((PM,pp)=>{"use strict";pp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var fp=m((AM,hp)=>{"use strict";var aI=dp(),sI=co();hp.exports=Object.keys||function(e){return aI(e,sI)}});var bp=m(mp=>{"use strict";var nI=$e(),oI=Bn(),uI=Ft(),lI=ze(),cI=fr(),dI=fp();mp.f=nI&&!oI?Object.defineProperties:function(e,t){lI(e);for(var r=cI(t),i=dI(t),s=i.length,n=0,o;s>n;)uI.f(e,o=i[n++],r[o]);return e}});var po=m((kM,gp)=>{"use strict";var pI=et();gp.exports=pI("document","documentElement")});var bo=m((RM,xp)=>{"use strict";var hI=ze(),fI=bp(),Sp=co(),mI=Ka(),bI=po(),gI=ja(),SI=za(),vp=">",yp="<",fo="prototype",mo="script",Ip=SI("IE_PROTO"),ho=function(){},Ep=function(a){return yp+mo+vp+a+yp+"/"+mo+vp},Tp=function(a){a.write(Ep("")),a.close();var e=a.parentWindow.Object;return a=null,e},vI=function(){var a=gI("iframe"),e="java"+mo+":",t;return a.style.display="none",bI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Ep("document.F=Object")),t.close(),t.F},ts,rs=function(){try{ts=new ActiveXObject("htmlfile")}catch(e){}rs=typeof document!="undefined"?document.domain&&ts?Tp(ts):vI():Tp(ts);for(var a=Sp.length;a--;)delete rs[fo][Sp[a]];return rs()};mI[Ip]=!0;xp.exports=Object.create||function(e,t){var r;return e!==null?(ho[fo]=hI(e),r=new ho,ho[fo]=null,r[Ip]=e):r=rs(),t===void 0?r:fI.f(r,t)}});var Ap=m(($M,Pp)=>{"use strict";var yI=ye();Pp.exports=!yI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var So=m((LM,kp)=>{"use strict";var TI=He(),II=Y(),EI=ui(),xI=za(),PI=Ap(),wp=xI("IE_PROTO"),go=Object,AI=go.prototype;kp.exports=PI?go.getPrototypeOf:function(a){var e=EI(a);if(TI(e,wp))return e[wp];var t=e.constructor;return II(t)&&e instanceof t?t.prototype:e instanceof go?AI:null}});var yr=m((MM,Rp)=>{"use strict";var wI=gr();Rp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:wI(a,e,t),a}});var Io=m((CM,Mp)=>{"use strict";var kI=ye(),RI=Y(),$I=Re(),LI=bo(),$p=So(),MI=yr(),CI=ae(),DI=qe(),To=CI("iterator"),Lp=!1,rt,vo,yo;[].keys&&(yo=[].keys(),"next"in yo?(vo=$p($p(yo)),vo!==Object.prototype&&(rt=vo)):Lp=!0);var BI=!$I(rt)||kI(function(){var a={};return rt[To].call(a)!==a});BI?rt={}:DI&&(rt=LI(rt));RI(rt[To])||MI(rt,To,function(){return this});Mp.exports={IteratorPrototype:rt,BUGGY_SAFARI_ITERATORS:Lp}});var is=m((DM,Dp)=>{"use strict";var OI=ae(),VI=OI("toStringTag"),Cp={};Cp[VI]="z";Dp.exports=String(Cp)==="[object z]"});var fi=m((BM,Bp)=>{"use strict";var _I=is(),NI=Y(),as=pr(),FI=ae(),UI=FI("toStringTag"),qI=Object,HI=as(function(){return arguments}())==="Arguments",jI=function(a,e){try{return a[e]}catch(t){}};Bp.exports=_I?as:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=jI(e=qI(a),UI))=="string"?t:HI?as(e):(r=as(e))==="Object"&&NI(e.callee)?"Arguments":r}});var Vp=m((OM,Op)=>{"use strict";var GI=is(),WI=fi();Op.exports=GI?{}.toString:function(){return"[object "+WI(this)+"]"}});var mi=m((VM,Np)=>{"use strict";var YI=is(),QI=Ft().f,zI=gr(),KI=He(),JI=Vp(),XI=ae(),_p=XI("toStringTag");Np.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(KI(i,_p)||QI(i,_p,{configurable:!0,value:e}),r&&!YI&&zI(i,"toString",JI))}});var Up=m((_M,Fp)=>{"use strict";var ZI=Io().IteratorPrototype,eE=bo(),tE=li(),rE=mi(),iE=Nt(),aE=function(){return this};Fp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=eE(ZI,{next:tE(+!r,t)}),rE(a,i,!1,!0),iE[i]=aE,a}});var Hp=m((NM,qp)=>{"use strict";var sE=ce(),nE=tt();qp.exports=function(a,e,t){try{return sE(nE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Gp=m((FM,jp)=>{"use strict";var oE=Re();jp.exports=function(a){return oE(a)||a===null}});var Yp=m((UM,Wp)=>{"use strict";var uE=Gp(),lE=String,cE=TypeError;Wp.exports=function(a){if(uE(a))return a;throw new cE("Can't set "+lE(a)+" as a prototype")}});var Eo=m((qM,Qp)=>{"use strict";var dE=Hp(),pE=Re(),hE=ri(),fE=Yp();Qp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=dE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return hE(i),fE(s),pE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var sh=m((HM,ah)=>{"use strict";var mE=Le(),bE=Te(),ss=qe(),rh=Jd(),gE=Y(),SE=Up(),zp=So(),Kp=Eo(),vE=mi(),yE=gr(),xo=yr(),TE=ae(),Jp=Nt(),ih=Io(),IE=rh.PROPER,EE=rh.CONFIGURABLE,Xp=ih.IteratorPrototype,ns=ih.BUGGY_SAFARI_ITERATORS,bi=TE("iterator"),Zp="keys",gi="values",eh="entries",th=function(){return this};ah.exports=function(a,e,t,r,i,s,n){SE(t,e,r);var o=function(v){if(v===i&&p)return p;if(!ns&&v&&v in l)return l[v];switch(v){case Zp:return function(){return new t(this,v)};case gi:return function(){return new t(this,v)};case eh:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[bi]||l["@@iterator"]||i&&l[i],p=!ns&&d||o(i),h=e==="Array"&&l.entries||d,f,b,g;if(h&&(f=zp(h.call(new a)),f!==Object.prototype&&f.next&&(!ss&&zp(f)!==Xp&&(Kp?Kp(f,Xp):gE(f[bi])||xo(f,bi,th)),vE(f,u,!0,!0),ss&&(Jp[u]=th))),IE&&i===gi&&d&&d.name!==gi&&(!ss&&EE?yE(l,"name",gi):(c=!0,p=function(){return bE(d,this)})),i)if(b={values:o(gi),keys:s?p:o(Zp),entries:o(eh)},n)for(g in b)(ns||c||!(g in l))&&xo(l,g,b[g]);else mE({target:e,proto:!0,forced:ns||c},b);return(!ss||n)&&l[bi]!==p&&xo(l,bi,p,{name:i}),Jp[e]=p,b}});var oh=m((jM,nh)=>{"use strict";nh.exports=function(a,e){return{value:a,done:e}}});var Ao=m((GM,ph)=>{"use strict";var xE=fr(),Po=$n(),uh=Nt(),ch=io(),PE=Ft().f,AE=sh(),os=oh(),wE=qe(),kE=$e(),dh="Array Iterator",RE=ch.set,$E=ch.getterFor(dh);ph.exports=AE(Array,"Array",function(a,e){RE(this,{type:dh,target:xE(a),index:0,kind:e})},function(){var a=$E(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,os(void 0,!0);switch(a.kind){case"keys":return os(t,!1);case"values":return os(e[t],!1)}return os([t,e[t]],!1)},"values");var lh=uh.Arguments=uh.Array;Po("keys");Po("values");Po("entries");if(!wE&&kE&&lh.name!=="values")try{PE(lh,"name",{value:"values"})}catch(a){}});var fh=m((WM,hh)=>{"use strict";var LE=ae(),ME=Nt(),CE=LE("iterator"),DE=Array.prototype;hh.exports=function(a){return a!==void 0&&(ME.Array===a||DE[CE]===a)}});var wo=m((YM,bh)=>{"use strict";var BE=fi(),mh=ni(),OE=hr(),VE=Nt(),_E=ae(),NE=_E("iterator");bh.exports=function(a){if(!OE(a))return mh(a,NE)||mh(a,"@@iterator")||VE[BE(a)]}});var Sh=m((QM,gh)=>{"use strict";var FE=Te(),UE=tt(),qE=ze(),HE=si(),jE=wo(),GE=TypeError;gh.exports=function(a,e){var t=arguments.length<2?jE(a):e;if(UE(t))return qE(FE(t,a));throw new GE(HE(a)+" is not iterable")}});var Th=m((zM,yh)=>{"use strict";var WE=Te(),vh=ze(),YE=ni();yh.exports=function(a,e,t){var r,i;vh(a);try{if(r=YE(a,"return"),!r){if(e==="throw")throw t;return t}r=WE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return vh(r),t}});var ls=m((KM,Ph)=>{"use strict";var QE=pi(),zE=Te(),KE=ze(),JE=si(),XE=fh(),ZE=es(),Ih=ai(),ex=Sh(),tx=wo(),Eh=Th(),rx=TypeError,us=function(a,e){this.stopped=a,this.result=e},xh=us.prototype;Ph.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=QE(e,r),c,l,d,p,h,f,b,g=function(I){return c&&Eh(c,"normal",I),new us(!0,I)},v=function(I){return i?(KE(I),o?u(I[0],I[1],g):u(I[0],I[1])):o?u(I,g):u(I)};if(s)c=a.iterator;else if(n)c=a;else{if(l=tx(a),!l)throw new rx(JE(a)+" is not iterable");if(XE(l)){for(d=0,p=ZE(a);p>d;d++)if(h=v(a[d]),h&&Ih(xh,h))return h;return new us(!1)}c=ex(a,l)}for(f=s?a.next:c.next;!(b=zE(f,c)).done;){try{h=v(b.value)}catch(I){Eh(c,"throw",I)}if(typeof h=="object"&&h&&Ih(xh,h))return h}return new us(!1)}});var wh=m((JM,Ah)=>{"use strict";var ix=$e(),ax=Ft(),sx=li();Ah.exports=function(a,e,t){ix?ax.f(a,e,sx(0,t)):a[e]=t}});var kh=m(()=>{"use strict";var nx=Le(),ox=ls(),ux=wh();nx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return ox(e,function(r,i){ux(t,r,i)},{AS_ENTRIES:!0}),t}})});var $h=m((eC,Rh)=>{"use strict";Ao();kh();var lx=Wa();Rh.exports=lx.Object.fromEntries});var Mh=m((tC,Lh)=>{"use strict";Lh.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var Dh=m(()=>{"use strict";Ao();var cx=Mh(),dx=Q(),px=mi(),Ch=Nt();for(cs in cx)px(dx[cs],cs),Ch[cs]=Ch.Array;var cs});var Oh=m((aC,Bh)=>{"use strict";var hx=$h();Dh();Bh.exports=hx});var ko=m((sC,Vh)=>{"use strict";var fx=Oh();Vh.exports=fx});var _h=m(()=>{"use strict"});var Ro=m((uC,Nh)=>{"use strict";var Si=Q(),mx=mr(),bx=pr(),ds=function(a){return mx.slice(0,a.length)===a};Nh.exports=function(){return ds("Bun/")?"BUN":ds("Cloudflare-Workers")?"CLOUDFLARE":ds("Deno/")?"DENO":ds("Node.js/")?"NODE":Si.Bun&&typeof Bun.version=="string"?"BUN":Si.Deno&&typeof Deno.version=="object"?"DENO":bx(Si.process)==="process"?"NODE":Si.window&&Si.document?"BROWSER":"REST"}()});var ps=m((lC,Fh)=>{"use strict";var gx=Ro();Fh.exports=gx==="NODE"});var qh=m((cC,Uh)=>{"use strict";var Sx=Ft();Uh.exports=function(a,e,t){return Sx.f(a,e,t)}});var Gh=m((dC,jh)=>{"use strict";var vx=et(),yx=qh(),Tx=ae(),Ix=$e(),Hh=Tx("species");jh.exports=function(a){var e=vx(a);Ix&&e&&!e[Hh]&&yx(e,Hh,{configurable:!0,get:function(){return this}})}});var Yh=m((pC,Wh)=>{"use strict";var Ex=ai(),xx=TypeError;Wh.exports=function(a,e){if(Ex(e,a))return a;throw new xx("Incorrect invocation")}});var Lo=m((hC,Qh)=>{"use strict";var Px=ce(),Ax=Y(),$o=oi(),wx=Px(Function.toString);Ax($o.inspectSource)||($o.inspectSource=function(a){return wx(a)});Qh.exports=$o.inspectSource});var ef=m((fC,Zh)=>{"use strict";var kx=ce(),Rx=ye(),zh=Y(),$x=fi(),Lx=et(),Mx=Lo(),Kh=function(){},Jh=Lx("Reflect","construct"),Mo=/^\s*(?:class|function)\b/,Cx=kx(Mo.exec),Dx=!Mo.test(Kh),vi=function(e){if(!zh(e))return!1;try{return Jh(Kh,[],e),!0}catch(t){return!1}},Xh=function(e){if(!zh(e))return!1;switch($x(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Dx||!!Cx(Mo,Mx(e))}catch(t){return!0}};Xh.sham=!0;Zh.exports=!Jh||Rx(function(){var a;return vi(vi.call)||!vi(Object)||!vi(function(){a=!0})||a})?Xh:vi});var rf=m((mC,tf)=>{"use strict";var Bx=ef(),Ox=si(),Vx=TypeError;tf.exports=function(a){if(Bx(a))return a;throw new Vx(Ox(a)+" is not a constructor")}});var Co=m((bC,sf)=>{"use strict";var af=ze(),_x=rf(),Nx=hr(),Fx=ae(),Ux=Fx("species");sf.exports=function(a,e){var t=af(a).constructor,r;return t===void 0||Nx(r=af(t)[Ux])?e:_x(r)}});var of=m((gC,nf)=>{"use strict";var qx=ce();nf.exports=qx([].slice)});var lf=m((SC,uf)=>{"use strict";var Hx=TypeError;uf.exports=function(a,e){if(a<e)throw new Hx("Not enough arguments");return a}});var Do=m((vC,cf)=>{"use strict";var jx=mr();cf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(jx)});var Ho=m((yC,vf)=>{"use strict";var Ie=Q(),Gx=ao(),Wx=pi(),df=Y(),Yx=He(),Sf=ye(),pf=po(),Qx=of(),hf=ja(),zx=lf(),Kx=Do(),Jx=ps(),Fo=Ie.setImmediate,Uo=Ie.clearImmediate,Xx=Ie.process,Bo=Ie.Dispatch,Zx=Ie.Function,ff=Ie.MessageChannel,eP=Ie.String,Oo=0,yi={},mf="onreadystatechange",Ti,qt,Vo,_o;Sf(function(){Ti=Ie.location});var qo=function(a){if(Yx(yi,a)){var e=yi[a];delete yi[a],e()}},No=function(a){return function(){qo(a)}},bf=function(a){qo(a.data)},gf=function(a){Ie.postMessage(eP(a),Ti.protocol+"//"+Ti.host)};(!Fo||!Uo)&&(Fo=function(e){zx(arguments.length,1);var t=df(e)?e:Zx(e),r=Qx(arguments,1);return yi[++Oo]=function(){Gx(t,void 0,r)},qt(Oo),Oo},Uo=function(e){delete yi[e]},Jx?qt=function(a){Xx.nextTick(No(a))}:Bo&&Bo.now?qt=function(a){Bo.now(No(a))}:ff&&!Kx?(Vo=new ff,_o=Vo.port2,Vo.port1.onmessage=bf,qt=Wx(_o.postMessage,_o)):Ie.addEventListener&&df(Ie.postMessage)&&!Ie.importScripts&&Ti&&Ti.protocol!=="file:"&&!Sf(gf)?(qt=gf,Ie.addEventListener("message",bf,!1)):mf in hf("script")?qt=function(a){pf.appendChild(hf("script"))[mf]=function(){pf.removeChild(this),qo(a)}}:qt=function(a){setTimeout(No(a),0)});vf.exports={set:Fo,clear:Uo}});var If=m((TC,Tf)=>{"use strict";var yf=Q(),tP=$e(),rP=Object.getOwnPropertyDescriptor;Tf.exports=function(a){if(!tP)return yf[a];var e=rP(yf,a);return e&&e.value}});var jo=m((IC,xf)=>{"use strict";var Ef=function(){this.head=null,this.tail=null};Ef.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}}};xf.exports=Ef});var Af=m((EC,Pf)=>{"use strict";var iP=mr();Pf.exports=/ipad|iphone|ipod/i.test(iP)&&typeof Pebble!="undefined"});var kf=m((xC,wf)=>{"use strict";var aP=mr();wf.exports=/web0s(?!.*chrome)/i.test(aP)});var Bf=m((PC,Df)=>{"use strict";var Ir=Q(),sP=If(),Rf=pi(),Go=Ho().set,nP=jo(),oP=Do(),uP=Af(),lP=kf(),Wo=ps(),$f=Ir.MutationObserver||Ir.WebKitMutationObserver,Lf=Ir.document,Mf=Ir.process,hs=Ir.Promise,zo=sP("queueMicrotask"),Tr,Yo,Qo,fs,Cf;zo||(Ii=new nP,Ei=function(){var a,e;for(Wo&&(a=Mf.domain)&&a.exit();e=Ii.get();)try{e()}catch(t){throw Ii.head&&Tr(),t}a&&a.enter()},!oP&&!Wo&&!lP&&$f&&Lf?(Yo=!0,Qo=Lf.createTextNode(""),new $f(Ei).observe(Qo,{characterData:!0}),Tr=function(){Qo.data=Yo=!Yo}):!uP&&hs&&hs.resolve?(fs=hs.resolve(void 0),fs.constructor=hs,Cf=Rf(fs.then,fs),Tr=function(){Cf(Ei)}):Wo?Tr=function(){Mf.nextTick(Ei)}:(Go=Rf(Go,Ir),Tr=function(){Go(Ei)}),zo=function(a){Ii.head||Tr(),Ii.add(a)});var Ii,Ei;Df.exports=zo});var Vf=m((AC,Of)=>{"use strict";Of.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var ms=m((wC,_f)=>{"use strict";_f.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ht=m((kC,Nf)=>{"use strict";var cP=Q();Nf.exports=cP.Promise});var Er=m((RC,Hf)=>{"use strict";var dP=Q(),xi=Ht(),pP=Y(),hP=no(),fP=Lo(),mP=ae(),Ff=Ro(),bP=qe(),Ko=Nn(),Uf=xi&&xi.prototype,gP=mP("species"),Jo=!1,qf=pP(dP.PromiseRejectionEvent),SP=hP("Promise",function(){var a=fP(xi),e=a!==String(xi);if(!e&&Ko===66||bP&&!(Uf.catch&&Uf.finally))return!0;if(!Ko||Ko<51||!/native code/.test(a)){var t=new xi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[gP]=r,Jo=t.then(function(){})instanceof r,!Jo)return!0}return!e&&(Ff==="BROWSER"||Ff==="DENO")&&!qf});Hf.exports={CONSTRUCTOR:SP,REJECTION_EVENT:qf,SUBCLASSING:Jo}});var xr=m(($C,Gf)=>{"use strict";var jf=tt(),vP=TypeError,yP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new vP("Bad Promise constructor");e=r,t=i}),this.resolve=jf(e),this.reject=jf(t)};Gf.exports.f=function(a){return new yP(a)}});var cm=m(()=>{"use strict";var TP=Le(),IP=qe(),vs=ps(),It=Q(),kr=Te(),Wf=yr(),Yf=Eo(),EP=mi(),xP=Gh(),PP=tt(),Ss=Y(),AP=Re(),wP=Yh(),kP=Co(),Xf=Ho().set,ru=Bf(),RP=Vf(),$P=ms(),LP=jo(),Zf=io(),ys=Ht(),iu=Er(),em=xr(),Ts="Promise",tm=iu.CONSTRUCTOR,MP=iu.REJECTION_EVENT,CP=iu.SUBCLASSING,Xo=Zf.getterFor(Ts),DP=Zf.set,Pr=ys&&ys.prototype,jt=ys,bs=Pr,rm=It.TypeError,Zo=It.document,au=It.process,eu=em.f,BP=eu,OP=!!(Zo&&Zo.createEvent&&It.dispatchEvent),im="unhandledrejection",VP="rejectionhandled",Qf=0,am=1,_P=2,su=1,sm=2,gs,zf,NP,Kf,nm=function(a){var e;return AP(a)&&Ss(e=a.then)?e:!1},om=function(a,e){var t=e.value,r=e.state===am,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{i?(r||(e.rejection===sm&&UP(e),e.rejection=su),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),l=!0)),u===a.promise?n(new rm("Promise-chain cycle")):(c=nm(u))?kr(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},um=function(a,e){a.notified||(a.notified=!0,ru(function(){for(var t=a.reactions,r;r=t.get();)om(r,a);a.notified=!1,e&&!a.rejection&&FP(a)}))},lm=function(a,e,t){var r,i;OP?(r=Zo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),It.dispatchEvent(r)):r={promise:e,reason:t},!MP&&(i=It["on"+a])?i(r):a===im&&RP("Unhandled promise rejection",t)},FP=function(a){kr(Xf,It,function(){var e=a.facade,t=a.value,r=Jf(a),i;if(r&&(i=$P(function(){vs?au.emit("unhandledRejection",t,e):lm(im,e,t)}),a.rejection=vs||Jf(a)?sm:su,i.error))throw i.value})},Jf=function(a){return a.rejection!==su&&!a.parent},UP=function(a){kr(Xf,It,function(){var e=a.facade;vs?au.emit("rejectionHandled",e):lm(VP,e,a.value)})},Ar=function(a,e,t){return function(r){a(e,r,t)}},wr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=_P,um(a,!0))},tu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new rm("Promise can't be resolved itself");var r=nm(e);r?ru(function(){var i={done:!1};try{kr(r,e,Ar(tu,i,a),Ar(wr,i,a))}catch(s){wr(i,s,a)}}):(a.value=e,a.state=am,um(a,!1))}catch(i){wr({done:!1},i,a)}}};if(tm&&(jt=function(e){wP(this,bs),PP(e),kr(gs,this);var t=Xo(this);try{e(Ar(tu,t),Ar(wr,t))}catch(r){wr(t,r)}},bs=jt.prototype,gs=function(e){DP(this,{type:Ts,done:!1,notified:!1,parent:!1,reactions:new LP,rejection:!1,state:Qf,value:void 0})},gs.prototype=Wf(bs,"then",function(e,t){var r=Xo(this),i=eu(kP(this,jt));return r.parent=!0,i.ok=Ss(e)?e:!0,i.fail=Ss(t)&&t,i.domain=vs?au.domain:void 0,r.state===Qf?r.reactions.add(i):ru(function(){om(i,r)}),i.promise}),zf=function(){var a=new gs,e=Xo(a);this.promise=a,this.resolve=Ar(tu,e),this.reject=Ar(wr,e)},em.f=eu=function(a){return a===jt||a===NP?new zf(a):BP(a)},!IP&&Ss(ys)&&Pr!==Object.prototype)){Kf=Pr.then,CP||Wf(Pr,"then",function(e,t){var r=this;return new jt(function(i,s){kr(Kf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Pr.constructor}catch(a){}Yf&&Yf(Pr,bs)}TP({global:!0,constructor:!0,wrap:!0,forced:tm},{Promise:jt});EP(jt,Ts,!1,!0);xP(Ts)});var mm=m((CC,fm)=>{"use strict";var qP=ae(),pm=qP("iterator"),hm=!1;try{dm=0,nu={next:function(){return{done:!!dm++}},return:function(){hm=!0}},nu[pm]=function(){return this},Array.from(nu,function(){throw 2})}catch(a){}var dm,nu;fm.exports=function(a,e){try{if(!e&&!hm)return!1}catch(i){return!1}var t=!1;try{var r={};r[pm]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var ou=m((DC,bm)=>{"use strict";var HP=Ht(),jP=mm(),GP=Er().CONSTRUCTOR;bm.exports=GP||!jP(function(a){HP.all(a).then(void 0,function(){})})});var gm=m(()=>{"use strict";var WP=Le(),YP=Te(),QP=tt(),zP=xr(),KP=ms(),JP=ls(),XP=ou();WP({target:"Promise",stat:!0,forced:XP},{all:function(e){var t=this,r=zP.f(t),i=r.resolve,s=r.reject,n=KP(function(){var o=QP(t.resolve),u=[],c=0,l=1;JP(e,function(d){var p=c++,h=!1;l++,YP(o,t,d).then(function(f){h||(h=!0,u[p]=f,--l||i(u))},s)}),--l||i(u)});return n.error&&s(n.value),r.promise}})});var vm=m(()=>{"use strict";var ZP=Le(),eA=qe(),tA=Er().CONSTRUCTOR,lu=Ht(),rA=et(),iA=Y(),aA=yr(),Sm=lu&&lu.prototype;ZP({target:"Promise",proto:!0,forced:tA,real:!0},{catch:function(a){return this.then(void 0,a)}});!eA&&iA(lu)&&(uu=rA("Promise").prototype.catch,Sm.catch!==uu&&aA(Sm,"catch",uu,{unsafe:!0}));var uu});var ym=m(()=>{"use strict";var sA=Le(),nA=Te(),oA=tt(),uA=xr(),lA=ms(),cA=ls(),dA=ou();sA({target:"Promise",stat:!0,forced:dA},{race:function(e){var t=this,r=uA.f(t),i=r.reject,s=lA(function(){var n=oA(t.resolve);cA(e,function(o){nA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Tm=m(()=>{"use strict";var pA=Le(),hA=xr(),fA=Er().CONSTRUCTOR;pA({target:"Promise",stat:!0,forced:fA},{reject:function(e){var t=hA.f(this),r=t.reject;return r(e),t.promise}})});var cu=m((HC,Im)=>{"use strict";var mA=ze(),bA=Re(),gA=xr();Im.exports=function(a,e){if(mA(a),bA(e)&&e.constructor===a)return e;var t=gA.f(a),r=t.resolve;return r(e),t.promise}});var Pm=m(()=>{"use strict";var SA=Le(),vA=et(),Em=qe(),yA=Ht(),xm=Er().CONSTRUCTOR,TA=cu(),IA=vA("Promise"),EA=Em&&!xm;SA({target:"Promise",stat:!0,forced:Em||xm},{resolve:function(e){return TA(EA&&this===IA?yA:this,e)}})});var Am=m(()=>{"use strict";cm();gm();vm();ym();Tm();Pm()});var $m=m(()=>{"use strict";var xA=Le(),PA=qe(),Is=Ht(),AA=ye(),km=et(),Rm=Y(),wA=Co(),wm=cu(),kA=yr(),pu=Is&&Is.prototype,RA=!!Is&&AA(function(){pu.finally.call({then:function(){}},function(){})});xA({target:"Promise",proto:!0,real:!0,forced:RA},{finally:function(a){var e=wA(this,km("Promise")),t=Rm(a);return this.then(t?function(r){return wm(e,a()).then(function(){return r})}:a,t?function(r){return wm(e,a()).then(function(){throw r})}:a)}});!PA&&Rm(Is)&&(du=km("Promise").prototype.finally,pu.finally!==du&&kA(pu,"finally",du,{unsafe:!0}));var du});var Es=m((KC,Lm)=>{"use strict";var $A=et();Lm.exports=$A});var Cm=m((JC,Mm)=>{"use strict";_h();Am();$m();var LA=Es();Mm.exports=LA("Promise","finally")});var Bm=m((XC,Dm)=>{"use strict";var MA=Cm();Dm.exports=MA});var xs=m((ZC,Om)=>{"use strict";var CA=Bm();Om.exports=CA});var ob=m(()=>{"use strict";var uw=Le(),lw=ui(),cw=es(),dw=Za(),pw=$n();uw({target:"Array",proto:!0},{at:function(e){var t=lw(this),r=cw(t),i=dw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});pw("at")});var lb=m((u0,ub)=>{"use strict";ob();var hw=Es();ub.exports=hw("Array","at")});var db=m((l0,cb)=>{"use strict";var fw=lb();cb.exports=fw});var Lr=m((c0,pb)=>{"use strict";var mw=db();pb.exports=mw});var gg=m(()=>{"use strict"});var Sg=m(()=>{"use strict"});var yg=m((c_,vg)=>{"use strict";var Tk=Re(),Ik=pr(),Ek=ae(),xk=Ek("match");vg.exports=function(a){var e;return Tk(a)&&((e=a[xk])!==void 0?!!e:Ik(a)==="RegExp")}});var Ig=m((d_,Tg)=>{"use strict";var Pk=fi(),Ak=String;Tg.exports=function(a){if(Pk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Ak(a)}});var xg=m((p_,Eg)=>{"use strict";var wk=ze();Eg.exports=function(){var a=wk(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var wg=m((h_,Ag)=>{"use strict";var kk=Te(),Rk=He(),$k=ai(),Lk=xg(),Pg=RegExp.prototype;Ag.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Pg)&&!Rk(a,"flags")&&$k(Pg,a)?kk(Lk,a):e}});var Rg=m((f_,kg)=>{"use strict";var qu=ce(),Mk=ui(),Ck=Math.floor,Fu=qu("".charAt),Dk=qu("".replace),Uu=qu("".slice),Bk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Ok=/\$([$&'`]|\d{1,2})/g;kg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=Ok;return i!==void 0&&(i=Mk(i),u=Bk),Dk(s,u,function(c,l){var d;switch(Fu(l,0)){case"$":return"$";case"&":return a;case"`":return Uu(e,0,t);case"'":return Uu(e,n);case"<":d=i[Uu(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=Ck(p/10);return h===0?c:h<=o?r[h-1]===void 0?Fu(l,1):r[h-1]+Fu(l,1):c}d=r[p-1]}return d===void 0?"":d})}});var Mg=m(()=>{"use strict";var Vk=Le(),_k=Te(),ju=ce(),$g=ri(),Nk=Y(),Fk=hr(),Uk=yg(),Fr=Ig(),qk=ni(),Hk=wg(),jk=Rg(),Gk=ae(),Wk=qe(),Yk=Gk("replace"),Qk=TypeError,Hu=ju("".indexOf),zk=ju("".replace),Lg=ju("".slice),Kk=Math.max;Vk({target:"String",proto:!0},{replaceAll:function(e,t){var r=$g(this),i,s,n,o,u,c,l,d,p,h,f=0,b="";if(!Fk(e)){if(i=Uk(e),i&&(s=Fr($g(Hk(e))),!~Hu(s,"g")))throw new Qk("`.replaceAll` does not allow non-global regexes");if(n=qk(e,Yk),n)return _k(n,e,r,t);if(Wk&&i)return zk(Fr(r),e,t)}for(o=Fr(r),u=Fr(e),c=Nk(t),c||(t=Fr(t)),l=u.length,d=Kk(1,l),p=Hu(o,u);p!==-1;)h=c?Fr(t(u,p,o)):jk(u,o,p,[],void 0,t),b+=Lg(o,f,p)+h,f=p+l,p=p+d>o.length?-1:Hu(o,u,p+d);return f<o.length&&(b+=Lg(o,f)),b}})});var Dg=m((g_,Cg)=>{"use strict";gg();Sg();Mg();var Jk=Es();Cg.exports=Jk("String","replaceAll")});var Og=m((S_,Bg)=>{"use strict";var Xk=Dg();Bg.exports=Xk});var _g=m((v_,Vg)=>{"use strict";var Zk=Og();Vg.exports=Zk});var tc="2.0.113-dev.cde1b449.0";var le=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(le||{}),Tt=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(Tt||{});var Ua=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Ua||{}),xn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(xn||{});var Pn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Pn||{});import{assertNever as oc,assertNonNullable as vv,isNonNullable as qa,ValueSubject as An,Subject as yv,Subscription as Tv,merge as Iv,observableFrom as Ev,fromEvent as ic,map as ac,tap as sc,filterChanged as xv,isNullable as wn,ErrorCategory as nc}from"@vkontakte/videoplayer-shared";var rc=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 Ha=class{constructor(e){this.connection$=new An(void 0);this.castState$=new An("NOT_AVAILABLE");this.errorEvent$=new yv;this.realCastState$=new An("NOT_AVAILABLE");this.subscription=new Tv;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=qa((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||rc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:nc.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){qa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();wn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();wn(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(ic(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 oc(i.sessionState)}})).add(Iv(ic(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(sc(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),ac(i=>i.castState)),Ev([r.getCastState()])).pipe(xv(),ac(Pv),sc(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=qa(this.connection$.getValue());if(s&&!n){let c=r.getCurrentSession();vv(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(wn(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"?qa(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:nc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Pv=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return oc(a)}};var OS=Fe(ko(),1);var Wm=Fe(xs(),1);import{assertNever as Vm}from"@vkontakte/videoplayer-shared";var te=(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:Vm(t)}return a},hu=(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:Vm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as DA,Subject as Ps,merge as _m}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new Ps;this.transitionEnded$=new Ps;this.transitionUpdated$=new Ps;this.forceChanged$=new Ps;this.stateChangeStarted$=_m(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=_m(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||DA(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as BA}from"@vkontakte/videoplayer-shared";var Nm=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return BA(a)}};import{assertNever as Rr,assertNonNullable as Gt,debounce as Fm,ErrorCategory as Um,fromEvent as Wt,isNonNullable as qm,map as Hm,merge as jm,observableFrom as OA,Subject as VA,Subscription as fu,timeout as _A,getHighestQuality as NA}from"@vkontakte/videoplayer-shared";var FA=5,UA=5,qA=500,Gm=7e3,Pi=class{constructor(e){this.subscription=new fu;this.loadMediaTimeoutSubscription=new fu;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:Rr(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:Rr(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:Rr(e)}break}default:Rr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Nm(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 fu;this.subscription.add(e),this.subscription.add(jm(this.videoState.stateChangeStarted$.pipe(Hm(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Hm(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new VA;e.add(i.pipe(Fm(qA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>FA)&&i.next(o),s=o})),e.add(Wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Wt(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:Rr(n)}}),t(Wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=jm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,OA(["init"])).pipe(Fm(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&E(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var c;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let l=t[e];Gt(l);let d=NA(Object.keys(l));Gt(d);let p=l[d];Gt(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Gt(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];Gt(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Gt(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];Gt(l),r=te(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:Um.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Rr(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 qm(o)&&(n.metadata.title=o),qm(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(_A(Gm).subscribe(()=>s(`timeout(${Gm})`)))});(0,Wm.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Um.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Qm}from"@vkontakte/videoplayer-shared";import{clearVideoElement as HA}from"@vkontakte/videoplayer-shared";var Ym=a=>{try{a.pause(),a.playbackRate=0,HA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as jA,Subscription as GA}from"@vkontakte/videoplayer-shared";var mu=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)}},bu=window.WeakMap?new WeakMap:new mu,gu=window.WeakMap?new WeakMap:new Map,WA=(a,e=20)=>{let t=0;return jA(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},de=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Qm(t):(t=document.createElement("video"),a.appendChild(t)),bu.set(t,r);let i=new GA;return i.add(WA(t,e)),gu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},pe=a=>{let e=gu.get(a);e==null||e.unsubscribe(),gu.delete(a);let t=bu.get(a);bu.delete(a),t?Qm(a):Ym(a)};import{assertNonNullable as Ai,isNonNullable as Je,isNullable as zA,fromEvent as $r,merge as zm,observableFrom as Km,filterChanged as Jm,map as wi,Subject as Xm,Subscription as KA,ValueSubject as JA,ErrorCategory as XA}from"@vkontakte/videoplayer-shared";import{isNonNullable as Su,isNullable as YA,Subscription as QA}from"@vkontakte/videoplayer-shared";var As=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=YA(i),c=new QA;return i&&c.add(i.subscribe(l=>{let d=a.getState();r(l,d)&&a.setState(l)},s)),r(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(l=>{t(l.to),u&&a.setState(l.to)},s)),c},Ke=(a,e,t)=>As(e,()=>a.loop,r=>{Su(r)&&(a.loop=r)},{onError:t}),he=(a,e,t,r)=>As(e,()=>({muted:a.muted,volume:a.volume}),i=>{Su(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Me=(a,e,t,r)=>As(e,()=>a.playbackRate,i=>{Su(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Et=As;var ZA=a=>["__",a.language,a.label].join("|"),ew=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},vu=class a{constructor(){this.available$=new Xm;this.current$=new JA(void 0);this.error$=new Xm;this.subscription=new KA;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:XA.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Et(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(wi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Et(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(wi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Et(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(Et(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ai(this.video);let{textTracks:e}=this.video;this.subscription.add($r(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(zm($r(e,"addtrack"),$r(e,"removetrack"),Km(["init"])).pipe(wi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Jm((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(zm($r(e,"change"),Km(["init"])).pipe(wi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),wi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Jm()).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($r(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($r(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){Ai(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,i=e.id?e.id:ZA(e),s=this.externalTracks.has(i),n=i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(i))==null?void 0:o.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(i))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){Ai(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(zA(e)||!ew(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Ai(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){Ai(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=vu;var at=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 Zm=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},yu=a=>{let e=Zm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},eb=a=>{let e=Zm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as De,map as xt,merge as rb,filterChanged as rw,isNonNullable as ib,Subject as iw,filter as ab,mapTo as sb,combine as aw,once as sw,ErrorCategory as nw,ValueSubject as nb,clientChecker as ow}from"@vkontakte/videoplayer-shared";var tw=3,tb=(a,e,t=tw)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var fe=a=>{let e=S=>De(a,S).pipe(sb(void 0)),r=rb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>De(a,S))).pipe(xt(S=>S.type==="ended"?a.readyState<2:a.readyState<3),rw()),i=rb(De(a,"progress"),De(a,"timeupdate")).pipe(xt(()=>tb(a.buffered,a.currentTime))),s=ow.isSafari?aw({play:e("play").pipe(sw()),playing:e("playing")}).pipe(sb(void 0)):e("playing"),n=De(a,"volumechange").pipe(xt(()=>({muted:a.muted,volume:a.volume}))),o=De(a,"ratechange").pipe(xt(()=>a.playbackRate)),u=De(a,"error").pipe(ab(()=>!!(a.error||a.played.length)),xt(()=>{var y;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:nw.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(y=a.error)!=null?y:void 0}})),c=De(a,"timeupdate").pipe(xt(()=>a.currentTime)),l=new iw,d=.3,p;c.subscribe(S=>{a.loop&&ib(p)&&ib(S)&&p>=a.duration-d&&S<=d&&l.next(p),p=S});let h=e("pause").pipe(ab(()=>!a.error&&p!==a.duration)),f=De(a,"enterpictureinpicture"),b=De(a,"leavepictureinpicture"),g=new nb(eb(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new nb(yu(a));return De(a,"fullscreenchange").pipe(xt(()=>yu(a))).subscribe(v),{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(xt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v}};import{VideoQuality as Pt}from"@vkontakte/videoplayer-shared";var At=a=>{switch(a){case"mobile":return Pt.Q_144P;case"lowest":return Pt.Q_240P;case"low":return Pt.Q_360P;case"sd":case"medium":return Pt.Q_480P;case"hd":case"high":return Pt.Q_720P;case"fullhd":case"full":return Pt.Q_1080P;case"quadhd":case"quad":return Pt.Q_1440P;case"ultrahd":case"ultra":return Pt.Q_2160P}};var Yt=Fe(Lr(),1);import{isNonNullable as me,isNullable as Iu,now as yb,isHigher as Eu,isHigherOrEqual as bb,isInvariantQuality as gb,isLower as xu,isLowerOrEqual as Sb,videoSizeToQuality as bw,assertNotEmptyArray as Tb,assertNonNullable as gw}from"@vkontakte/videoplayer-shared";var Tu=!1,st={},hb=a=>{Tu=a},fb=()=>{st={}},mb=a=>{a(st)},ki=(a,e)=>{var t;Tu&&(st.meta=(t=st.meta)!=null?t:{},st.meta[a]=e)},se=class{constructor(e){this.name=e}next(e){var r,i;if(!Tu)return;st.series=(r=st.series)!=null?r:{};let t=(i=st.series[this.name])!=null?i:[];t.push([Date.now(),e]),st.series[this.name]=t}};var Sw=new se("best_bitrate"),Ib=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Pu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ri=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=yb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Eb='Assertion "ABR Tracks is empty array" failed',ws=(a,e,t,r)=>{var u;let i=[...e].sort(Pu(1)),s=[...t].sort(Pu(1)),n=s.filter(c=>me(c.bitrate)&&me(a.bitrate)?a.bitrate/c.bitrate>r:!0),o=(u=(0,Yt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Yt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Yt.default)(n,-1):(0,Yt.default)(s,0)},vb=a=>"quality"in a,xb=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&yb()-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=vb(s)?"video":"audio",o=vb(s)?s.quality:s.bitrate;return e({message:`
|
|
7
7
|
[last ${n} selected] ${o}
|
|
8
|
-
`}),s}return r==null||r.recordSwitch(t),t},
|
|
8
|
+
`}),s}return r==null||r.recordSwitch(t),t},wt=(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 F,O,k,L,q;Tb(a,Eb);let h=r.usePixelRatio&&(F=window.devicePixelRatio)!=null?F:1,f=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*r.containerSizeFactor,height:e.height*h*r.containerSizeFactor},b=f&&bw(f),g=r.considerPlaybackRate&&me(o)?o:1,v=a.filter($=>!gb($.quality)).sort(($,x)=>Eu($.quality,x.quality)?-1:1),I=(O=(0,Yt.default)(v,-1))==null?void 0:O.quality,S=(k=(0,Yt.default)(v,0))==null?void 0:k.quality,y=Iu(i)||me(i.min)&&me(i.max)&&xu(i.max,i.min)||me(i.min)&&S&&Eu(i.min,S)||me(i.max)&&I&&xu(i.max,I),T=g*Ib(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),R={},w=v.filter($=>{if(!(b?xu($.quality,b):!0))return R[$.quality]="FitsContainer",!1;if(!(me(t)&&isFinite(t)&&me($.bitrate)?t-s>=$.bitrate*T:!0))return R[$.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&me(r.minBufferToSwitchUp)&&u&&!gb(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Eu($.quality,u.quality))return R[$.quality]="Buffer",!1;if(!!d&&bb($.quality,d))return R[$.quality]="DroppedFramesLimit",!1;let K=y||(Iu(i.max)||Sb($.quality,i.max))&&(Iu(i.min)||bb($.quality,i.min)),oe=me(l)&&!l?Sb($.quality,r.backgroundVideoQualityLimit):!0;return!K||!oe?(R[$.quality]="FitsQualityLimits",!1):!0})[0];w&&w.bitrate&&Sw.next(w.bitrate);let B=(L=w!=null?w:v[Math.ceil((v.length-1)/2)])!=null?L:a[0];return B.quality!==((q=c==null?void 0:c.last)==null?void 0:q.quality)&&p({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
10
10
|
[available video tracks]
|
|
11
11
|
${a.map($=>`{ id: ${$.id}, quality: ${$.quality}, bitrate: ${$.bitrate} }`).join(`
|
|
@@ -35,7 +35,7 @@ var hv=Object.create;var el=Object.defineProperty;var fv=Object.getOwnPropertyDe
|
|
|
35
35
|
|
|
36
36
|
[best video track] ${w==null?void 0:w.quality}
|
|
37
37
|
[selected video track] ${B==null?void 0:B.quality}
|
|
38
|
-
`}),xb(r,p,B,
|
|
38
|
+
`}),xb(r,p,B,c)},Pb=(a,e,t,{throughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var f;Tb(t,Eb);let c=i.considerPlaybackRate&&me(s)?s:1,l=[...t].sort(Pu(-1)),d=a.bitrate;gw(d);let p=c*Ib(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),h;return me(r)&&isFinite(r)&&(h=l.find(b=>me(b.bitrate)?r-d>=b.bitrate*p:!0)),h||(h=ws(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 hv=Object.create;var el=Object.defineProperty;var fv=Object.getOwnPropertyDe
|
|
|
49
49
|
throughput: ${r},
|
|
50
50
|
reserve: ${d},
|
|
51
51
|
playbackRate: ${s},
|
|
52
|
-
playbackRateFactor: ${
|
|
52
|
+
playbackRateFactor: ${c},
|
|
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&&xb(i,u,h,o)};var X=a=>new URL(a).hostname;import{assertNever as Lb,assertNonNullable as Mb,combine as _w,debounce as Nw,ErrorCategory as Cb,filter as Db,filterChanged as Fw,isNonNullable as Ru,map as Ls,merge as Bb,observableFrom as qw,once as Uw,Subscription as Hw,ValueSubject as $u,videoQualityToHeight as jw,videoSizeToQuality as Gw}from"@vkontakte/videoplayer-shared";var Ab=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},be=async a=>{let e=a.muted;try{await a.play()}catch(t){if(!Ab(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(r){return Ab(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as ks,isNullable as Tw,assertNonNullable as Li}from"@vkontakte/videoplayer-shared";import{isNonNullable as wb,assertNonNullable as ws,now as vw}from"@vkontakte/videoplayer-shared";function Z(){return vw()}function Pu(a){return Z()-a}function Au(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 kb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function $r(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;ws(c);let k=Pu(c),L;if(k<b){L=b-k,setTimeout(g,L);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,R()},v=k=>(s=k,O),I=k=>(d=k,O),S=()=>(h="json",O),y=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},T=k=>(p=k,O),R=()=>{c=Z(),n=new i,n.open("get",a);let k=0,L,U=0,$=()=>(ws(c),Math.max(c,Math.max(L||0,U||0)));if(s&&n.addEventListener("progress",x=>{let V=Z();s.updateChunk&&x.loaded>k&&(s.updateChunk($(),x.loaded-k),k=x.loaded,L=V)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;ws(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let V=n.response.byteLength-k;V&&s.updateChunk&&s.updateChunk($(),V)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),p){let x=()=>{ws(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(U=Z(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),O},O={withBitrateReporting:v,withParallel:T,withJSONResponse:S,withRetryCount:k=>(l=k,O),withRetryInterval:(k,L)=>(wb(k)&&(b=k),wb(L)&&(f=L),O),withTimeout:k=>(o=k,O),withFinally:I,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return O}var Ri=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 $i=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=Z(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=Z()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=$r(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Z()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=Z();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Rs=1e4,wu=3;var Iw=6e4,Ew=10,xw=1,Pw=500,Mi=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 Ri(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Au(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=Au(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||ks(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=()=>{kb(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 $i(wu,Rs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let y=s&&(!c||c===this.rep);return y||t("Not running!"),y},p=(y,T,R)=>{u&&u.abort(),u=$r(this.urlResolver.resolve(y,!1),T,R,()=>this._retryCallback()).withTimeout(Rs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(wu).withFinally(()=>{u=null}).send()},h=(y,T,R)=>{Li(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),T,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=y=>{let T=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${T}=>${y}`),r.playbackRate=y)},b=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=Z()-1e4,_=0;for(let B=0;B<this.bufferStates.length;B++){let F=this.bufferStates[B];y=Math.min(y,F.buf),F.ts<R&&_++}this.bufferStates.splice(0,_),t(`update playback rate; minBuffer=${y} drop=${_} jitter=${this.sourceJitter}`);let w=y-xw;this.sourceJitter>=0?w-=this.sourceJitter/2:this.sourceJitter-=1,w>3?f(1.15):w>1?f(1.1):w>.3?f(1.05):f(1)}},v=y=>{let T,R=()=>T&&T.start?T.start.length:0,_=x=>T.start[x]/1e3,w=x=>T.dur[x]/1e3,B=x=>T.fragIndex+x,F=(x,V)=>({chunkIdx:B(x),startTS:_(x),dur:w(x),discontinuity:V}),O=()=>{let x=0;if(T&&T.dur){let V=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,W=V;this.sourceJitter>1&&(W+=this.sourceJitter-1);let K=T.dur.length-1;for(;K>=0&&(W-=T.dur[K],!(W<=0));--K);x=Math.min(K,T.dur.length-1-H),x=Math.max(x,0)}return F(x,!0)},k=x=>{let V=R();if(!(V<=0)){if(ks(x)){for(let H=0;H<V;H++)if(_(H)>x)return F(H)}return O()}},L=x=>{let V=R(),H=x?x.chunkIdx+1:0,W=H-T.fragIndex;if(!(V<=0)){if(!x||W<0||W-V>Ew)return t(`Resync: offset=${W} bChunks=${V} chunk=`+JSON.stringify(x)),O();if(!(W>=V))return F(H-T.fragIndex,!1)}},U=(x,V,H)=>{l&&l.abort(),l=$r(this.urlResolver.resolve(x,!0,this.lowLatency),V,H,()=>this._retryCallback()).withTimeout(Rs).withRetryCount(wu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(x,V)=>{U(y,H=>{if(!d())return;T=H;let W=!!T.lowLatency;W!==this.lowLatency&&b(W);let K=0;for(let ne=0;ne<T.dur.length;++ne)K+=T.dur[ne];K>0&&(Li(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(K/T.dur.length)),i({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,x(k(V))},()=>this._handleNetworkError())},nextChunk:L}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Li(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:T,logger:R}=this.params,_=v(e.jidxUrl),w,B,F,O,k=0,L,U,$,x=()=>{L&&(clearTimeout(L),L=void 0);let A=Math.max(Pw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),oe=k+A,ve=Z(),Ae=Math.min(1e4,oe-ve);k=ve;let ft=()=>{l||d()&&_.seek(()=>{d()&&(k=Z(),V(),x())})};Ae>0?L=window.setTimeout(()=>{this.paused?x():ft()},Ae):ft()},V=()=>{let A;for(;A=_.nextChunk(O);)O=A,Mt(A);let oe=_.nextChunk(F);if(oe){if(F&&oe.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?x():(I(),this._initPlayerWith(e));return}ne(oe)}else x()},H=(A,oe)=>{if(!d()||!this.sourceBuffer)return;let ve,Ae,ft,ir=mt=>{window.setTimeout(()=>{d()&&H(A,oe)},mt)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),ir(100);else{let mt=Z(),Ct=T.currentTime;!this.paused&&T.buffered.length>1&&U===Ct&&mt-$>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),U!==Ct&&(U=Ct,$=mt);let ar=this._getBufferSizeSec();if(ar>30)R(`Buffered ${ar} seconds; delaying appendBuffer`),ir(2e3);else try{this.sourceBuffer.appendBuffer(A),this.videoPlayStarted?(this.bufferStates.push({ts:mt,buf:ar}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),oe&&oe()}catch(Wr){if(Wr.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),ft=this.sourceBuffer.buffered.length,ft!==0&&(ve=this.sourceBuffer.buffered.start(0),Ae=Ct,Ae-ve>4&&this.sourceBuffer.remove(ve,Ae-3)),ir(1e3);else throw Wr}}},W=()=>{B&&w&&(R([`Appending chunk, sz=${B.byteLength}:`,JSON.stringify(F)]),H(B,function(){B=null,V()}))},K=A=>e.fragUrlTemplate.replace("%%id%%",A.chunkIdx),ne=A=>{d()&&h(K(A),(oe,ve)=>{if(d()){if(ve/=1e3,B=oe,F=A,n=A.startTS,ve){let Ae=Math.min(10,A.dur/ve);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ae:Ae}W()}},()=>this._handleNetworkError())},Mt=A=>{d()&&(Li(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(K(A),!1)))},ht=A=>{d()&&(e.cachedHeader=A,H(A,()=>{w=!0,W()}))};s=!0,_.seek(A=>{if(d()){if(k=Z(),!A){x();return}O=A,!Tw(y)||A.startTS>y?ne(A):(F=A,V())}},y),e.cachedHeader?ht(e.cachedHeader):p(e.headerUrl,ht,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),ks(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,Li(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return ks(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=Z();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Pu(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=Z();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=$r(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Rs).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;be(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Iw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Aw,filter as Rb,fromEvent as ww,interval as kw,isHigher as Rw,isInvariantQuality as $w,isLower as Lw,merge as Mw,Subject as $b,Subscription as Cw}from"@vkontakte/videoplayer-shared";var ku=class{constructor(){this.onDroopedVideoFramesLimit$=new $b;this.subscription=new Cw;this.playing=!1;this.tracks=[];this.forceChecker$=new $b;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!$w(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Rw(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(ww(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=kw(this.droppedFramesChecker.checkTime).pipe(Rb(()=>this.playing),Rb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(Aw(this.droppedFramesChecker.checkTime)),r=Mw(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>Lw(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},$s=ku;import{map as Dw,Observable as Bw}from"@vkontakte/videoplayer-shared";import{fromEvent as Ow}from"@vkontakte/videoplayer-shared";var Ci=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Vw=(a,e)=>new Bw(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ci()))},{...r,...e});i.observe(a);let s=Ow(document,"visibilitychange").pipe(Dw(n=>!document.hidden||Ci())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),De=Vw;var Ww=["paused","playing","ready"],Yw=["paused","playing","ready"],Di=class{constructor(e){this.subscription=new Hw;this.videoState=new M("stopped");this.representations$=new $u([]);this.textTracksManager=new Me;this.droppedFramesManager=new $s;this.maxSeekBackTime$=new $u(1/0);this.zeroTime$=new $u(void 0);this.liveOffset=new at;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Cb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Pt(u.name))!=null?r:Gw(u.video),d=u.bitrate/1e3,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),Ru(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Yw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Ww.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ee(this.params.source.url,u))}return;default:return Lb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Cb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Bb(this.videoState.stateChangeStarted$.pipe(Ls(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ls(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=de(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(X(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=fe(this.video);this.subscription.add(this.representations$.pipe(Ls(i=>i.map(({track:s})=>s)),Db(i=>!!i.length),Uw()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Fw(),Ls(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(_w({zeroTime:this.zeroTime$.pipe(Db(Ru)),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(he(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Le(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(De(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&jw(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Lb(i.to)}},t)).add(Bb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,qw(["init"])).pipe(Nw(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),pe(this.video)}createLiveDashPlayer(){let e=new Mi({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&&Ru(t)?t:At(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;Mb(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;Mb(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ee(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Ob=Di;var Xe=(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 IR,assertNonNullable as ER,debounce as xR,ErrorCategory as nc,filter as oS,filterChanged as oc,fromEvent as PR,isNonNullable as AR,map as uS,merge as rn,observableFrom as wR,observeElementSize as kR,once as cS,Subscription as RR,ValueSubject as $R}from"@vkontakte/videoplayer-shared";var Ms=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Lr=class extends Ms{constructor(){super(),this.listeners||Ms.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Bi=class{constructor(){Object.defineProperty(this,"signal",{value:new Lr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Bi.prototype[Symbol.toStringTag]="AbortController",Lr.prototype[Symbol.toStringTag]="AbortSignal");function Cs(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 Lu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Cs({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 Oi=Cs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Vb=Oi?Lu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,nt=Oi?Vb.fetch:window.fetch,MB=Oi?Vb.Request:window.Request,ot=Oi?Bi:window.AbortController,CB=Oi?Lr:window.AbortSignal;var Kb=Qe(Ai(),1);var ut=()=>window.ManagedMediaSource||window.MediaSource,Ds=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},_b=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Nb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Hs,clientChecker as Us}from"@vkontakte/videoplayer-shared";var Be=document.createElement("video"),Kw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Jw='video/mp4; codecs="hev1.1.6.L93.B0"',Jb='video/webm; codecs="vp09.00.10.08"',Xb='video/webm; codecs="av01.0.00M.08"',Xw='audio/mp4; codecs="mp4a.40.2"',Zw='audio/webm; codecs="opus"',Fb,qb,Yt={mms:Ds(),mse:_b(),hls:!!((Fb=Be.canPlayType)!=null&&Fb.call(Be,"application/x-mpegurl")||(qb=Be.canPlayType)!=null&&qb.call(Be,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Ub,Hb,ge={mp4:!!((Ub=Be.canPlayType)!=null&&Ub.call(Be,"video/mp4")),webm:!!((Hb=Be.canPlayType)!=null&&Hb.call(Be,"video/webm")),cmaf:!0},Os,jb,Vs,Gb,_s,Wb,Ns,Yb,Fs,Qb,qs,zb,Se={h264:!!((jb=(Os=ut())==null?void 0:Os.isTypeSupported)!=null&&jb.call(Os,Kw)),h265:!!((Gb=(Vs=ut())==null?void 0:Vs.isTypeSupported)!=null&&Gb.call(Vs,Jw)),vp9:!!((Wb=(_s=ut())==null?void 0:_s.isTypeSupported)!=null&&Wb.call(_s,Jb)),av1:!!((Yb=(Ns=ut())==null?void 0:Ns.isTypeSupported)!=null&&Yb.call(Ns,Xb)),aac:!!((Qb=(Fs=ut())==null?void 0:Fs.isTypeSupported)!=null&&Qb.call(Fs,Xw)),opus:!!((zb=(qs=ut())==null?void 0:qs.isTypeSupported)!=null&&zb.call(qs,Zw))},Mr=(Se.h264||Se.h265)&&Se.aac,Qt,ek=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Xb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Jb}})]);Qt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{ek()}catch(a){console.error(a)}var Cr=Yt.hls&&ge.mp4,Zb=()=>Object.keys(Se).filter(a=>Se[a]),eg=(a,e=!1,t=!1)=>{let r=Yt.mse||Yt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&ge.mp4&&Mr;case"DASH_WEBM":return r&&ge.webm&&Se.vp9&&Se.opus;case"DASH_WEBM_AV1":return r&&ge.webm&&Se.av1&&Se.opus;case"DASH_STREAMS":return r&&(ge.mp4&&Mr||ge.webm&&(Se.vp9||Se.av1)&&(Se.opus||Se.aac));case"DASH_LIVE":return Yt.mse&&ge.mp4&&Mr;case"DASH_LIVE_CMAF":return r&&ge.mp4&&Mr&&ge.cmaf;case"DASH_ONDEMAND":return r&&ge.mp4&&Mr;case"HLS":case"HLS_ONDEMAND":return Cr||e&&Yt.mse&&ge.mp4&&Mr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Cr;case"MPEG":return ge.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Yt.webrtc&&Yt.ws&&Se.h264&&(ge.mp4||ge.webm);default:return Hs(i)}})},Bs=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 Qt?Qt[t].smooth?[t,e]:Qt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Qt?Qt[t].powerEfficient?[t,e]:Qt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Hs(a)}return[e,t]},tg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Bs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Us.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",...Bs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Bs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Bs(a),...i,"HLS","HLS_ONDEMAND"];default:Hs(e)}return Cr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},rg=({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=Us.isMac&&Us.isSafari;if(Us.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:Hs(a)}else Cr&&!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"]},Mu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ig=a=>{if(a.size!==0){if(a.size===1)return a.values().next().value.split(".").at(0);for(let e of a){let t=(0,Kb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as Vi}from"@vkontakte/videoplayer-shared";var ag=a=>{if(!a)return{id:"EmptyResponse",category:Vi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Vi.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:Vi.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:Vi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Vi.PARSER,message:"Response is valid XML, but parser failed"}};var Dr=(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 rc,assertNonNullable as tr,clientChecker as dR,combine as Js,ErrorCategory as lt,filter as ic,filterChanged as tS,flattenObject as ha,fromEvent as Ur,getTraceSubscriptionMethod as pR,interval as ac,isNonNullable as rS,map as sc,merge as Hr,now as hR,Subject as iS,Subscription as aS,tap as fR,throttle as mR,ValueSubject as te}from"@vkontakte/videoplayer-shared";var Fr=Qe(Ai(),1);var tk=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},rk=a=>window.clearTimeout(a),sg=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Cu=sg?tk:window.requestIdleCallback,YB=sg?rk:window.cancelIdleCallback;var Qg=Qe(Es(),1);import{assertNever as ik,ErrorCategory as ng,clientChecker as Du,Subject as og}from"@vkontakte/videoplayer-shared";var ak=16,ug=!1;try{ug=Du.isSafari&&!!Du.macVersion&&Du.macVersion<=ak}catch(a){console.error(a)}var Bu=class{constructor(e){this.bufferFull$=new og;this.error$=new og;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:ng.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;ug&&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:ng.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:ik(t)}}},cg=Bu;var Ou=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 Nr,assertNonNullable as Ve,ErrorCategory as Xt,fromEvent as Ku,getExponentialDelay as Ju,isNonNullable as Xu,isNullable as Ee,now as Ws,once as tR,Subject as rR,Subscription as iR,ValueSubject as na}from"@vkontakte/videoplayer-shared";var q=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 Br=class extends q{};var _i=class extends q{};var Ni=class extends q{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 Fi=class extends q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qi=class extends q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends q{constructor(e,t){super(e,t),this.data=this.content}};var z=class extends q{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var zt=class extends z{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 Hi=class extends q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends z{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 Wi=class extends z{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Yi=class extends z{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 q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zi=class extends z{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 Ki=class extends q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ji=class extends q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xi=class extends z{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zi=class extends q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends z{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 ta=class extends z{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 ra=class extends z{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var nk={ftyp:Ni,moov:Fi,moof:qi,mdat:Ui,sidx:zt,trak:Hi,mdia:Qi,mfhd:Xi,tkhd:zi,traf:Zi,tfhd:ea,tfdt:ta,trun:ra,minf:Ki,sv3d:ji,st3d:Gi,prhd:Wi,proj:Ji,equi:Yi,uuid:_i,unknown:Br},Kt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=nk[e];return r?new r(t,new a):new Br(t,new a)}};var Or=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var uk=new TextDecoder("ascii"),ck=a=>uk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",lk=a=>{let e=new zt(a,new Kt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},dk=(a,e)=>{let r=new Kt().parse(a),i=new Or(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)},pk=(a,e)=>{let r=new Kt().parse(a),s=new Or(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},hk=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Kt().parse(a),i=new Or(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},lg={validateData:ck,parseInit:hk,getIndexRange:()=>{},parseSegments:lk,parseFeedableSegmentChunk:dk,getSegmentEndTime:pk};import{assertNonNullable as _u,isNonNullable as fg,isNullable as mk}from"@vkontakte/videoplayer-shared";import{assertNever as fk}from"@vkontakte/videoplayer-shared";var dg={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"}},pg=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=ia(a,t),i=r in dg,s=i?dg[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=ia(u),d=l*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}},ia=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},je=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ia(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:fk(e)}},Jt=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=pg(r);if(!e(i))return;i.type==="master"&&Jt(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},hg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=pg(a);return Jt(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 mg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],bk=[231,22612,22743,167,171,163,160,175],gk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Jt(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=je(f,h);l=ia(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=je(f,h):p===17545?i=je(f,h):p===21420&&l===475249515?u=je(f,h):p===374648427?Jt(f,({tag:g,type:v,value:I})=>g===30321?(c=je(I,v)===1,!1):!0):s&&n&&mg.includes(p)&&(o=!0),!o}),_u(e,"Failed to parse webm Segment start"),_u(t,"Failed to parse webm Segment end"),_u(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Sk=a=>{if(mk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},vk=(a,e)=>{let t=!1,r=!1,i=o=>fg(o.time)&&fg(o.position),s=[],n;return Jt(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=je(l,u));break;case 183:break;case 241:n&&(n.position=je(l,u));break;default:t&&mg.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}}})},yk=a=>{let e=0,t=!1;try{Jt(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):bk.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},bg={validateData:hg,parseInit:gk,getIndexRange:Sk,parseSegments:vk,parseFeedableSegmentChunk:yk};var Vr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return bg;case"mp4":return lg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Gu=Qe(_g(),1);var ju=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 Fg,isNullable as qg}from"@vkontakte/videoplayer-shared";var Ng=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Ug=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},ct=(a,e)=>{let t=a;t=(0,Gu.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,Gu.default)(t,n,(o,u)=>qg(s)?o:qg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Hg=(a,e)=>{var y,T,R,_,w,B,F,O,k,L,U,$,x,V,H,W,K,ne,Mt,ht,A,oe,ve,Ae,ft,ir,mt,Ct,ar,Wr,Ec,xc,Pc,Ac,wc,kc,Rc,$c,Lc,Mc,Cc,Dc,Bc,Oc,Vc,_c,Nc,Fc,qc,Uc,Hc,jc,Gc,Wc,Yc,Qc,zc,Kc,Jc,Xc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(R=(T=(y=s.querySelector("BaseURL"))==null?void 0:y.textContent)==null?void 0:T.trim())!=null?R:"",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=Ug(h);else if(f){let ue=Ug(f);Fg(ue)&&(p=ue)}else g&&(p=parseInt(g,10));let v=0,I=(w=(_=s.getAttribute("profiles"))==null?void 0:_.split(","))!=null?w:[];for(let ue of u){let ev=(B=ue.getAttribute("id"))!=null?B:"id"+(v++).toString(10),Yr=(F=ue.getAttribute("mimeType"))!=null?F:"",Sn=(O=ue.getAttribute("codecs"))!=null?O:"",vn=(k=ue.getAttribute("contentType"))!=null?k:Yr==null?void 0:Yr.split("/")[0],tv=(U=(L=ue.getAttribute("profiles"))==null?void 0:L.split(","))!=null?U:[],rv=($=ue.getAttribute("lang"))!=null?$:void 0,iv=(H=(V=(x=ue.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:V.trim())!=null?H:void 0,av=ue.querySelectorAll("Representation"),sv=ue.querySelector("SegmentTemplate"),nv=(K=(W=ue.querySelector("Role"))==null?void 0:W.getAttribute("value"))!=null?K:void 0,Qr=vn,J={id:ev,language:rv,isDefault:nv==="main",label:iv,codecs:Sn,hdr:Qr==="video"&&ju(Sn),mime:Yr,representations:[]};for(let G of av){let ov=(ne=G.getAttribute("lang"))!=null?ne:void 0,uv=(Mt=G.getAttribute("label"))!=null?Mt:void 0,cv=(oe=(A=(ht=G.querySelector("BaseURL"))==null?void 0:ht.textContent)==null?void 0:A.trim())!=null?oe:"",ka=new URL(cv||o,e).toString(),sr=(ve=G.getAttribute("mimeType"))!=null?ve:Yr,Ra=(ft=(Ae=G.getAttribute("codecs"))!=null?Ae:Sn)!=null?ft:"",$a;if(vn==="text"){let bt=G.getAttribute("id")||"",La=bt.includes("_auto"),Dt=G.querySelector("SegmentTemplate");if(Dt){let zr={representationId:(ir=G.getAttribute("id"))!=null?ir:void 0,bandwidth:(mt=G.getAttribute("bandwidth"))!=null?mt:void 0},Ma=parseInt((Ct=G.getAttribute("bandwidth"))!=null?Ct:"",10)/1e3,Ca=(Wr=parseInt((ar=Dt.getAttribute("startNumber"))!=null?ar:"",10))!=null?Wr:1,nr=parseInt((Ec=Dt.getAttribute("timescale"))!=null?Ec:"",10),yn=(xc=Dt.querySelectorAll("SegmentTimeline S"))!=null?xc:[],or=Dt.getAttribute("media");if(!or)continue;let Da=[],Ba=0,Oa="",ur=0,Kr=Ca,re=0;for(let _e of yn){let Bt=parseInt((Pc=_e.getAttribute("d"))!=null?Pc:"",10),we=parseInt((Ac=_e.getAttribute("r"))!=null?Ac:"",10)||0,gt=parseInt((wc=_e.getAttribute("t"))!=null?wc:"",10);re=Number.isFinite(gt)?gt:re;let Ot=Bt/nr*1e3,St=re/nr*1e3;for(let We=0;We<we+1;We++){let vt=ct(or,{...zr,segmentNumber:Kr.toString(10),segmentTime:(re+We*Bt).toString(10)}),cr=(St!=null?St:0)+We*Ot,Xr=cr+Ot;Kr++,Da.push({time:{from:cr,to:Xr},url:vt})}re+=(we+1)*Bt,Ba+=(we+1)*Ot}ur=re/nr*1e3,Oa=ct(or,{...zr,segmentNumber:Kr.toString(10),segmentTime:re.toString(10)});let Jr={time:{from:ur,to:1/0},url:Oa},Ze={type:"template",baseUrl:ka,segmentTemplateUrl:or,initUrl:"",totalSegmentsDurationMs:Ba,segments:Da,nextSegmentBeyondManifest:Jr,timescale:nr};$a={id:bt,kind:"text",segmentReference:Ze,profiles:[],duration:p,bitrate:Ma,mime:"",codecs:"",width:0,height:0,isAuto:La}}else $a={id:bt,isAuto:La,kind:"text",url:ka}}else{let bt=(Rc=(kc=G.getAttribute("contentType"))!=null?kc:sr==null?void 0:sr.split("/")[0])!=null?Rc:vn,La=(Lc=($c=ue.getAttribute("profiles"))==null?void 0:$c.split(","))!=null?Lc:[],Dt=parseInt((Mc=G.getAttribute("width"))!=null?Mc:"",10),zr=parseInt((Cc=G.getAttribute("height"))!=null?Cc:"",10),Ma=parseInt((Dc=G.getAttribute("bandwidth"))!=null?Dc:"",10)/1e3,Ca=(Bc=G.getAttribute("frameRate"))!=null?Bc:"",nr=(Oc=G.getAttribute("quality"))!=null?Oc:void 0,yn=Ca?Ng(Ca):void 0,or=(Vc=G.getAttribute("id"))!=null?Vc:"id"+(v++).toString(10),Da=bt==="video"?`${zr}p`:bt==="audio"?`${Ma}Kbps`:Ra,Ba=`${or}@${Da}`,Oa=[...I,...tv,...La],ur,Kr=G.querySelector("SegmentBase"),re=(_c=G.querySelector("SegmentTemplate"))!=null?_c:sv;if(Kr){let Ze=(Fc=(Nc=G.querySelector("SegmentBase Initialization"))==null?void 0:Nc.getAttribute("range"))!=null?Fc:"",[_e,Bt]=Ze.split("-").map(vt=>parseInt(vt,10)),we={from:_e,to:Bt},gt=(qc=G.querySelector("SegmentBase"))==null?void 0:qc.getAttribute("indexRange"),[Ot,St]=gt?gt.split("-").map(vt=>parseInt(vt,10)):[],We=gt?{from:Ot,to:St}:void 0;ur={type:"byteRange",url:ka,initRange:we,indexRange:We}}else if(re){let Ze={representationId:(Uc=G.getAttribute("id"))!=null?Uc:void 0,bandwidth:(Hc=G.getAttribute("bandwidth"))!=null?Hc:void 0},_e=parseInt((jc=re.getAttribute("timescale"))!=null?jc:"",10),Bt=(Gc=re.getAttribute("initialization"))!=null?Gc:"",we=re.getAttribute("media"),gt=(Yc=parseInt((Wc=re.getAttribute("startNumber"))!=null?Wc:"",10))!=null?Yc:1,Ot=ct(Bt,Ze);if(!we)throw new ReferenceError("No media attribute in SegmentTemplate");let St=(Qc=re.querySelectorAll("SegmentTimeline S"))!=null?Qc:[],We=[],vt=0,cr="",Xr=0;if(St.length){let Va=gt,Ne=0;for(let lr of St){let Ye=parseInt((zc=lr.getAttribute("d"))!=null?zc:"",10),Vt=parseInt((Kc=lr.getAttribute("r"))!=null?Kc:"",10)||0,_a=parseInt((Jc=lr.getAttribute("t"))!=null?Jc:"",10);Ne=Number.isFinite(_a)?_a:Ne;let Tn=Ye/_e*1e3,In=Ne/_e*1e3;for(let Na=0;Na<Vt+1;Na++){let dv=ct(we,{...Ze,segmentNumber:Va.toString(10),segmentTime:(Ne+Na*Ye).toString(10)}),Zc=(In!=null?In:0)+Na*Tn,pv=Zc+Tn;Va++,We.push({time:{from:Zc,to:pv},url:dv})}Ne+=(Vt+1)*Ye,vt+=(Vt+1)*Tn}Xr=Ne/_e*1e3,cr=ct(we,{...Ze,segmentNumber:Va.toString(10),segmentTime:Ne.toString(10)})}else if(Fg(p)){let Ne=parseInt((Xc=re.getAttribute("duration"))!=null?Xc:"",10)/_e*1e3,lr=Math.ceil(p/Ne),Ye=0;for(let Vt=1;Vt<lr;Vt++){let _a=ct(we,{...Ze,segmentNumber:Vt.toString(10),segmentTime:Ye.toString(10)});We.push({time:{from:Ye,to:Ye+Ne},url:_a}),Ye+=Ne}Xr=Ye,cr=ct(we,{...Ze,segmentNumber:lr.toString(10),segmentTime:Ye.toString(10)})}let lv={time:{from:Xr,to:1/0},url:cr};ur={type:"template",baseUrl:ka,segmentTemplateUrl:we,initUrl:Ot,totalSegmentsDurationMs:vt,segments:We,nextSegmentBeyondManifest:lv,timescale:_e}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!bt||!sr)continue;let Jr={video:"video",audio:"audio",text:"text"}[bt];if(!Jr)continue;Qr||(Qr=Jr),$a={id:Ba,kind:Jr,segmentReference:ur,profiles:Oa,duration:p,bitrate:Ma,mime:sr,codecs:Ra,width:Dt,height:zr,fps:yn,quality:nr}}J.language||(J.language=ov),J.label||(J.label=uv),J.mime||(J.mime=sr),J.codecs||(J.codecs=Ra),J.hdr||(J.hdr=Qr==="video"&&ju(Ra)),J.representations.push($a)}Qr&&i[Qr].push(J)}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,streams:i}};var aa=Qe(Ai(),1);import{videoSizeToQuality as eR}from"@vkontakte/videoplayer-shared";var jg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?Pt(s):void 0)!=null?o:eR({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},Gg=({id:a,bitrate:e})=>({id:a,bitrate:e}),js=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,aa.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,aa.default)(t,-1)},Wg=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Yg=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Qu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,aa.default)(r.split("."),0),isDefault:i}),zu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,aa.default)(i.split("."),0)}),Gs=a=>"url"in a,Oe=a=>a.type==="template",sa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var oa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new na(0);this.onLastSegment$=new na(!1);this.fullyBuffered$=new na(!1);this.playingRepresentation$=new na(void 0);this.playingRepresentationInit$=new na(void 0);this.error$=new rR;this.gaps=[];this.subscription=new iR;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ot;this.destroyAbortController=new ot;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Nr(this.destroyAbortController.signal,async function*(e){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 cg(this.sourceBuffer),this.subscription.add(Ku(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Xt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Xt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Ku(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Xt.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,Ou(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=Xe(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);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=Nr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Ve(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Ee(s)||Ee(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();Xu(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Nr(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!Oe(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);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=!!(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 ot,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(Ee(e)||Ee(this.downloadingRepresentationId)||Ee(this.playingRepresentationId)||Ee(this.sourceBuffer)||!Ee(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(((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=Xe(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)&&Ou(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Xe(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,Fr.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&&Xe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Fr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;Xu(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||!Oe(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Fr.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;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(!Oe(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=ct(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,v=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&I&&this.sourceBuffer&&!(Dr(this.sourceBuffer.buffered,p)&&Dr(this.sourceBuffer.buffered,h)))&&g&&I});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){Oe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Nr(o,async function*(){let c=Ju(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Ws(),!c)return;let d=new DataView(c);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=Vr(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),sa(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Nr(n,async function*(){let u=Ju(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ku(window,"online").pipe(tR()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=Ws(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),sa(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Oe(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Fr.default)(e,0).byte.from,to:(0,Fr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ws(),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:Xt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Oe(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ws();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:Xt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Vr(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,l=e.byteLength;for(let c of this.activeSegments){let{segment: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,v=b<i,I=g<=i;if(d.status==="downloading"&&v&&I){d.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+b,h),y=this.getCurrentPosition();Xu(y)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-y,this.bufferAccumulation.accumulated.push({segmentView:S,segmentProgress:c}),this.activeSegments.delete(c));let T=({segmentView:R,segmentProgress:_})=>this.sourceBufferTaskQueue.append(R,s).then(w=>w&&!s.aborted?this.onSegmentFullyAppended(_,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(T),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||Ee(y))&&(T({segmentView:S,segmentProgress:c}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&!I&&(c.loadedBytes=Math.min(h,i-b),c.loadedBytes>c.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),y=c.loadedBytes===h?S:Vr(o.mime).parseFeedableSegmentChunk(S);y!=null&&y.byteLength&&(d.status="partially_fed",c.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(T=>{if(s.aborted)n();else if(T)c.fedBytes+=y.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let c=l.byte.from-r,d=l.byte.to-r,p=d-c+1,h=c<i,f=d<=i;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-c),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?b:Vr(o.mime).parseFeedableSegmentChunk(b);g!=null&&g.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Gs(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=Cu(()=>(0,Qg.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Nr(this.destroyAbortController.signal,async function*(){let o=Ju(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Vr(e.mime),i)).then(async o=>{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&&Oe(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:Xt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ee(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push({...u.time}),i=n(i);let l=Gs(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?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ee(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=Gs(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)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||Ee(e)?0:Xe(this.sourceBuffer.buffered,e)}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=Cu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Xt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ee(this.sourceBuffer)||Ee(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 ua=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var zg=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 ca,assertNever as Kg,fromEvent as Jg,merge as aR,now as la,Subscription as sR,ValueSubject as Zu,flattenObject as qr}from"@vkontakte/videoplayer-shared";var Ys=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 ot;this.subscription=new sR;this.fetchManifest=ca(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ua(r));let i=yield nt(r,{signal:this.abortAllController.signal}).catch(da);return i?(t.log("success",qr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",qr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ca(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var O,k;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(l,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),l=L.toString();break}default:Kg(t)}this.requestQuic&&(l=ua(l));let p=this.abortAllController.signal,h;if(n){let L=new ot;if(h=aR(Jg(this.abortAllController.signal,"abort"),Jg(n,"abort")).subscribe(()=>{try{L.abort()}catch(U){da(U)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(U){da(U)}p=L.signal}let f=la();d.log("startRequest",qr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield nt(l,{priority:s,headers:c,signal:p}).catch(da),g=la();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(g-f),!b.ok||!b.body){h==null||h.unsubscribe();let L=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:L}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){h==null||h.unsubscribe();let L=la(),U={requestStartedAt:f,requestEndedAt:L,duration:L-f};return d.log("endRequest",qr(U)),d.end(),b.arrayBuffer()}let[v,I]=b.body.tee(),S=v.getReader();o&&((k=this.throughputEstimator)==null||k.trackStream(I,u));let y=0,T=new Uint8Array(0),R=!1,_=L=>{h==null||h.unsubscribe(),R=!0,da(L)},w=ca(p,async function*({done:L,value:U}){if(y===0&&this.lastRequestFirstBytes$.next(la()-f),p.aborted){h==null||h.unsubscribe();return}if(!L&&U){let $=new Uint8Array(T.length+U.length);$.set(T),$.set(U,T.length),T=$,y+=U.byteLength,i==null||i(new DataView(T.buffer),y),yield S==null?void 0:S.read().then(w,_)}}.bind(this));yield S==null?void 0:S.read().then(w,_),h==null||h.unsubscribe();let B=la(),F={failed:R,requestStartedAt:f,requestEndedAt:B,duration:B-f};return R?(d.error("endRequest",qr(F)),d.end(),null):(d.log("endRequest",qr(F)),d.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=ca(this.abortAllController.signal,async function*(e,t,r){var v;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=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let I=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!I)return null;b=new DataView(I)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=ca(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=zg(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Kg(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},da=a=>{if(!sa(a))throw a};var Zt=(a,e,t)=>t*e+(1-t)*a,ec=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Xg=(a,e,t,r)=>{let i=0,s=t,n=ec(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as nR,ValueSubject as Zg}from"@vkontakte/videoplayer-shared";var wt=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 Zg(e.initial),this.debounced$=new Zg(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ae(`raw_${t}`),this.smoothedSeries$=new ae(`smoothed_${t}`),this.reportedSeries$=new ae(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(nR(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Qs=class extends wt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Zt(this.slow,e,this.params.emaAlphaSlow),this.fast=Zt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var zs=class extends wt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ec(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Zt(this.emaSmoothed,e,this.params.emaAlpha);let r=Xg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Ks=class extends wt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Zt(this.smoothed,t,this.params.emaAlpha):t}};var er=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Qs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new zs({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 Ks({initial:e,label:"liveEdgeDelay",...t})}};var tc=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as oR,ValueSubject as uR}from"@vkontakte/videoplayer-shared";var pa=class a{constructor(e,t){this.currentRepresentation$=new uR(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!oR(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Oe(t.segmentReference))}};var bR=["timeupdate","progress","play","seeked","stalled","waiting"],gR=["timeupdate","progress","loadeddata","playing","seeked"];var Xs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new aS;this.representationSubscription=new aS;this.state$=new M("none");this.currentVideoRepresentation$=new te(void 0);this.currentVideoRepresentationInit$=new te(void 0);this.currentAudioRepresentation$=new te(void 0);this.currentVideoSegmentLength$=new te(0);this.currentAudioSegmentLength$=new te(0);this.error$=new iS;this.lastConnectionType$=new te(void 0);this.lastConnectionReused$=new te(void 0);this.lastRequestFirstBytes$=new te(void 0);this.currentLiveTextRepresentation$=new te(null);this.isLive$=new te(!1);this.liveDuration$=new te(0);this.liveAvailabilityStartTime$=new te(void 0);this.bufferLength$=new te(0);this.liveLoadBufferLength$=new te(0);this.livePositionFromPlayer$=new te(0);this.isActiveLowLatency$=new te(!1);this.timeInWaiting=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new iS;this.gapWatchdogActive=!1;this.destroyController=new ot;this.initManifest=rc(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:lt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=rc(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:lt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Hg(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=ag(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=ut())==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=ig(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);dR.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",ha(s)),s}.bind(this));this.initRepresentations=rc(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",ha({initialVideo:e,initialAudio:t,sourceHls:r})),tr(this.manifest),tr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Ur(p,"error").pipe(ic(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?Nb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ds())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 oa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],rS(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new oa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(pa.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new pa(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(ac(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=pu(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Hr(...gR.map(p=>Ur(this.element,p))).pipe(sc(p=>this.element?Xe(this.element.buffered,this.element.currentTime*1e3):0),tS(),fR(p=>{var h;p>this.tuning.dash.bufferEmptinessTolerance&&((h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(tS()).subscribe(h=>tc(this.element,1))),this.representationSubscription.add(Js({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(ic(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(Js({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,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b,S=1;Math.abs(I)>g&&(S=1+Math.sign(I)*v),tc(this.element,S)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let v=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(S=>{var y,T;return(T=(y=S.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?T:v}))-v}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(Js({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(mR(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(tr(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=pu(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,T=isFinite(h)?h:f,R=this.isActiveLowLatency$.getValue(),_=v<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(R&&_);let w="none";if(R?w="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&_?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),w="active_low_latency"):g!==0&&T<I?w="live_forward_buffering":T<I+y&&(w="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let B=p-(I+S),F=this.normolizeLiveOffset(Math.trunc(g+B/b)),O=Math.abs(F-g),k;!h||O<=this.tuning.dashCmafLive.offsetCalculationError?k=g:F>0&&O>this.tuning.dashCmafLive.offsetCalculationError?k=F:k=0,this.manifestUrlString=ee(this.manifestUrlString,k,2)}w!=="none"&&w!=="active_low_latency"&&(p=0,this.updateLive())}))}let u=Hr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(sc(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=Hr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(sc(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Hr(this.forceEnded$,Js({allBuffersFull:u,someBufferEnded:l}).pipe(ic(({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(Hr(...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),Oe(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&rS(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=ac(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 Ys({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=er.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;tr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ee(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){tr(this.element),this.state$.setState("running"),this.subscription.add(Hr(...bR.map(e=>Ur(this.element,e)),Ur(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:lt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ur(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ur(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Dr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var f,b,g,v,I,S,y,T,R,_;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting},n=hR(),o=100,u=(b=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?b:0,l=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,c=(S=(I=this.videoBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?S:0,d=(T=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?T:0,p=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if(this.tuning.useNewProviderReinitLogic&&(p||h)||this.tuning.useNewProviderReinitLogic&&this.timeInWaiting>=2*this.tuning.dash.crashOnStallTimeout||!this.tuning.useNewProviderReinitLogic&&this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s={...s,liveLastSeekOffset:this.liveLastSeekOffset};else{let w=this.element.currentTime*1e3;(R=this.videoBufferManager)==null||R.maintain(w),(_=this.audioBufferManager)==null||_.maintain(w),s={...s,position:w}}this.tracer.log("stallIntervalCallback",ha(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=ac(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:this.tuning.useNewProviderReinitLogic?lt.NETWORK:lt.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u,l;tr(this.element),tr(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),Dr(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",ha({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=pR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await 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={...t,gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ha(t)))}}};var Zs=class{constructor(e,t){this.fov=e,this.orientation=t}};var en=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var sS=`attribute vec2 a_vertex;
|
|
58
|
+
`}),h&&xb(i,u,h,o)};var X=a=>new URL(a).hostname;import{assertNever as Lb,assertNonNullable as Mb,combine as _w,debounce as Nw,ErrorCategory as Cb,filter as Db,filterChanged as Fw,isNonNullable as $u,map as Ms,merge as Bb,observableFrom as Uw,once as qw,Subscription as Hw,ValueSubject as Lu,videoQualityToHeight as jw,videoSizeToQuality as Gw}from"@vkontakte/videoplayer-shared";var Ab=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},be=async a=>{let e=a.muted;try{await a.play()}catch(t){if(!Ab(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(r){return Ab(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Rs,isNullable as Tw,assertNonNullable as Mi}from"@vkontakte/videoplayer-shared";import{isNonNullable as wb,assertNonNullable as ks,now as vw}from"@vkontakte/videoplayer-shared";function Z(){return vw()}function Au(a){return Z()-a}function wu(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 kb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Mr(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;ks(l);let k=Au(l),L;if(k<b){L=b-k,setTimeout(g,L);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,R()},v=k=>(s=k,O),I=k=>(d=k,O),S=()=>(h="json",O),y=()=>{if(!u){if(--c>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},T=k=>(p=k,O),R=()=>{l=Z(),n=new i,n.open("get",a);let k=0,L,q=0,$=()=>(ks(l),Math.max(l,Math.max(L||0,q||0)));if(s&&n.addEventListener("progress",x=>{let V=Z();s.updateChunk&&x.loaded>k&&(s.updateChunk($(),x.loaded-k),k=x.loaded,L=V)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;ks(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let V=n.response.byteLength-k;V&&s.updateChunk&&s.updateChunk($(),V)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),p){let x=()=>{ks(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(q=Z(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),O},O={withBitrateReporting:v,withParallel:T,withJSONResponse:S,withRetryCount:k=>(c=k,O),withRetryInterval:(k,L)=>(wb(k)&&(b=k),wb(L)&&(f=L),O),withTimeout:k=>(o=k,O),withFinally:I,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return O}var $i=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 Li=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=Z(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=Z()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Mr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Z()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=Z();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var $s=1e4,ku=3;var Iw=6e4,Ew=10,xw=1,Pw=500,Ci=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 $i(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=wu(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=wu(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||Rs(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=()=>{kb(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 Li(ku,$s,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,T,R)=>{u&&u.abort(),u=Mr(this.urlResolver.resolve(y,!1),T,R,()=>this._retryCallback()).withTimeout($s).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ku).withFinally(()=>{u=null}).send()},h=(y,T,R)=>{Mi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),T,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=y=>{let T=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${T}=>${y}`),r.playbackRate=y)},b=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=Z()-1e4,_=0;for(let B=0;B<this.bufferStates.length;B++){let F=this.bufferStates[B];y=Math.min(y,F.buf),F.ts<R&&_++}this.bufferStates.splice(0,_),t(`update playback rate; minBuffer=${y} drop=${_} jitter=${this.sourceJitter}`);let w=y-xw;this.sourceJitter>=0?w-=this.sourceJitter/2:this.sourceJitter-=1,w>3?f(1.15):w>1?f(1.1):w>.3?f(1.05):f(1)}},v=y=>{let T,R=()=>T&&T.start?T.start.length:0,_=x=>T.start[x]/1e3,w=x=>T.dur[x]/1e3,B=x=>T.fragIndex+x,F=(x,V)=>({chunkIdx:B(x),startTS:_(x),dur:w(x),discontinuity:V}),O=()=>{let x=0;if(T&&T.dur){let V=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,W=V;this.sourceJitter>1&&(W+=this.sourceJitter-1);let K=T.dur.length-1;for(;K>=0&&(W-=T.dur[K],!(W<=0));--K);x=Math.min(K,T.dur.length-1-H),x=Math.max(x,0)}return F(x,!0)},k=x=>{let V=R();if(!(V<=0)){if(Rs(x)){for(let H=0;H<V;H++)if(_(H)>x)return F(H)}return O()}},L=x=>{let V=R(),H=x?x.chunkIdx+1:0,W=H-T.fragIndex;if(!(V<=0)){if(!x||W<0||W-V>Ew)return t(`Resync: offset=${W} bChunks=${V} chunk=`+JSON.stringify(x)),O();if(!(W>=V))return F(H-T.fragIndex,!1)}},q=(x,V,H)=>{c&&c.abort(),c=Mr(this.urlResolver.resolve(x,!0,this.lowLatency),V,H,()=>this._retryCallback()).withTimeout($s).withRetryCount(ku).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(x,V)=>{q(y,H=>{if(!d())return;T=H;let W=!!T.lowLatency;W!==this.lowLatency&&b(W);let K=0;for(let oe=0;oe<T.dur.length;++oe)K+=T.dur[oe];K>0&&(Mi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(K/T.dur.length)),i({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,x(k(V))},()=>this._handleNetworkError())},nextChunk:L}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),Mi(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:y=>{let{videoElement:T,logger:R}=this.params,_=v(e.jidxUrl),w,B,F,O,k=0,L,q,$,x=()=>{L&&(clearTimeout(L),L=void 0);let A=Math.max(Pw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ue=k+A,ve=Z(),we=Math.min(1e4,ue-ve);k=ve;let ft=()=>{c||d()&&_.seek(()=>{d()&&(k=Z(),V(),x())})};we>0?L=window.setTimeout(()=>{this.paused?x():ft()},we):ft()},V=()=>{let A;for(;A=_.nextChunk(O);)O=A,Ct(A);let ue=_.nextChunk(F);if(ue){if(F&&ue.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?x():(I(),this._initPlayerWith(e));return}oe(ue)}else x()},H=(A,ue)=>{if(!d()||!this.sourceBuffer)return;let ve,we,ft,ar=mt=>{window.setTimeout(()=>{d()&&H(A,ue)},mt)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),ar(100);else{let mt=Z(),Dt=T.currentTime;!this.paused&&T.buffered.length>1&&q===Dt&&mt-$>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),q!==Dt&&(q=Dt,$=mt);let sr=this._getBufferSizeSec();if(sr>30)R(`Buffered ${sr} seconds; delaying appendBuffer`),ar(2e3);else try{this.sourceBuffer.appendBuffer(A),this.videoPlayStarted?(this.bufferStates.push({ts:mt,buf:sr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ue&&ue()}catch(zr){if(zr.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),ft=this.sourceBuffer.buffered.length,ft!==0&&(ve=this.sourceBuffer.buffered.start(0),we=Dt,we-ve>4&&this.sourceBuffer.remove(ve,we-3)),ar(1e3);else throw zr}}},W=()=>{B&&w&&(R([`Appending chunk, sz=${B.byteLength}:`,JSON.stringify(F)]),H(B,function(){B=null,V()}))},K=A=>e.fragUrlTemplate.replace("%%id%%",A.chunkIdx),oe=A=>{d()&&h(K(A),(ue,ve)=>{if(d()){if(ve/=1e3,B=ue,F=A,n=A.startTS,ve){let we=Math.min(10,A.dur/ve);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}W()}},()=>this._handleNetworkError())},Ct=A=>{d()&&(Mi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(K(A),!1)))},ht=A=>{d()&&(e.cachedHeader=A,H(A,()=>{w=!0,W()}))};s=!0,_.seek(A=>{if(d()){if(k=Z(),!A){x();return}O=A,!Tw(y)||A.startTS>y?oe(A):(F=A,V())}},y),e.cachedHeader?ht(e.cachedHeader):p(e.headerUrl,ht,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},l}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Rs(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,Mi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Rs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=Z();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,c=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Au(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&c(),h},notifySwitch:d=>{let p=Z();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Mr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout($s).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;be(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,c)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Iw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Aw,filter as Rb,fromEvent as ww,interval as kw,isHigher as Rw,isInvariantQuality as $w,isLower as Lw,merge as Mw,Subject as $b,Subscription as Cw}from"@vkontakte/videoplayer-shared";var Ru=class{constructor(){this.onDroopedVideoFramesLimit$=new $b;this.subscription=new Cw;this.playing=!1;this.tracks=[];this.forceChecker$=new $b;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!$w(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Rw(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(ww(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=kw(this.droppedFramesChecker.checkTime).pipe(Rb(()=>this.playing),Rb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(Aw(this.droppedFramesChecker.checkTime)),r=Mw(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>Lw(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Ls=Ru;import{map as Dw,Observable as Bw}from"@vkontakte/videoplayer-shared";import{fromEvent as Ow}from"@vkontakte/videoplayer-shared";var Di=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Vw=(a,e)=>new Bw(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Di()))},{...r,...e});i.observe(a);let s=Ow(document,"visibilitychange").pipe(Dw(n=>!document.hidden||Di())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Be=Vw;var Ww=["paused","playing","ready"],Yw=["paused","playing","ready"],Bi=class{constructor(e){this.subscription=new Hw;this.videoState=new M("stopped");this.representations$=new Lu([]);this.textTracksManager=new Ce;this.droppedFramesManager=new Ls;this.maxSeekBackTime$=new Lu(1/0);this.zeroTime$=new Lu(void 0);this.liveOffset=new at;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Cb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let c=(t=u.name)!=null?t:u.index.toString(10),l=(r=At(u.name))!=null?r:Gw(u.video),d=u.bitrate/1e3,p={...u.video};if(!l)continue;let h={id:c,quality:l,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),$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(Yw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Ww.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(te(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(te(this.params.source.url,u))}return;default:return Lb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Cb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Bb(this.videoState.stateChangeStarted$.pipe(Ms(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ms(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=de(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(X(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=fe(this.video);this.subscription.add(this.representations$.pipe(Ms(i=>i.map(({track:s})=>s)),Db(i=>!!i.length),qw()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Fw(),Ms(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(_w({zeroTime:this.zeroTime$.pipe(Db($u)),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(he(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Me(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&jw(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Lb(i.to)}},t)).add(Bb(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(Nw(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),pe(this.video)}createLiveDashPlayer(){let e=new Ci({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var c,l,d,p,h,f;let e=this.representations$.getValue(),t=(l=(c=this.params.desiredState.videoTrack.getTransition())==null?void 0:c.to)!=null?l:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&$u(t)?t:wt(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;Mb(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;Mb(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(te(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Ob=Bi;var Xe=(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 IR,assertNonNullable as ER,debounce as xR,ErrorCategory as ol,filter as uS,filterChanged as ul,fromEvent as PR,isNonNullable as AR,map as lS,merge as an,observableFrom as wR,observeElementSize as kR,once as cS,Subscription as RR,ValueSubject as $R}from"@vkontakte/videoplayer-shared";var Cs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Cr=class extends Cs{constructor(){super(),this.listeners||Cs.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Oi=class{constructor(){Object.defineProperty(this,"signal",{value:new Cr,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&&(Oi.prototype[Symbol.toStringTag]="AbortController",Cr.prototype[Symbol.toStringTag]="AbortSignal");function Ds(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Mu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Ds({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(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 Vi=Ds({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Vb=Vi?Mu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,nt=Vi?Vb.fetch:window.fetch,MB=Vi?Vb.Request:window.Request,ot=Vi?Oi:window.AbortController,CB=Vi?Cr:window.AbortSignal;var Kb=Fe(Lr(),1);var ut=()=>window.ManagedMediaSource||window.MediaSource,Bs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},_b=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Nb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as js,clientChecker as Hs}from"@vkontakte/videoplayer-shared";var Oe=document.createElement("video"),Kw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Jw='video/mp4; codecs="hev1.1.6.L93.B0"',Jb='video/webm; codecs="vp09.00.10.08"',Xb='video/webm; codecs="av01.0.00M.08"',Xw='audio/mp4; codecs="mp4a.40.2"',Zw='audio/webm; codecs="opus"',Fb,Ub,Qt={mms:Bs(),mse:_b(),hls:!!((Fb=Oe.canPlayType)!=null&&Fb.call(Oe,"application/x-mpegurl")||(Ub=Oe.canPlayType)!=null&&Ub.call(Oe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},qb,Hb,ge={mp4:!!((qb=Oe.canPlayType)!=null&&qb.call(Oe,"video/mp4")),webm:!!((Hb=Oe.canPlayType)!=null&&Hb.call(Oe,"video/webm")),cmaf:!0},Vs,jb,_s,Gb,Ns,Wb,Fs,Yb,Us,Qb,qs,zb,Se={h264:!!((jb=(Vs=ut())==null?void 0:Vs.isTypeSupported)!=null&&jb.call(Vs,Kw)),h265:!!((Gb=(_s=ut())==null?void 0:_s.isTypeSupported)!=null&&Gb.call(_s,Jw)),vp9:!!((Wb=(Ns=ut())==null?void 0:Ns.isTypeSupported)!=null&&Wb.call(Ns,Jb)),av1:!!((Yb=(Fs=ut())==null?void 0:Fs.isTypeSupported)!=null&&Yb.call(Fs,Xb)),aac:!!((Qb=(Us=ut())==null?void 0:Us.isTypeSupported)!=null&&Qb.call(Us,Xw)),opus:!!((zb=(qs=ut())==null?void 0:qs.isTypeSupported)!=null&&zb.call(qs,Zw))},Dr=(Se.h264||Se.h265)&&Se.aac,zt,ek=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Xb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Jb}})]);zt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{ek()}catch(a){console.error(a)}var Br=Qt.hls&&ge.mp4,Zb=()=>Object.keys(Se).filter(a=>Se[a]),eg=(a,e=!1,t=!1)=>{let r=Qt.mse||Qt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&ge.mp4&&Dr;case"DASH_WEBM":return r&&ge.webm&&Se.vp9&&Se.opus;case"DASH_WEBM_AV1":return r&&ge.webm&&Se.av1&&Se.opus;case"DASH_STREAMS":return r&&(ge.mp4&&Dr||ge.webm&&(Se.vp9||Se.av1)&&(Se.opus||Se.aac));case"DASH_LIVE":return Qt.mse&&ge.mp4&&Dr;case"DASH_LIVE_CMAF":return r&&ge.mp4&&Dr&&ge.cmaf;case"DASH_ONDEMAND":return r&&ge.mp4&&Dr;case"HLS":case"HLS_ONDEMAND":return Br||e&&Qt.mse&&ge.mp4&&Dr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Br;case"MPEG":return ge.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Qt.webrtc&&Qt.ws&&Se.h264&&(ge.mp4||ge.webm);default:return js(i)}})},Os=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:js(a)}return[e,t]},tg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Os(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Hs.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",...Os(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Os(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Os(a),...i,"HLS","HLS_ONDEMAND"];default:js(e)}return Br?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},rg=({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=Hs.isMac&&Hs.isSafari;if(Hs.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:js(a)}else Br&&!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"]},Cu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ig=a=>{if(a.size!==0){if(a.size===1)return a.values().next().value.split(".").at(0);for(let e of a){let t=(0,Kb.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 ag=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 Or=(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 il,assertNonNullable as rr,clientChecker as dR,combine as Xs,ErrorCategory as ct,filter as al,filterChanged as rS,flattenObject as fa,fromEvent as jr,getTraceSubscriptionMethod as pR,interval as sl,isNonNullable as iS,map as nl,merge as Gr,now as hR,Subject as aS,Subscription as sS,tap as fR,throttle as mR,ValueSubject as re}from"@vkontakte/videoplayer-shared";var qr=Fe(Lr(),1);var tk=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},rk=a=>window.clearTimeout(a),sg=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Du=sg?tk:window.requestIdleCallback,YB=sg?rk:window.cancelIdleCallback;var zg=Fe(xs(),1);import{assertNever as ik,ErrorCategory as ng,clientChecker as Bu,Subject as og}from"@vkontakte/videoplayer-shared";var ak=16,ug=!1;try{ug=Bu.isSafari&&!!Bu.macVersion&&Bu.macVersion<=ak}catch(a){console.error(a)}var Ou=class{constructor(e){this.bufferFull$=new og;this.error$=new og;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:ng.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;ug&&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:ng.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:ik(t)}}},lg=Ou;var Vu=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 Ur,assertNonNullable as Ve,ErrorCategory as Zt,fromEvent as Ju,getExponentialDelay as Xu,isNonNullable as Zu,isNullable as xe,now as Ys,once as tR,Subject as rR,Subscription as iR,ValueSubject as oa}from"@vkontakte/videoplayer-shared";var U=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 Vr=class extends U{};var Ni=class extends U{};var Fi=class extends U{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 Ui=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qi=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Hi=class extends U{constructor(e,t){super(e,t),this.data=this.content}};var z=class extends U{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Kt=class extends z{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 ji=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Wi=class extends z{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 Yi=class extends z{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Qi=class extends z{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 U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ki=class extends z{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 Ji=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xi=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Zi=class extends z{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ea=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ta=class extends z{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 ra=class extends z{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 ia=class extends z{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var nk={ftyp:Fi,moov:Ui,moof:qi,mdat:Hi,sidx:Kt,trak:ji,mdia:zi,mfhd:Zi,tkhd:Ki,traf:ea,tfhd:ta,tfdt:ra,trun:ia,minf:Ji,sv3d:Gi,st3d:Wi,prhd:Yi,proj:Xi,equi:Qi,uuid:Ni,unknown:Vr},Jt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=nk[e];return r?new r(t,new a):new Vr(t,new a)}};var _r=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var uk=new TextDecoder("ascii"),lk=a=>uk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",ck=a=>{let e=new Kt(a,new Jt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},dk=(a,e)=>{let r=new Jt().parse(a),i=new _r(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,d)},pk=(a,e)=>{let r=new Jt().parse(a),s=new _r(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((d,p)=>d+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},hk=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Jt().parse(a),i=new _r(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},cg={validateData:lk,parseInit:hk,getIndexRange:()=>{},parseSegments:ck,parseFeedableSegmentChunk:dk,getSegmentEndTime:pk};import{assertNonNullable as Nu,isNonNullable as fg,isNullable as mk}from"@vkontakte/videoplayer-shared";import{assertNever as fk}from"@vkontakte/videoplayer-shared";var dg={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"}},pg=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=aa(a,t),i=r in dg,s=i?dg[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=aa(u),d=c*2**((o-1)*8)+l,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},aa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ge=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return aa(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:fk(e)}},Xt=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=pg(r);if(!e(i))return;i.type==="master"&&Xt(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},hg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=pg(a);return Xt(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ge(o,n):s===17026?t=Ge(o,n):s===17029&&(r=Ge(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var mg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],bk=[231,22612,22743,167,171,163,160,175],gk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,c,l=!1,d=0;return Xt(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Ge(f,h);c=aa(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=Ge(f,h):p===17545?i=Ge(f,h):p===21420&&c===475249515?u=Ge(f,h):p===374648427?Xt(f,({tag:g,type:v,value:I})=>g===30321?(l=Ge(I,v)===1,!1):!0):s&&n&&mg.includes(p)&&(o=!0),!o}),Nu(e,"Failed to parse webm Segment start"),Nu(t,"Failed to parse webm Segment end"),Nu(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Sk=a=>{if(mk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},vk=(a,e)=>{let t=!1,r=!1,i=o=>fg(o.time)&&fg(o.position),s=[],n;return Xt(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=Ge(c,u));break;case 183:break;case 241:n&&(n.position=Ge(c,u));break;default:t&&mg.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:l}=o,d=s[u+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},yk=a=>{let e=0,t=!1;try{Xt(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):bk.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},bg={validateData:hg,parseInit:gk,getIndexRange:Sk,parseSegments:vk,parseFeedableSegmentChunk:yk};var Nr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return bg;case"mp4":return cg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Wu=Fe(_g(),1),Hg=Fe(Lr(),1);var Gu=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 Fg,isNullable as Ug}from"@vkontakte/videoplayer-shared";var Ng=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var qg=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},lt=(a,e)=>{let t=a;t=(0,Wu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Wu.default)(t,n,(o,u)=>Ug(s)?o:Ug(u)?s:s.padStart(parseInt(u,10),"0"))}return t},jg=(a,e)=>{var T,R,_,w,B,F,O,k,L,q,$,x,V,H,W,K,oe,Ct,ht,A,ue,ve,we,ft,ar,mt,Dt,sr,zr,xl,Pl,Al,wl,kl,Rl,$l,Ll,Ml,Cl,Dl,Bl,Ol,Vl,_l,Nl,Fl,Ul,ql,Hl,jl,Gl,Wl,Yl,Ql,zl,Kl,Jl,Xl;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(ee=>{var ka,bt;return(bt=(ka=ee.textContent)==null?void 0:ka.trim())!=null?bt:""}),u=(T=(0,Hg.default)(o,0))!=null?T:"",c=n.children,l=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),p=d?new Date(d).getTime():void 0,h,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],v=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)h=qg(f);else if(b){let ee=qg(b);Fg(ee)&&(h=ee)}else v&&(h=parseInt(v,10));let I=0,S=(_=(R=s.getAttribute("profiles"))==null?void 0:R.split(","))!=null?_:[];for(let ee of c){let ka=(w=ee.getAttribute("id"))!=null?w:"id"+(I++).toString(10),bt=(B=ee.getAttribute("mimeType"))!=null?B:"",vn=(F=ee.getAttribute("codecs"))!=null?F:"",yn=(O=ee.getAttribute("contentType"))!=null?O:bt==null?void 0:bt.split("/")[0],tv=(L=(k=ee.getAttribute("profiles"))==null?void 0:k.split(","))!=null?L:[],rv=(q=ee.getAttribute("lang"))!=null?q:void 0,iv=(V=(x=($=ee.querySelector("Label"))==null?void 0:$.textContent)==null?void 0:x.trim())!=null?V:void 0,av=ee.querySelectorAll("Representation"),sv=ee.querySelector("SegmentTemplate"),nv=(W=(H=ee.querySelector("Role"))==null?void 0:H.getAttribute("value"))!=null?W:void 0,Kr=yn,J={id:ka,language:rv,isDefault:nv==="main",label:iv,codecs:vn,hdr:Kr==="video"&&Gu(vn),mime:bt,representations:[]};for(let G of av){let ov=(K=G.getAttribute("lang"))!=null?K:void 0,uv=(oe=G.getAttribute("label"))!=null?oe:void 0,lv=(A=(ht=(Ct=G.querySelector("BaseURL"))==null?void 0:Ct.textContent)==null?void 0:ht.trim())!=null?A:"",Ra=new URL(lv||u,e).toString(),nr=(ue=G.getAttribute("mimeType"))!=null?ue:bt,$a=(we=(ve=G.getAttribute("codecs"))!=null?ve:vn)!=null?we:"",La;if(yn==="text"){let gt=G.getAttribute("id")||"",Ma=gt.includes("_auto"),Bt=G.querySelector("SegmentTemplate");if(Bt){let Jr={representationId:(ft=G.getAttribute("id"))!=null?ft:void 0,bandwidth:(ar=G.getAttribute("bandwidth"))!=null?ar:void 0},Ca=parseInt((mt=G.getAttribute("bandwidth"))!=null?mt:"",10)/1e3,Da=(sr=parseInt((Dt=Bt.getAttribute("startNumber"))!=null?Dt:"",10))!=null?sr:1,or=parseInt((zr=Bt.getAttribute("timescale"))!=null?zr:"",10),Tn=(xl=Bt.querySelectorAll("SegmentTimeline S"))!=null?xl:[],ur=Bt.getAttribute("media");if(!ur)continue;let Ba=[],Oa=0,Va="",lr=0,Xr=Da,ie=0;for(let _e of Tn){let Ot=parseInt((Pl=_e.getAttribute("d"))!=null?Pl:"",10),ke=parseInt((Al=_e.getAttribute("r"))!=null?Al:"",10)||0,St=parseInt((wl=_e.getAttribute("t"))!=null?wl:"",10);ie=Number.isFinite(St)?St:ie;let Vt=Ot/or*1e3,vt=ie/or*1e3;for(let Ye=0;Ye<ke+1;Ye++){let yt=lt(ur,{...Jr,segmentNumber:Xr.toString(10),segmentTime:(ie+Ye*Ot).toString(10)}),cr=(vt!=null?vt:0)+Ye*Vt,ei=cr+Vt;Xr++,Ba.push({time:{from:cr,to:ei},url:yt})}ie+=(ke+1)*Ot,Oa+=(ke+1)*Vt}lr=ie/or*1e3,Va=lt(ur,{...Jr,segmentNumber:Xr.toString(10),segmentTime:ie.toString(10)});let Zr={time:{from:lr,to:1/0},url:Va},Ze={type:"template",baseUrl:Ra,segmentTemplateUrl:ur,initUrl:"",totalSegmentsDurationMs:Oa,segments:Ba,nextSegmentBeyondManifest:Zr,timescale:or};La={id:gt,kind:"text",segmentReference:Ze,profiles:[],duration:h,bitrate:Ca,mime:"",codecs:"",width:0,height:0,isAuto:Ma}}else La={id:gt,isAuto:Ma,kind:"text",url:Ra}}else{let gt=(Rl=(kl=G.getAttribute("contentType"))!=null?kl:nr==null?void 0:nr.split("/")[0])!=null?Rl:yn,Ma=(Ll=($l=ee.getAttribute("profiles"))==null?void 0:$l.split(","))!=null?Ll:[],Bt=parseInt((Ml=G.getAttribute("width"))!=null?Ml:"",10),Jr=parseInt((Cl=G.getAttribute("height"))!=null?Cl:"",10),Ca=parseInt((Dl=G.getAttribute("bandwidth"))!=null?Dl:"",10)/1e3,Da=(Bl=G.getAttribute("frameRate"))!=null?Bl:"",or=(Ol=G.getAttribute("quality"))!=null?Ol:void 0,Tn=Da?Ng(Da):void 0,ur=(Vl=G.getAttribute("id"))!=null?Vl:"id"+(I++).toString(10),Ba=gt==="video"?`${Jr}p`:gt==="audio"?`${Ca}Kbps`:$a,Oa=`${ur}@${Ba}`,Va=[...S,...tv,...Ma],lr,Xr=G.querySelector("SegmentBase"),ie=(_l=G.querySelector("SegmentTemplate"))!=null?_l:sv;if(Xr){let Ze=(Fl=(Nl=G.querySelector("SegmentBase Initialization"))==null?void 0:Nl.getAttribute("range"))!=null?Fl:"",[_e,Ot]=Ze.split("-").map(yt=>parseInt(yt,10)),ke={from:_e,to:Ot},St=(Ul=G.querySelector("SegmentBase"))==null?void 0:Ul.getAttribute("indexRange"),[Vt,vt]=St?St.split("-").map(yt=>parseInt(yt,10)):[],Ye=St?{from:Vt,to:vt}:void 0;lr={type:"byteRange",url:Ra,initRange:ke,indexRange:Ye}}else if(ie){let Ze={representationId:(ql=G.getAttribute("id"))!=null?ql:void 0,bandwidth:(Hl=G.getAttribute("bandwidth"))!=null?Hl:void 0},_e=parseInt((jl=ie.getAttribute("timescale"))!=null?jl:"",10),Ot=(Gl=ie.getAttribute("initialization"))!=null?Gl:"",ke=ie.getAttribute("media"),St=(Yl=parseInt((Wl=ie.getAttribute("startNumber"))!=null?Wl:"",10))!=null?Yl:1,Vt=lt(Ot,Ze);if(!ke)throw new ReferenceError("No media attribute in SegmentTemplate");let vt=(Ql=ie.querySelectorAll("SegmentTimeline S"))!=null?Ql:[],Ye=[],yt=0,cr="",ei=0;if(vt.length){let _a=St,Ne=0;for(let dr of vt){let Qe=parseInt((zl=dr.getAttribute("d"))!=null?zl:"",10),_t=parseInt((Kl=dr.getAttribute("r"))!=null?Kl:"",10)||0,Na=parseInt((Jl=dr.getAttribute("t"))!=null?Jl:"",10);Ne=Number.isFinite(Na)?Na:Ne;let In=Qe/_e*1e3,En=Ne/_e*1e3;for(let Fa=0;Fa<_t+1;Fa++){let dv=lt(ke,{...Ze,segmentNumber:_a.toString(10),segmentTime:(Ne+Fa*Qe).toString(10)}),Zl=(En!=null?En:0)+Fa*In,pv=Zl+In;_a++,Ye.push({time:{from:Zl,to:pv},url:dv})}Ne+=(_t+1)*Qe,yt+=(_t+1)*In}ei=Ne/_e*1e3,cr=lt(ke,{...Ze,segmentNumber:_a.toString(10),segmentTime:Ne.toString(10)})}else if(Fg(h)){let Ne=parseInt((Xl=ie.getAttribute("duration"))!=null?Xl:"",10)/_e*1e3,dr=Math.ceil(h/Ne),Qe=0;for(let _t=1;_t<dr;_t++){let Na=lt(ke,{...Ze,segmentNumber:_t.toString(10),segmentTime:Qe.toString(10)});Ye.push({time:{from:Qe,to:Qe+Ne},url:Na}),Qe+=Ne}ei=Qe,cr=lt(ke,{...Ze,segmentNumber:dr.toString(10),segmentTime:Qe.toString(10)})}let cv={time:{from:ei,to:1/0},url:cr};lr={type:"template",baseUrl:Ra,segmentTemplateUrl:ke,initUrl:Vt,totalSegmentsDurationMs:yt,segments:Ye,nextSegmentBeyondManifest:cv,timescale:_e}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!gt||!nr)continue;let Zr={video:"video",audio:"audio",text:"text"}[gt];if(!Zr)continue;Kr||(Kr=Zr),La={id:Oa,kind:Zr,segmentReference:lr,profiles:Va,duration:h,bitrate:Ca,mime:nr,codecs:$a,width:Bt,height:Jr,fps:Tn,quality:or}}J.language||(J.language=ov),J.label||(J.label=uv),J.mime||(J.mime=nr),J.codecs||(J.codecs=$a),J.hdr||(J.hdr=Kr==="video"&&Gu($a)),J.representations.push(La)}Kr&&i[Kr].push(J)}return{dynamic:l,liveAvailabilityStartTime:p,duration:h,streams:i,failoverUrls:o}};var sa=Fe(Lr(),1);import{videoSizeToQuality as eR}from"@vkontakte/videoplayer-shared";var Gg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?At(s):void 0)!=null?o:eR({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},Wg=({id:a,bitrate:e})=>({id:a,bitrate:e}),Gs=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,sa.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,sa.default)(t,-1)},Yg=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Qg=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),zu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,sa.default)(r.split("."),0),isDefault:i}),Ku=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,sa.default)(i.split("."),0)}),Ws=a=>"url"in a,Ee=a=>a.type==="template",na=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ua=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new oa(0);this.onLastSegment$=new oa(!1);this.fullyBuffered$=new oa(!1);this.playingRepresentation$=new oa(void 0);this.playingRepresentationInit$=new oa(void 0);this.error$=new rR;this.gaps=[];this.subscription=new iR;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ot;this.destroyAbortController=new ot;this.bufferLimit=1/0;this.failedDownloads=0;this.failoverUrls=[];this.failoverUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Ur(this.destroyAbortController.signal,async function*(e){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 lg(this.sourceBuffer),this.subscription.add(Ju(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Zt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Zt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Ju(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Zt.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,Vu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=Xe(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=Ur(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Ve(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(xe(s)||xe(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();Zu(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Ur(this.destroyAbortController.signal,async function*(e){var u,c;let t=(u=e==null?void 0:e.flatMap(l=>l.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let d=t.find(f=>f.id===l);d&&this.representations.set(l,d);let p=this.representations.get(l);if(!p||!Ee(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));var l;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.failoverUrls=(l=c==null?void 0:c.failoverUrls)!=null?l:[],this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ot,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;if(xe(e)||xe(this.downloadingRepresentationId)||xe(this.playingRepresentationId)||xe(this.sourceBuffer)||!xe(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=Xe(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)&&Vu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Xe(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,qr.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&&Xe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,qr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;Zu(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||!Ee(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),c=(i=this.segments.get(o.id))!=null?i:[],l=(n=(s=(0,qr.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(!Ee(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=lt(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,v=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&I&&this.sourceBuffer&&!(Or(this.sourceBuffer.buffered,p)&&Or(this.sourceBuffer.buffered,h)))&&g&&I});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=c||o<=l);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){Ee(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ur(o,async function*(){let l=Xu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Ys(),!l)return;let d=new DataView(l);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=Nr(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),na(l)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.failoverUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.failoverUrlsIndex=(this.failoverUrlsIndex+1)%this.failoverUrls.length;let e=this.failoverUrls[this.failoverUrlsIndex];for(let t of this.representations.values())Ee(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ur(n,async function*(){let u=Xu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),Ju(window,"online").pipe(tR()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=Ys(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),na(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ee(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,qr.default)(e,0).byte.from,to:(0,qr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ys(),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:Zt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ee(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{this.lastDataObtainedTimestampMs=Ys();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:Zt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=Nr(n.mime).parseFeedableSegmentChunk(c,this.isLive);l!=null&&l.byteLength&&(u.status="partially_fed",o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,c=e.byteLength;for(let l of this.activeSegments){let{segment:d}=l,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:c;if(l.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,g=p?d.byte.to-r:e.byteLength,v=b<i,I=g<=i;if(d.status==="downloading"&&v&&I){d.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+b,h),y=this.getCurrentPosition();Zu(y)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-y,this.bufferAccumulation.accumulated.push({segmentView:S,segmentProgress:l}),this.activeSegments.delete(l));let T=({segmentView:R,segmentProgress:_})=>this.sourceBufferTaskQueue.append(R,s).then(w=>w&&!s.aborted?this.onSegmentFullyAppended(_,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(T),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||xe(y))&&(T({segmentView:S,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&!I&&(l.loadedBytes=Math.min(h,i-b),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+b+l.feedingBytes,l.loadedBytes-l.feedingBytes),y=l.loadedBytes===h?S:Nr(o.mime).parseFeedableSegmentChunk(S);y!=null&&y.byteLength&&(d.status="partially_fed",l.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(T=>{if(s.aborted)n();else if(T)l.fedBytes+=y.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let l=c.byte.from-r,d=c.byte.to-r,p=d-l+1,h=l<i,f=d<=i;if(h){if(c.status==="downloading"&&f){c.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+l,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-l),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+l+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?b:Nr(o.mime).parseFeedableSegmentChunk(b);g!=null&&g.byteLength&&(c.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ws(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=Du(()=>(0,zg.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Ur(this.destroyAbortController.signal,async function*(){let o=Xu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Nr(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:c,segments:l}=o,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d);let p=l;this.isLive&&Ee(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:Zt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||xe(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((l,d)=>l.from-d.from);let c=[u[0]];for(let l=1;l<u.length;l++){let{from:d,to:p}=u[l],h=c[c.length-1];h.to>=d?h.to=Math.max(h.to,p):c.push(u[l])}return c},o=u=>{var l;if(s>=t)return i;i.push({...u.time}),i=n(i);let c=Ws(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?(await Promise.all(i.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||xe(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=Ws(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)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||xe(e)?0:Xe(this.sourceBuffer.buffered,e)}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=Du(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Zt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(xe(this.sourceBuffer)||xe(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(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 la=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Kg=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as ca,assertNever as Jg,fromEvent as Xg,merge as aR,now as da,Subscription as sR,ValueSubject as el,flattenObject as Hr}from"@vkontakte/videoplayer-shared";var Qs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new el(void 0);this.lastConnectionReused$=new el(void 0);this.lastRequestFirstBytes$=new el(void 0);this.abortAllController=new ot;this.subscription=new sR;this.fetchManifest=ca(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=la(r));let i=yield nt(r,{signal:this.abortAllController.signal}).catch(pa);return i?(t.log("success",Hr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Hr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ca(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var O,k;let c=e,l=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{l.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(c,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),c=L.toString();break}default:Jg(t)}this.requestQuic&&(c=la(c));let p=this.abortAllController.signal,h;if(n){let L=new ot;if(h=aR(Xg(this.abortAllController.signal,"abort"),Xg(n,"abort")).subscribe(()=>{try{L.abort()}catch(q){pa(q)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(q){pa(q)}p=L.signal}let f=da();d.log("startRequest",Hr({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield nt(c,{priority:s,headers:l,signal:p}).catch(pa),g=da();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(g-f),!b.ok||!b.body){h==null||h.unsubscribe();let L=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:L}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){h==null||h.unsubscribe();let L=da(),q={requestStartedAt:f,requestEndedAt:L,duration:L-f};return d.log("endRequest",Hr(q)),d.end(),b.arrayBuffer()}let[v,I]=b.body.tee(),S=v.getReader();o&&((k=this.throughputEstimator)==null||k.trackStream(I,u));let y=0,T=new Uint8Array(0),R=!1,_=L=>{h==null||h.unsubscribe(),R=!0,pa(L)},w=ca(p,async function*({done:L,value:q}){if(y===0&&this.lastRequestFirstBytes$.next(da()-f),p.aborted){h==null||h.unsubscribe();return}if(!L&&q){let $=new Uint8Array(T.length+q.length);$.set(T),$.set(q,T.length),T=$,y+=q.byteLength,i==null||i(new DataView(T.buffer),y),yield S==null?void 0:S.read().then(w,_)}}.bind(this));yield S==null?void 0:S.read().then(w,_),h==null||h.unsubscribe();let B=da(),F={failed:R,requestStartedAt:f,requestEndedAt:B,duration:B-f};return R?(d.error("endRequest",Hr(F)),d.end(),null):(d.log("endRequest",Hr(F)),d.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=ca(this.abortAllController.signal,async function*(e,t,r){var v;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=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let I=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!I)return null;b=new DataView(I)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=ca(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=Kg(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Jg(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},pa=a=>{if(!na(a))throw a};var er=(a,e,t)=>t*e+(1-t)*a,tl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Zg=(a,e,t,r)=>{let i=0,s=t,n=tl(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as nR,ValueSubject as eS}from"@vkontakte/videoplayer-shared";var kt=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 eS(e.initial),this.debounced$=new eS(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new se(`raw_${t}`),this.smoothedSeries$=new se(`smoothed_${t}`),this.reportedSeries$=new se(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(nR(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var zs=class extends kt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=er(this.slow,e,this.params.emaAlphaSlow),this.fast=er(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ks=class extends kt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=tl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=er(this.emaSmoothed,e,this.params.emaAlpha);let r=Zg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Js=class extends kt{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?er(this.smoothed,t,this.params.emaAlpha):t}};var tr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new zs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Ks({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Js({initial:e,label:"liveEdgeDelay",...t})}};var rl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as oR,ValueSubject as uR}from"@vkontakte/videoplayer-shared";var ha=class a{constructor(e,t){this.currentRepresentation$=new uR(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!oR(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let c=s.segments.find(l=>l.time.from<=e&&l.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ee(t.segmentReference))}};var bR=["timeupdate","progress","play","seeked","stalled","waiting"],gR=["timeupdate","progress","loadeddata","playing","seeked"];var Zs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new sS;this.representationSubscription=new sS;this.state$=new M("none");this.currentVideoRepresentation$=new re(void 0);this.currentVideoRepresentationInit$=new re(void 0);this.currentAudioRepresentation$=new re(void 0);this.currentVideoSegmentLength$=new re(0);this.currentAudioSegmentLength$=new re(0);this.error$=new aS;this.lastConnectionType$=new re(void 0);this.lastConnectionReused$=new re(void 0);this.lastRequestFirstBytes$=new re(void 0);this.currentLiveTextRepresentation$=new re(null);this.isLive$=new re(!1);this.liveDuration$=new re(0);this.liveAvailabilityStartTime$=new re(void 0);this.bufferLength$=new re(0);this.liveLoadBufferLength$=new re(0);this.livePositionFromPlayer$=new re(0);this.isActiveLowLatency$=new re(!1);this.timeInWaiting=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new aS;this.gapWatchdogActive=!1;this.destroyController=new ot;this.initManifest=il(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=te(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:ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=il(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=jg(e!=null?e:"",this.manifestUrlString)}catch(u){let c=(n=ag(e))!=null?n:{id:"ManifestParsing",category:ct.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=ut())==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=ig(d);if(p&&(i[u]=l.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);dR.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",fa(s)),s}.bind(this));this.initRepresentations=il(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",fa({initialVideo:e,initialAudio:t,sourceHls:r})),rr(this.manifest),rr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(jr(p,"error").pipe(al(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Nb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Bs())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 ua("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],iS(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new ua("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(ha.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new ha(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(sl(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=hu(this.manifestUrlString,2);this.manifestUrlString=te(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Gr(...gR.map(p=>jr(this.element,p))).pipe(nl(p=>this.element?Xe(this.element.buffered,this.element.currentTime*1e3):0),rS(),fR(p=>{var h;p>this.tuning.dash.bufferEmptinessTolerance&&((h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(rS()).subscribe(h=>rl(this.element,1))),this.representationSubscription.add(Xs({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(al(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(Xs({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,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b,S=1;Math.abs(I)>g&&(S=1+Math.sign(I)*v),rl(this.element,S)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let v=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(S=>{var y,T;return(T=(y=S.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?T:v}))-v}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(Xs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(mR(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(rr(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=hu(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,T=isFinite(h)?h:f,R=this.isActiveLowLatency$.getValue(),_=v<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(R&&_);let w="none";if(R?w="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&_?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),w="active_low_latency"):g!==0&&T<I?w="live_forward_buffering":T<I+y&&(w="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let B=p-(I+S),F=this.normolizeLiveOffset(Math.trunc(g+B/b)),O=Math.abs(F-g),k;!h||O<=this.tuning.dashCmafLive.offsetCalculationError?k=g:F>0&&O>this.tuning.dashCmafLive.offsetCalculationError?k=F:k=0,this.manifestUrlString=te(this.manifestUrlString,k,2)}w!=="none"&&w!=="active_low_latency"&&(p=0,this.updateLive())}))}let u=Gr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(nl(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Gr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(nl(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Gr(this.forceEnded$,Xs({allBuffersFull:u,someBufferEnded:c}).pipe(al(({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:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Gr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let l=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),Ee(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/1e3,this.audioBufferManager&&iS(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=sl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:ct.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 Qs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=tr.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;rr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=te(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){rr(this.element),this.state$.setState("running"),this.subscription.add(Gr(...bR.map(e=>jr(this.element,e)),jr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(jr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(jr(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Or(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var f,b,g,v,I,S,y,T,R,_;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting},n=hR(),o=100,u=(b=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?b:0,c=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(S=(I=this.videoBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?S:0,d=(T=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?T:0,p=l<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=d<o&&n-c>this.tuning.dash.crashOnStallTWithoutDataTimeout;if(this.tuning.useNewProviderReinitLogic&&(p||h)||this.tuning.useNewProviderReinitLogic&&this.timeInWaiting>=2*this.tuning.dash.crashOnStallTimeout||!this.tuning.useNewProviderReinitLogic&&this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s={...s,liveLastSeekOffset:this.liveLastSeekOffset};else{let w=this.element.currentTime*1e3;(R=this.videoBufferManager)==null||R.maintain(w),(_=this.audioBufferManager)==null||_.maintain(w),s={...s,position:w}}this.tracer.log("stallIntervalCallback",fa(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=sl(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:this.tuning.useNewProviderReinitLogic?ct.NETWORK:ct.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u,c;rr(this.element),rr(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),Or(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",fa({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=pR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await 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={...t,gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",fa(t)))}}};var en=class{constructor(e,t){this.fov=e,this.orientation=t}};var tn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var nS=`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
|
|
69
|
+
`;var oS=`#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 tn=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 Zs(this.params.fov,this.params.orientation),this.cameraRotationManager=new en(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(sS,this.gl.VERTEX_SHADER),r=this.createShader(nS,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 rr=class{constructor(e){this.subscription=new RR;this.videoState=new M("stopped");this.elementSize$=new $R(void 0);this.textTracksManager=new Me;this.droppedFramesManager=new $s;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ki;this.audioTrackSwitchHistory=new ki;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 IR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new tn(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=de(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(X(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 Xs({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=fe(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:nc.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(){var l;let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(oS(c=>!!c.length),cS()).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(oS(AR),cS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(uS(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(he(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Le(this.video,t.playbackRate,r.playbackRateState$,i)),s(kR(this.video),this.elementSize$),s(De(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(ER(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(Qu(f));let b=[];for(let g of f.representations){let v=Gg(g);b.push(v),this.audioTracksMap.set(v,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(zu(h));let f=[];for(let b of h.representations){let g=jg(b);g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}if(this.params.output.availableVideoStreams$.next(p),this.textTracksManager)for(let h of d.text)for(let f of h.representations){let b=Wg(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=c=>e.error$.next({id:"RepresentationSwitch",category:nc.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(rn(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$,PR(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,f]=p,b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),c==="manifest_ready")this.player.initRepresentations(h.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(n),f){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,g).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(oc()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(zu(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(oc()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Qu(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),(l=this.textTracksManager)==null||l.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(uS(({to:c})=>c==="ready"),oc());this.subscription.add(rn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(rn(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=rn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,wR(["init"])).pipe(xR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var R,_,w,B,F,O,k,L,U,$,x,V,H,W,K,ne,Mt,ht;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(R=e.videoTrack.getState())==null?void 0:R.id,n=[...this.videoTracksMap.keys()].find(({id:A})=>A===i),o=t.currentVideoTrack$.getValue(),u=((B=(w=e.videoStream.getState())!=null?w:n&&((_=this.videoTracksMap.get(n))==null?void 0:_.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:A})=>A===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Xe(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=(F=e.audioStream.getState())!=null?F:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(O=[...this.audioStreamsMap.keys()].find(({id:A})=>A===(f==null?void 0:f.id)))!=null?O:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let A=As(n,c,(k=this.audioStreamsMap.get(b))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(L=A==null?void 0:A.bitrate)!=null?L:-1/0)}else{let A=js(n,c,(U=this.audioStreamsMap.get(b))!=null?U:[]);g=Math.max(g,($=A==null?void 0:A.bitrate)!=null?$:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let A=As(o,c,(x=this.audioStreamsMap.get(b))!=null?x:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(V=A==null?void 0:A.bitrate)!=null?V:-1/0)}else{let A=js(o,c,(H=this.audioStreamsMap.get(b))!=null?H:[]);g=Math.max(g,(W=A==null?void 0:A.bitrate)!=null?W:-1/0)}}let v=At(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}),I=r?v!=null?v:n:n!=null?n:v,S;this.params.tuning.useSeparateAudioVideoABR?S=b&&Pb(I,c,(K=this.audioStreamsMap.get(b))!=null?K:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):S=b&&js(I,c,(ne=this.audioStreamsMap.get(b))!=null?ne:[]);let y=(Mt=this.videoTracksMap.get(I))==null?void 0:Mt.representation,T=S&&((ht=this.audioTracksMap.get(S))==null?void 0:ht.representation);if(y&&T)return[y,T];if(y&&!T&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){be(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:nc.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),pe(this.video),this.tracer.end()}};var ma=class extends rr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as lS,interval as LR,map as MR}from"@vkontakte/videoplayer-shared";var ba=class extends rr{constructor(e){super(e),this.liveOffset=new at,this.textTracksManager=null}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(lS({interval:LR(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(lS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(MR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(i=>{if(i){let s=Yg(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 pS=Qe(Es(),1);import{assertNever as ga,assertNonNullable as dS,debounce as CR,ErrorCategory as an,filter as DR,isNonNullable as BR,isNullable as OR,map as sn,merge as VR,Observable as _R,observableFrom as NR,Subscription as FR,videoSizeToQuality as qR}from"@vkontakte/videoplayer-shared";var Ge={};var jr=(a,e)=>new _R(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Sa=class{constructor(e){this.subscription=new FR;this.videoState=new M("initializing");this.textTracksManager=new Me;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:ga(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ga(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ga(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:ga(e)}break;default:ga(t)}};this.video=de(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(X(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),pe(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:an.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,pS.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(){dS(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(){dS(Ge.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:an.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=fe(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(Ke(this.video,e.isLooped,r)),this.subscription.add(he(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Le(this.video,e.playbackRate,i.playbackRateState$,r)),s(De(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(sn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(jr(this.hls,Ge.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:an.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(jr(this.hls,Ge.Events.MANIFEST_PARSED).pipe(sn(({levels:l})=>l.reduce((c,d)=>{var I,S;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(S=Pt((I=d.attrs.QUALITY)!=null?I:""))!=null?S:qR({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(jr(this.hls,Ge.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(jr(this.hls,Ge.Events.LEVEL_LOADING).pipe(sn(({url:l})=>X(l))),t.hostname$),s(jr(this.hls,Ge.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(It(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=jr(this.hls,Ge.Events.LEVEL_SWITCHED).pipe(sn(({level:l})=>n(this.hls.levels[l])));o.pipe(DR(BR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(It(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(OR(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=VR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,NR(["init"])).pipe(CR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await be(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:an.DOM,thrown:t}))||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0)}};var hS="X-Playback-Duration",uc=async a=>{var i;let e=await nt(a),t=await e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(hS)?parseInt(e.headers.get(hS),10):void 0};import{assertNever as YR,combine as QR,debounce as zR,ErrorCategory as on,filter as KR,filterChanged as JR,isNonNullable as mS,isNullable as un,map as bS,merge as XR,observableFrom as ZR,Subscription as e$,ValueSubject as dc,VideoQuality as t$}from"@vkontakte/videoplayer-shared";var lc=Qe(wo(),1);import{videoSizeToQuality as UR,getExponentialDelay as HR}from"@vkontakte/videoplayer-shared";var jR=a=>{let e=null;if(a.QUALITY&&(e=Pt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=UR({width:t,height:r})}return e!=null?e:null},GR=(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,lc.default)(l[1].split(",").map(I=>I.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=jR(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[I,S]=d.RESOLUTION.split("x").map(y=>parseInt(y,10));I&&S&&(g={width:I,height:S})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:f,size:g,fps:b})}if(c){let d=(0,lc.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}},WR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),cc=0,fS=async(a,e=a,t)=>{let i=await(await nt(a)).text();cc+=1;try{let{qualityManifests:s,textTracks:n}=GR(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(cc<=t.manifestRetryMaxCount)return await WR(HR(cc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),fS(a,e,t)}return{qualityManifests:[],textTracks:[]}},nn=fS;var va=class{constructor(e){this.subscription=new e$;this.videoState=new M("stopped");this.textTracksManager=new Me;this.manifests$=new dc([]);this.liveOffset=new at;this.manifestStartTime$=new dc(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 YR(t)}};var t;this.params=e,this.video=de(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:t$.INVARIANT,url:this.params.source.url},nn(ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:on.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:on.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(X(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new dc((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:on.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=fe(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(he(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Le(this.video,t.playbackRate,i.playbackRateState$,r)),s(De(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(JR(),bS(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&&mS(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(X(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(QR({startTime:this.manifestStartTime$.pipe(KR(mS)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(bS(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=XR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ZR(["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),pe(this.video)}prepare(){var o,u;let e=this.selectManifest();if(un(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=ee(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),uc(n).then(l=>{var c;if(!un(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(un(d)||!isFinite(d))try{nt(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();uc(b).then(g=>{un(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:on.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 r$,debounce as i$,ErrorCategory as pc,fromEvent as hc,isNonNullable as a$,isNullable as s$,map as gS,merge as SS,observableFrom as vS,Subscription as n$,ValueSubject as o$,VideoQuality as u$,clientChecker as c$}from"@vkontakte/videoplayer-shared";var ya=class{constructor(e){this.subscription=new n$;this.videoState=new M("stopped");this.textTracksManager=new Me;this.manifests$=new o$([]);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 r$(t)}};this.params=e,this.video=de(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:u$.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(X(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),nn(ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:pc.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:pc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=fe(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(gS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ke(this.video,t.isLooped,r)),this.subscription.add(he(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Le(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&a$(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(X(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}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(gS(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)),!c$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(SS(hc(o,"addtrack"),hc(o,"removetrack"),hc(o,"change"),vS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=SS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,vS(["init"])).pipe(i$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),pe(this.video)}prepare(){var s,n;let e=this.selectManifest();if(s$(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as l$,assertNonNullable as yS,debounce as d$,ErrorCategory as TS,isHigher as p$,isHigherOrEqual as h$,isInvariantQuality as IS,isLowerOrEqual as f$,isNonNullable as m$,merge as b$,observableFrom as g$,Subscription as S$,map as v$}from"@vkontakte/videoplayer-shared";var Ta=class{constructor(e){this.subscription=new S$;this.videoState=new M("stopped");this.trackUrls={};this.textTracksManager=new Me;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return l$(e)}};this.params=e,this.video=de(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:TS.WTF,message:"MpegProvider internal logic error",thrown:o})},i=fe(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(v$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ke(this.video,t.isLooped,r)),this.subscription.add(he(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Le(this.video,t.playbackRate,i.playbackRateState$,r)),s(De(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&m$(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=b$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,g$(["init"])).pipe(d$(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),pe(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;yS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];yS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ua(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(X(t))}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:TS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!IS(d.track.quality)&&f$(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&&h$(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!IS(h.track.quality)&&p$(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=At(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 xS,debounce as E$,merge as PS,observableFrom as x$,Subscription as P$,map as AS,ValueSubject as A$,ErrorCategory as mc,VideoQuality as w$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as y$}from"@vkontakte/videoplayer-shared";var ES=["stun:videostun.mycdn.me:80"],T$=1e3,I$=3,fc=()=>null,cn=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=fc;this.externalStopCallback=fc;this.externalErrorCallback=fc;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:ES}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:y$.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),T$)}normalizeOptions(e={}){let t={stunServerList:ES,maxRetryNumber:I$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ia=class{constructor(e){this.videoState=new M("stopped");this.maxSeekBackTime$=new A$(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 xS(e)}};this.subscription=new P$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=de(e.container,e.tuning),this.liveStreamClient=new cn(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),pe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:mc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};PS(this.videoState.stateChangeStarted$.pipe(AS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(AS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=fe(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(De(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(he(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 xS(n.to)}},r)).add(PS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,x$(["init"])).pipe(E$(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(X(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:w$.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:mc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:mc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ea=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 Aa,assertNonNullable as kt,ErrorCategory as dn,filter as D$,isNonNullable as MS,isNullable as B$,map as O$,merge as V$,once as _$,Subject as xe,Subscription as CS,ValueSubject as C,flattenObject as DS}from"@vkontakte/videoplayer-shared";import{Observable as k$,map as wS,Subscription as R$,Subject as $$}from"@vkontakte/videoplayer-shared";var kS=a=>new k$(e=>{let t=new R$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(wS(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(wS(({type:l})=>l!==void 0)),n=new $$,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 RS,Subscription as L$,combine as M$,filter as $S,once as LS}from"@vkontakte/videoplayer-shared";var xa=null,ln=null;function bc(){return xa||(xa=new(window.AudioContext||window.webkitAudioContext)),ln||(ln=new GainNode(xa,{gain:1}),ln.connect(xa.destination)),{audioCtx:xa,gainNode:ln}}import{clientChecker as C$}from"@vkontakte/videoplayer-shared";var Gr=class Gr{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new L$;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe($S(n=>!!n.type),LS()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){C$.isSafari&&e!=="MPEG"||this.subscriptions.add(M$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe($S(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),LS()).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}=bc(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Gr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Gr.errorId,category:RS.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:Gr.errorId,category:RS.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=bc();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Gr.errorId="VolumeMultiplierManager";var Pa=Gr;var N$={chunkDuration:5e3,maxParallelRequests:5},wa=class{constructor(e){this.current$=new C({type:void 0});this.providerError$=new xe;this.noAvailableProvidersError$=new xe;this.volumeMultiplierError$=new xe;this.providerOutput={position$:new C(0),duration$:new C(1/0),volume$:new C({muted:!1,volume:1}),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableVideoTracks$:new C([]),currentVideoTrack$:new C(void 0),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0),isAudioAvailable$:new C(!0),autoVideoTrackLimitingAvailable$:new C(!1),autoVideoTrackLimits$:new C(void 0),currentBuffer$:new C(void 0),isBuffering$:new C(!0),error$:new xe,warning$:new xe,willSeekEvent$:new xe,seekedEvent$:new xe,loopedEvent$:new xe,endedEvent$:new xe,firstBytesEvent$:new xe,loadedMetadataEvent$:new xe,firstFrameEvent$:new xe,canplay$:new xe,isLive$:new C(void 0),isLowLatency$:new C(!1),canChangePlaybackSpeed$:new C(!0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),inPiP$:new C(!1),inFullscreen$:new C(!1),element$:new C(void 0),elementVisible$:new C(!0),availableSources$:new C(void 0),is3DVideo$:new C(!1),playbackState$:new C("")};this.subscription=new CS;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=eg([...rg(this.params.tuning),...tg(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>MS(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",DS(s)),this.screenFormatsIterator=new Ea(s);let n=[...Mu(!0),...Mu(!1)];this.chromecastFormatsIterator=new Ea(n.filter(u=>MS(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Pa(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy(),this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(B$(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:dn.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 Aa(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 kt(o),new ma({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return kt(o),new ba({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return kt(o),Cr||!this.params.tuning.useHlsJs?new ya({...n,source:o}):new Sa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return kt(o),new va({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return kt(o),new Ta({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return kt(o),new Ob({...n,source:o,config:{...N$,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return kt(o),new Ia({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 Aa(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 kt(o),new Ei({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 Aa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Aa(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 Aa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,BS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new CS,t=!1,r=0;return e.add(V$(this.providerOutput.error$,kS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(O$(i=>({id:`ProviderHangup:${i}`,category:dn.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(D$(({to:s})=>s==="playing"),_$()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===dn.NETWORK,u=i.category===dn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},this.params.tuning.useNewProviderReinitLogic?c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN"):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",DS(n))})),e}};import{fromEvent as pn,once as F$,combine as q$,Subscription as OS,ValueSubject as gc,map as U$,filter as H$,isNonNullable as hn,now as Pe,safeStorage as Sc}from"@vkontakte/videoplayer-shared";var j$=5e3,VS="one_video_throughput",_S="one_video_rtt",dt=window.navigator.connection,NS=()=>{let a=dt==null?void 0:dt.downlink;if(hn(a)&&a!==10)return a*1e3},FS=()=>{let a=dt==null?void 0:dt.rtt;if(hn(a)&&a!==3e3)return a},qS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},vc=class a{constructor(e){this.subscription=new OS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(VS)||(e.useBrowserEstimation?NS():void 0)||j$,r=(s=(i=a.load(_S))!=null?i:e.useBrowserEstimation?FS():void 0)!=null?s:0;if(this.throughput$=new gc(t),this.rtt$=new gc(r),this.rttAdjustedThroughput$=new gc(qS(t,r,e.rttPenaltyRequestSize)),this.throughput=er.getSmoothedValue(t,-1,e),this.rtt=er.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=NS();u&&this.throughput.next(u);let l=FS();hn(l)&&this.rtt.next(l)};dt&&"onchange"in dt&&this.subscription.add(pn(dt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Sc.set(VS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Sc.set(_S,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(q$({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(U$(({throughput:n,rtt:o})=>qS(n,o,e.rttPenaltyRequestSize)),H$(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=Pe(),i=new OS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(pn(e,"progress").pipe(F$()).subscribe(s=>{t=s.loaded,r=Pe()}));break;case 1:case 0:i.add(pn(e,"loadstart").subscribe(()=>{t=0,r=Pe()}));break}i.add(pn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Pe(),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=Pe(),n=0,o=Pe(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(i,Pe()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Pe();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=Pe()}else n+=d.byteLength;o=Pe()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Pe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Pe()-o,this.concurrentDownloads.size),n=0,o=Pe());await(r==null?void 0:r.read().then(l,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Sc.get(e);if(hn(t))return(r=parseInt(t,10))!=null?r:void 0}},US=vc;import{fillWithDefault as G$,VideoQuality as HS}from"@vkontakte/videoplayer-shared";var jS={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:HS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:HS.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0},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,useNewProviderReinitLogic:!1,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},GS=a=>{var e;return{...G$(a,jS),configName:[...(e=a.configName)!=null?e:[],...jS.configName]}};import{assertNonNullable as fn,combine as Rt,ErrorCategory as mn,filter as se,filterChanged as N,fromEvent as Tc,isNonNullable as X$,isNullable as Z$,Logger as eL,map as D,mapTo as zS,merge as $t,now as bn,once as pt,Subject as j,Subscription as KS,tap as JS,ValueSubject as P,isHigher as tL,isInvariantQuality as XS,flattenObject as Lt,throttle as Ic,getTraceSubscriptionMethod as ZS,Tracer as rL}from"@vkontakte/videoplayer-shared";import{merge as W$,map as Y$,filter as WS,isNonNullable as Q$}from"@vkontakte/videoplayer-shared";var yc=({seekState:a,position$:e})=>W$(a.stateChangeEnded$.pipe(Y$(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),WS(Q$)),e.pipe(WS(()=>a.getState().state==="none")));import{assertNonNullable as z$}from"@vkontakte/videoplayer-shared";var YS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return z$(e,`Wrong container or containerId {${a.container}}`),e};import{filter as K$,once as J$}from"@vkontakte/videoplayer-shared";var QS=(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(K$(i=>i.length>0),J$()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var gn=class{constructor(e={configName:[]},t=rL.createRootTracer(!1)){this.subscription=new KS;this.logger=new eL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new M("stopped"),seekState:new M({state:"none"}),volume:new M({volume:1,muted:!1}),videoTrack:new M(void 0),videoStream:new M(void 0),audioStream:new M(void 0),autoVideoTrackSwitching:new M(!0),autoVideoTrackLimits:new M({}),isLooped:new M(!1),playbackRate:new M(1),externalTextTracks:new M([]),internalTextTracks:new M([]),currentTextTrack:new M(void 0),textTrackCuesSettings:new M({}),cameraOrientation:new M({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,firstBytes$:new j,loadedMetadata$:new j,firstFrame$:new j,canplay$:new j,log$:new j};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:mb};if(this.initLogs(),this.tuning=GS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ua({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new US(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:mn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i,s,n;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",Lt(r)),this.domContainer=YS(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new wa({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],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&&!Ci()?(this.tracer.log("request play from hidden tab"),Tc(document,"visibilitychange").pipe(pt()).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){fn(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(se(r=>r.length>0),pt()).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",Lt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;fn(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",Lt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return QS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Z$(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return X$(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($t(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(se(({from:e})=>e==="stopped"),pt()).subscribe(()=>{this.initedAt=bn(),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",Lt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:mn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Lt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(D(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(D(n=>n.destination),N()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(D(n=>n.map(({quality:o})=>o).sort((o,u)=>XS(o)?1:XS(u)?-1:tL(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(N()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(N((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(N((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(N()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(N()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(N()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(D(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Rt({hasLiveOffsetByPaused:$t(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(n=>n.to),N(),D(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Rt({atLiveEdge:Rt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:yc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(D(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),N(),JS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(D(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Rt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(D(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),N(),JS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(D(n=>n.muted),N()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(D(n=>n.volume),N()).subscribe(this.info.volume$)).add(yc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add($t(e.providerOutput.endedEvent$.pipe(zS(!0)),e.providerOutput.seekedEvent$.pipe(zS(!1))).pipe(N()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(D(n=>({id:n?`No${n}`:"NoProviders",category:mn.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(pt(),D(n=>n!=null?n:bn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(pt(),D(()=>bn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(pt(),D(()=>bn()-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(se(({to:n})=>n==="playing"),pt()).subscribe(()=>r.next(!1)));let i=0,s=$t(e.providerOutput.isBuffering$,t,r).pipe(D(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),N());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($t(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($t(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(D(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new KS;this.subscription.add(t),this.subscription.add(e.current$.pipe(N((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(se(r=>r.length>0),pt()).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=At(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($t(this.desiredState.videoTrack.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(D(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;fn(this.providerContainer),fn(e),fb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>hb(r)),this.providerContainer.current$.subscribe(({type:r})=>wi("provider",r)),e.duration$.subscribe(r=>wi("duration",r)),e.availableVideoTracks$.pipe(se(r=>!!r.length),pt()).subscribe(r=>wi("tracks",r)),this.events.fatalError$.subscribe(new ae("fatalError")),this.events.managedError$.subscribe(new ae("managedError")),e.position$.subscribe(new ae("position")),e.currentVideoTrack$.pipe(D(r=>r==null?void 0:r.quality)).subscribe(new ae("quality")),this.info.currentBuffer$.subscribe(new ae("buffer")),e.isBuffering$.subscribe(new ae("isBuffering"))].forEach(r=>this.subscription.add(r)),wi("codecs",Zb())}initTracerSubscription(){let e=ZS(this.tracer.log.bind(this.tracer)),t=ZS(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(N()).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(Rt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(se(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),N((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(se(r=>r>0),N()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(se(r=>r>0),N()).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(Rt({currentBuffer:this.info.currentBuffer$.pipe(se(r=>r.end>0),N((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(N())}).pipe(Ic(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(N()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(N()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(N()).subscribe(e("canChangePlaybackSpeed"))).add(Rt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(se(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Ic(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(N(),se(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(N(),se(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(N()).subscribe(e("muted"))).add(this.info.volume$.pipe(N()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(N(),se(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Rt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(se(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Ic(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(N(),se(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:mn.DOM,message:String(i)})})};this.subscription.add($t(Tc(document,"visibilitychange"),Tc(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",Lt({quality:t,availableTracks:Lt(e),track:Lt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as tW,Observable as rW,Subject as iW,ValueSubject as aW,VideoQuality as sW}from"@vkontakte/videoplayer-shared";var nW=`@vkontakte/videoplayer-core@${tl}`;export{Fa as ChromecastState,En as HttpConnectionType,rW as Observable,ce as PlaybackState,gn as Player,nW as SDK_VERSION,iW as Subject,tW as Subscription,xn as Surface,tl as VERSION,aW as ValueSubject,yt as VideoFormat,sW as VideoQuality};
|
|
112
|
+
`;var rn=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new en(this.params.fov,this.params.orientation),this.cameraRotationManager=new tn(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(nS,this.gl.VERTEX_SHADER),r=this.createShader(oS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,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 ir=class{constructor(e){this.subscription=new RR;this.videoState=new M("stopped");this.elementSize$=new $R(void 0);this.textTracksManager=new Ce;this.droppedFramesManager=new Ls;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ri;this.audioTrackSwitchHistory=new Ri;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 IR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new rn(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=de(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(X(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 Zs({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=fe(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:ol.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(){var c;let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(uS(l=>!!l.length),cS()).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(uS(AR),cS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(lS(l=>l.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(he(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(kR(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:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(ER(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(zu(f));let b=[];for(let g of f.representations){let v=Wg(g);b.push(v),this.audioTracksMap.set(v,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(Ku(h));let f=[];for(let b of h.representations){let g=Gg(b);g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}if(this.params.output.availableVideoStreams$.next(p),this.textTracksManager)for(let h of d.text)for(let f of h.representations){let b=Yg(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=l=>e.error$.next({id:"RepresentationSwitch",category:ol.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(an(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$,PR(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,f]=p,b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")this.player.initRepresentations(h.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(n),f){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,g).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(ul()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Ku(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ul()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(zu(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,p;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),(c=this.textTracksManager)==null||c.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(lS(({to:l})=>l==="ready"),ul());this.subscription.add(an(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(an(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=an(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,wR(["init"])).pipe(xR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var R,_,w,B,F,O,k,L,q,$,x,V,H,W,K,oe,Ct,ht;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(R=e.videoTrack.getState())==null?void 0:R.id,n=[...this.videoTracksMap.keys()].find(({id:A})=>A===i),o=t.currentVideoTrack$.getValue(),u=((B=(w=e.videoStream.getState())!=null?w:n&&((_=this.videoTracksMap.get(n))==null?void 0:_.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let c=[...this.videoStreamsMap.keys()].find(({id:A})=>A===u.id),l=c&&this.videoStreamsMap.get(c);if(!l)return;let d=Xe(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=(F=e.audioStream.getState())!=null?F:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(O=[...this.audioStreamsMap.keys()].find(({id:A})=>A===(f==null?void 0:f.id)))!=null?O:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let A=ws(n,l,(k=this.audioStreamsMap.get(b))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(L=A==null?void 0:A.bitrate)!=null?L:-1/0)}else{let A=Gs(n,l,(q=this.audioStreamsMap.get(b))!=null?q:[]);g=Math.max(g,($=A==null?void 0:A.bitrate)!=null?$:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let A=ws(o,l,(x=this.audioStreamsMap.get(b))!=null?x:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(V=A==null?void 0:A.bitrate)!=null?V:-1/0)}else{let A=Gs(o,l,(H=this.audioStreamsMap.get(b))!=null?H:[]);g=Math.max(g,(W=A==null?void 0:A.bitrate)!=null?W:-1/0)}}let v=wt(l,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),I=r?v!=null?v:n:n!=null?n:v,S;this.params.tuning.useSeparateAudioVideoABR?S=b&&Pb(I,l,(K=this.audioStreamsMap.get(b))!=null?K:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):S=b&&Gs(I,l,(oe=this.audioStreamsMap.get(b))!=null?oe:[]);let y=(Ct=this.videoTracksMap.get(I))==null?void 0:Ct.representation,T=S&&((ht=this.audioTracksMap.get(S))==null?void 0:ht.representation);if(y&&T)return[y,T];if(y&&!T&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){be(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ol.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),pe(this.video),this.tracer.end()}};var ba=class extends ir{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 dS,interval as LR,map as MR}from"@vkontakte/videoplayer-shared";var ga=class extends ir{constructor(e){super(e),this.liveOffset=new at,this.textTracksManager=null}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(dS({interval:LR(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(dS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(MR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(i=>{if(i){let s=Qg(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 hS=Fe(xs(),1);import{assertNever as Sa,assertNonNullable as pS,debounce as CR,ErrorCategory as sn,filter as DR,isNonNullable as BR,isNullable as OR,map as nn,merge as VR,Observable as _R,observableFrom as NR,Subscription as FR,videoSizeToQuality as UR}from"@vkontakte/videoplayer-shared";var We={};var Wr=(a,e)=>new _R(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),va=class{constructor(e){this.subscription=new FR;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:Sa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Sa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Sa(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:Sa(e)}break;default:Sa(t)}};this.video=de(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(X(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),pe(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:sn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,hS.default)(import("hls.js").then(i=>{e||(We.Hls=i.default,We.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){pS(We.Hls,"hls.js not loaded"),this.hls=new We.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){pS(We.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=c=>{t.error$.next({id:"HlsJsProvider",category:sn.WTF,message:"HlsJsProvider internal logic error",thrown:c})},i=fe(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(he(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(nn(c=>c.to)),this.params.output.playbackState$),this.subscription.add(Wr(this.hls,We.Events.ERROR).subscribe(c=>{var l;c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:sn.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(Wr(this.hls,We.Events.MANIFEST_PARSED).pipe(nn(({levels:c})=>c.reduce((l,d)=>{var I,S;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(S=At((I=d.attrs.QUALITY)!=null?I:""))!=null?S:UR({width:h,height:f});if(!b)return l;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:v,level:d}),l.push(v),l},[]))),t.availableVideoTracks$),s(Wr(this.hls,We.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(Wr(this.hls,We.Events.LEVEL_LOADING).pipe(nn(({url:c})=>X(c))),t.hostname$),s(Wr(this.hls,We.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(Et(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=Wr(this.hls,We.Events.LEVEL_SWITCHED).pipe(nn(({level:c})=>n(this.hls.levels[c])));o.pipe(DR(BR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Et(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),c=>{var f;if(OR(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=VR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,NR(["init"])).pipe(CR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await be(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sn.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 fS="X-Playback-Duration",ll=async a=>{var i;let e=await nt(a),t=await e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(fS)?parseInt(e.headers.get(fS),10):void 0};import{assertNever as YR,combine as QR,debounce as zR,ErrorCategory as un,filter as KR,filterChanged as JR,isNonNullable as bS,isNullable as ln,map as gS,merge as XR,observableFrom as ZR,Subscription as e$,ValueSubject as pl,VideoQuality as t$}from"@vkontakte/videoplayer-shared";var dl=Fe(ko(),1);import{videoSizeToQuality as qR,getExponentialDelay as HR}from"@vkontakte/videoplayer-shared";var jR=a=>{let e=null;if(a.QUALITY&&(e=At(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=qR({width:t,height:r})}return e!=null?e:null},GR=(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,dl.default)(c[1].split(",").map(I=>I.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=jR(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[I,S]=d.RESOLUTION.split("x").map(y=>parseInt(y,10));I&&S&&(g={width:I,height:S})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:f,size:g,fps:b})}if(l){let d=(0,dl.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}},WR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),cl=0,mS=async(a,e=a,t)=>{let i=await(await nt(a)).text();cl+=1;try{let{qualityManifests:s,textTracks:n}=GR(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(cl<=t.manifestRetryMaxCount)return await WR(HR(cl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),mS(a,e,t)}return{qualityManifests:[],textTracks:[]}},on=mS;var ya=class{constructor(e){this.subscription=new e$;this.videoState=new M("stopped");this.textTracksManager=new Ce;this.manifests$=new pl([]);this.liveOffset=new at;this.manifestStartTime$=new pl(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 YR(t)}};var t;this.params=e,this.video=de(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:t$.INVARIANT,url:this.params.source.url},on(te(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:un.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:un.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(X(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new pl((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:un.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=fe(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(he(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(JR(),gS(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&&bS(c.to)){let d=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(X(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,c,l;let o=(l=(c=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:c.call(u))==null?void 0:l.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(QR({startTime:this.manifestStartTime$.pipe(KR(bS)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(gS(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=XR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ZR(["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),pe(this.video)}prepare(){var o,u;let e=this.selectManifest();if(ln(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=te(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ll(n).then(c=>{var l;if(!ln(c))this.maxSeekBackTime$.next(c);else{let d=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();if(ln(d)||!isFinite(d))try{nt(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();ll(b).then(g=>{ln(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:un.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 r$,debounce as i$,ErrorCategory as hl,fromEvent as fl,isNonNullable as a$,isNullable as s$,map as SS,merge as vS,observableFrom as yS,Subscription as n$,ValueSubject as o$,VideoQuality as u$,clientChecker as l$}from"@vkontakte/videoplayer-shared";var Ta=class{constructor(e){this.subscription=new n$;this.videoState=new M("stopped");this.textTracksManager=new Ce;this.manifests$=new o$([]);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 r$(t)}};this.params=e,this.video=de(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:u$.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(X(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),on(te(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:hl.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:hl.WTF,message:"HlsProvider internal logic error",thrown:o})},i=fe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(SS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ke(this.video,t.isLooped,r)),this.subscription.add(he(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&&a$(c.to)){let p=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let h=this.manifests$.getValue().find(f=>f.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(X(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(SS(o=>o.map(({id:u,quality:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!l$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(vS(fl(o,"addtrack"),fl(o,"removetrack"),fl(o,"change"),yS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=vS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,yS(["init"])).pipe(i$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),pe(this.video)}prepare(){var s,n;let e=this.selectManifest();if(s$(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(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as c$,assertNonNullable as TS,debounce as d$,ErrorCategory as IS,isHigher as p$,isHigherOrEqual as h$,isInvariantQuality as ES,isLowerOrEqual as f$,isNonNullable as m$,merge as b$,observableFrom as g$,Subscription as S$,map as v$}from"@vkontakte/videoplayer-shared";var Ia=class{constructor(e){this.subscription=new S$;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 c$(e)}};this.params=e,this.video=de(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:IS.WTF,message:"MpegProvider internal logic error",thrown:o})},i=fe(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(v$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ke(this.video,t.isLooped,r)),this.subscription.add(he(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&&m$(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=b$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,g$(["init"])).pipe(d$(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),pe(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;TS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];TS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=la(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(X(t))}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:IS.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=>!ES(d.track.quality)&&f$(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&&h$(l.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!ES(h.track.quality)&&p$(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=wt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as PS,debounce as E$,merge as AS,observableFrom as x$,Subscription as P$,map as wS,ValueSubject as A$,ErrorCategory as bl,VideoQuality as w$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as y$}from"@vkontakte/videoplayer-shared";var xS=["stun:videostun.mycdn.me:80"],T$=1e3,I$=3,ml=()=>null,cn=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=ml;this.externalStopCallback=ml;this.externalErrorCallback=ml;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:xS}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:y$.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),T$)}normalizeOptions(e={}){let t={stunServerList:xS,maxRetryNumber:I$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ea=class{constructor(e){this.videoState=new M("stopped");this.maxSeekBackTime$=new A$(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return PS(e)}};this.subscription=new P$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=de(e.container,e.tuning),this.liveStreamClient=new cn(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),pe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:bl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};AS(this.videoState.stateChangeStarted$.pipe(wS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(wS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=fe(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(he(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return PS(n.to)}},r)).add(AS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,x$(["init"])).pipe(E$(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(X(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:w$.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:bl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var xa=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 Aa,assertNonNullable as Rt,ErrorCategory as pn,filter as D$,isNonNullable as CS,isNullable as B$,map as O$,merge as V$,once as _$,Subject as Pe,Subscription as DS,ValueSubject as C,flattenObject as BS}from"@vkontakte/videoplayer-shared";import{Observable as k$,map as kS,Subscription as R$,Subject as $$}from"@vkontakte/videoplayer-shared";var RS=a=>new k$(e=>{let t=new R$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(kS(({from:c,to:l})=>`${c}-${l}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(kS(({type:c})=>c!==void 0)),n=new $$,o=0,u="unknown";return t.add(r.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(c=>{o&&(window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as $S,Subscription as L$,combine as M$,filter as LS,once as MS}from"@vkontakte/videoplayer-shared";var Pa=null,dn=null;function gl(){return Pa||(Pa=new(window.AudioContext||window.webkitAudioContext)),dn||(dn=new GainNode(Pa,{gain:1}),dn.connect(Pa.destination)),{audioCtx:Pa,gainNode:dn}}import{clientChecker as C$}from"@vkontakte/videoplayer-shared";var Yr=class Yr{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.audioContextInit=!1;this.subscriptions=new L$;this.lastAudioContextResumeId=0;this.subscriptions.add(this.provider$.pipe(LS(s=>!!s.type),MS()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){C$.isSafari&&e!=="MPEG"||this.subscriptions.add(M$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(LS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),MS()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:i}=gl(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Yr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i),this.audioContextInit=!0}catch(o){this.volumeMultiplierError$.next({id:Yr.errorId,category:$S.VIDEO_PIPELINE,message:(n=o==null?void 0:o.message)!=null?n:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(n=>{var o;this.volumeMultiplierError$.next({id:Yr.errorId,category:$S.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){if(this.audioContextInit){let{gainNode:e}=gl();e.gain.value=1}this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Yr.errorId="VolumeMultiplierManager";var Qr=Yr;var N$={chunkDuration:5e3,maxParallelRequests:5},wa=class{constructor(e){this.current$=new C({type:void 0});this.providerError$=new Pe;this.noAvailableProvidersError$=new Pe;this.volumeMultiplierError$=new Pe;this.providerOutput={position$:new C(0),duration$:new C(1/0),volume$:new C({muted:!1,volume:1}),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableVideoTracks$:new C([]),currentVideoTrack$:new C(void 0),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0),isAudioAvailable$:new C(!0),autoVideoTrackLimitingAvailable$:new C(!1),autoVideoTrackLimits$:new C(void 0),currentBuffer$:new C(void 0),isBuffering$:new C(!0),error$:new Pe,warning$:new Pe,willSeekEvent$:new Pe,seekedEvent$:new Pe,loopedEvent$:new Pe,endedEvent$:new Pe,firstBytesEvent$:new Pe,loadedMetadataEvent$:new Pe,firstFrameEvent$:new Pe,canplay$:new Pe,isLive$:new C(void 0),isLowLatency$:new C(!1),canChangePlaybackSpeed$:new C(!0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),inPiP$:new C(!1),inFullscreen$:new C(!1),element$:new C(void 0),elementVisible$:new C(!0),availableSources$:new C(void 0),is3DVideo$:new C(!1),playbackState$:new C("")};this.subscription=new DS;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=eg([...rg(this.params.tuning),...tg(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(c=>CS(e.sources[c])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(c=>!i.includes(c)),...t.filter(c=>i.includes(c))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",BS(s)),this.screenFormatsIterator=new xa(s);let n=[...Cu(!0),...Cu(!1)];this.chromecastFormatsIterator=new xa(n.filter(c=>CS(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Qr.isSupported()&&(this.volumeMultiplierManager=new Qr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(B$(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:pn.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 Aa(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 Rt(o),new ba({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Rt(o),new ga({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Rt(o),Br||!this.params.tuning.useHlsJs?new Ta({...n,source:o}):new va({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Rt(o),new ya({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Rt(o),new Ia({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Rt(o),new Ob({...n,source:o,config:{...N$,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Rt(o),new Ea({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 Aa(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 Rt(o),new Pi({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 Aa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Aa(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 Aa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,OS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new DS,t=!1,r=0;return e.add(V$(this.providerOutput.error$,RS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(O$(i=>({id:`ProviderHangup:${i}`,category:pn.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(D$(({to:s})=>s==="playing"),_$()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===pn.NETWORK,u=i.category===pn.FATAL,c=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!u,d=c&&!u&&(o&&t||!l);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:c,tryFailover:d,canReinitProvider:l},this.params.tuning.useNewProviderReinitLogic?l?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN"):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",BS(n))})),e}};import{fromEvent as hn,once as F$,combine as U$,Subscription as VS,ValueSubject as Sl,map as q$,filter as H$,isNonNullable as fn,now as Ae,safeStorage as vl}from"@vkontakte/videoplayer-shared";var j$=5e3,_S="one_video_throughput",NS="one_video_rtt",dt=window.navigator.connection,FS=()=>{let a=dt==null?void 0:dt.downlink;if(fn(a)&&a!==10)return a*1e3},US=()=>{let a=dt==null?void 0:dt.rtt;if(fn(a)&&a!==3e3)return a},qS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},yl=class a{constructor(e){this.subscription=new VS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(_S)||(e.useBrowserEstimation?FS():void 0)||j$,r=(s=(i=a.load(NS))!=null?i:e.useBrowserEstimation?US():void 0)!=null?s:0;if(this.throughput$=new Sl(t),this.rtt$=new Sl(r),this.rttAdjustedThroughput$=new Sl(qS(t,r,e.rttPenaltyRequestSize)),this.throughput=tr.getSmoothedValue(t,-1,e),this.rtt=tr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=FS();u&&this.throughput.next(u);let c=US();fn(c)&&this.rtt.next(c)};dt&&"onchange"in dt&&this.subscription.add(hn(dt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{vl.set(_S,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{vl.set(NS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(U$({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(q$(({throughput:n,rtt:o})=>qS(n,o,e.rttPenaltyRequestSize)),H$(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Ae(),i=new VS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(hn(e,"progress").pipe(F$()).subscribe(s=>{t=s.loaded,r=Ae()}));break;case 1:case 0:i.add(hn(e,"loadstart").subscribe(()=>{t=0,r=Ae()}));break}i.add(hn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ae(),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=Ae(),n=0,o=Ae(),u=l=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},c=async({done:l,value:d})=>{if(l)!t&&this.addRawSpeed(i,Ae()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Ae();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=Ae()}else n+=d.byteLength;o=Ae()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ae()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ae()-o,this.concurrentDownloads.size),n=0,o=Ae());await(r==null?void 0:r.read().then(c,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(c,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=vl.get(e);if(fn(t))return(r=parseInt(t,10))!=null?r:void 0}},HS=yl;import{fillWithDefault as G$,VideoQuality as jS}from"@vkontakte/videoplayer-shared";var GS={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:jS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:jS.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!1,maxSegmentRetryCount:5},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,useNewProviderReinitLogic:!1,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},WS=a=>{var e;return{...G$(a,GS),configName:[...(e=a.configName)!=null?e:[],...GS.configName]}};import{assertNonNullable as mn,combine as $t,ErrorCategory as bn,filter as ne,filterChanged as N,fromEvent as Il,isNonNullable as X$,isNullable as Z$,Logger as eL,map as D,mapTo as KS,merge as Lt,now as gn,once as pt,Subject as j,Subscription as JS,tap as XS,ValueSubject as P,isHigher as tL,isInvariantQuality as ZS,flattenObject as Mt,throttle as El,getTraceSubscriptionMethod as ev,Tracer as rL}from"@vkontakte/videoplayer-shared";import{merge as W$,map as Y$,filter as YS,isNonNullable as Q$}from"@vkontakte/videoplayer-shared";var Tl=({seekState:a,position$:e})=>W$(a.stateChangeEnded$.pipe(Y$(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),YS(Q$)),e.pipe(YS(()=>a.getState().state==="none")));import{assertNonNullable as z$}from"@vkontakte/videoplayer-shared";var QS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return z$(e,`Wrong container or containerId {${a.container}}`),e};import{filter as K$,once as J$}from"@vkontakte/videoplayer-shared";var zS=(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(K$(i=>i.length>0),J$()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Sn=class{constructor(e={configName:[]},t=rL.createRootTracer(!1)){this.subscription=new JS;this.logger=new eL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new M("stopped"),seekState:new M({state:"none"}),volume:new M({volume:1,muted:!1}),videoTrack:new M(void 0),videoStream:new M(void 0),audioStream:new M(void 0),autoVideoTrackSwitching:new M(!0),autoVideoTrackLimits:new M({}),isLooped:new M(!1),playbackRate:new M(1),externalTextTracks:new M([]),internalTextTracks:new M([]),currentTextTrack:new M(void 0),textTrackCuesSettings:new M({}),cameraOrientation:new M({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,firstBytes$:new j,loadedMetadata$:new j,firstFrame$:new j,canplay$:new j,log$:new j};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:mb};if(this.initLogs(),this.tuning=WS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ha({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new HS(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:bn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i,s,n;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",Mt(r)),this.domContainer=QS(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new wa({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],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&&!Di()?(this.tracer.log("request play from hidden tab"),Il(document,"visibilitychange").pipe(pt()).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){mn(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(ne(r=>r.length>0),pt()).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",Mt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;mn(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",Mt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return zS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Z$(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return X$(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(Lt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ne(({from:e})=>e==="stopped"),pt()).subscribe(()=>{this.initedAt=gn(),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",Mt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:bn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Mt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(D(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(D(n=>n.destination),N()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(D(n=>n.map(({quality:o})=>o).sort((o,u)=>ZS(o)?1:ZS(u)?-1:tL(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(N()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(N((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(N((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(N()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(N()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(N()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(D(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add($t({hasLiveOffsetByPaused:Lt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(n=>n.to),N(),D(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add($t({atLiveEdge:$t({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Tl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(D(({isLive:n,position:o,isLowLatency:u})=>{let c=this.getActiveLiveDelay(u);return n&&Math.abs(o)<c/1e3}),N(),XS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(D(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add($t({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(D(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),N(),XS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(D(n=>n.muted),N()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(D(n=>n.volume),N()).subscribe(this.info.volume$)).add(Tl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Lt(e.providerOutput.endedEvent$.pipe(KS(!0)),e.providerOutput.seekedEvent$.pipe(KS(!1))).pipe(N()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(D(n=>({id:n?`No${n}`:"NoProviders",category:bn.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(pt(),D(n=>n!=null?n:gn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(pt(),D(()=>gn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(pt(),D(()=>gn()-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(ne(({to:n})=>n==="playing"),pt()).subscribe(()=>r.next(!1)));let i=0,s=Lt(e.providerOutput.isBuffering$,t,r).pipe(D(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),N());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(Lt(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(Lt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),c=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),d;l==="CONNECTED"?d="second_screen":u?c?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(D(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new JS;this.subscription.add(t),this.subscription.add(e.current$.pipe(N((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ne(r=>r.length>0),pt()).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=wt(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(Lt(this.desiredState.videoTrack.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(D(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;mn(this.providerContainer),mn(e),fb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>hb(r)),this.providerContainer.current$.subscribe(({type:r})=>ki("provider",r)),e.duration$.subscribe(r=>ki("duration",r)),e.availableVideoTracks$.pipe(ne(r=>!!r.length),pt()).subscribe(r=>ki("tracks",r)),this.events.fatalError$.subscribe(new se("fatalError")),this.events.managedError$.subscribe(new se("managedError")),e.position$.subscribe(new se("position")),e.currentVideoTrack$.pipe(D(r=>r==null?void 0:r.quality)).subscribe(new se("quality")),this.info.currentBuffer$.subscribe(new se("buffer")),e.isBuffering$.subscribe(new se("isBuffering"))].forEach(r=>this.subscription.add(r)),ki("codecs",Zb())}initTracerSubscription(){let e=ev(this.tracer.log.bind(this.tracer)),t=ev(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(N()).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($t({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ne(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),N((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ne(r=>r>0),N()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ne(r=>r>0),N()).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($t({currentBuffer:this.info.currentBuffer$.pipe(ne(r=>r.end>0),N((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(N())}).pipe(El(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(N()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(N()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(N()).subscribe(e("canChangePlaybackSpeed"))).add($t({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ne(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),El(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(N(),ne(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(N(),ne(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(N()).subscribe(e("muted"))).add(this.info.volume$.pipe(N()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(N(),ne(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add($t({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ne(({throughputEstimation:r,rtt:i})=>!!r&&!!i),El(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(N(),ne(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:bn.DOM,message:String(i)})})};this.subscription.add(Lt(Il(document,"visibilitychange"),Il(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",Mt({quality:t,availableTracks:Mt(e),track:Mt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as tW,Observable as rW,Subject as iW,ValueSubject as aW,VideoQuality as sW}from"@vkontakte/videoplayer-shared";var nW=`@vkontakte/videoplayer-core@${tc}`;export{Ua as ChromecastState,xn as HttpConnectionType,rW as Observable,le as PlaybackState,Sn as Player,nW as SDK_VERSION,iW as Subject,tW as Subscription,Pn as Surface,tc as VERSION,aW as ValueSubject,Tt as VideoFormat,sW as VideoQuality};
|