@vkontakte/videoplayer-core 2.0.108-dev.43b53ca1.0 → 2.0.108-dev.9b636631.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 +17 -38
- package/es2015.esm.js +16 -37
- package/es2018.cjs.js +17 -38
- package/es2018.esm.js +16 -37
- package/esnext.cjs.js +18 -39
- package/esnext.esm.js +17 -38
- package/evergreen.esm.js +16 -37
- package/package.json +2 -2
- package/types/player/Player.d.ts +2 -2
- package/types/player/types.d.ts +6 -5
- package/types/providers/DashProvider/baseDashProvider.d.ts +1 -2
- package/types/utils/autoSelectVideoTrack.d.ts +11 -13
- package/types/utils/tuningConfig.d.ts +0 -5
package/es2015.esm.js
CHANGED
|
@@ -1,18 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.108-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.108-dev.9b636631.0
|
|
3
|
+
* Fri, 30 Aug 2024 14:05:43 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-108/doc/
|
|
5
5
|
*/
|
|
6
|
-
var iv=Object.create;var pn=Object.defineProperty,av=Object.defineProperties,sv=Object.getOwnPropertyDescriptor,nv=Object.getOwnPropertyDescriptors,ov=Object.getOwnPropertyNames,Dl=Object.getOwnPropertySymbols,uv=Object.getPrototypeOf,Bl=Object.prototype.hasOwnProperty,lv=Object.prototype.propertyIsEnumerable;var cv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var Ye=Math.pow,Ol=(a,e,t)=>e in a?pn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,R=(a,e)=>{for(var t in e||(e={}))Bl.call(e,t)&&Ol(a,t,e[t]);if(Dl)for(var t of Dl(e))lv.call(e,t)&&Ol(a,t,e[t]);return a},F=(a,e)=>av(a,nv(e));var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var dv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ov(e))!Bl.call(a,i)&&i!==t&&pn(a,i,{get:()=>e[i],enumerable:!(r=sv(e,i))||r.enumerable});return a};var We=(a,e,t)=>(t=a!=null?iv(uv(a)):{},dv(e||!a||!a.__esModule?pn(t,"default",{value:a,enumerable:!0}):t,a));var w=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),pv=function(a,e){this[0]=a,this[1]=e},re=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof pv,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[cv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var ye=m((n$,jl)=>{"use strict";jl.exports=function(a){try{return!!a()}catch(e){return!0}}});var qr=m((o$,Gl)=>{"use strict";var yv=ye();Gl.exports=!yv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var pe=m((u$,Ql)=>{"use strict";var Yl=qr(),Wl=Function.prototype,gn=Wl.call,Tv=Yl&&Wl.bind.bind(gn,gn);Ql.exports=Yl?Tv:function(a){return function(){return gn.apply(a,arguments)}}});var ir=m((l$,Kl)=>{"use strict";var zl=pe(),Iv=zl({}.toString),Ev=zl("".slice);Kl.exports=function(a){return Ev(Iv(a),8,-1)}});var Xl=m((c$,Jl)=>{"use strict";var xv=pe(),Pv=ye(),Av=ir(),Sn=Object,wv=xv("".split);Jl.exports=Pv(function(){return!Sn("z").propertyIsEnumerable(0)})?function(a){return Av(a)==="String"?wv(a,""):Sn(a)}:Sn});var ar=m((d$,Zl)=>{"use strict";Zl.exports=function(a){return a==null}});var Ur=m((p$,ec)=>{"use strict";var kv=ar(),Rv=TypeError;ec.exports=function(a){if(kv(a))throw new Rv("Can't call method on "+a);return a}});var sr=m((h$,tc)=>{"use strict";var Lv=Xl(),$v=Ur();tc.exports=function(a){return Lv($v(a))}});var vn=m((f$,rc)=>{"use strict";rc.exports=function(){}});var Mt=m((m$,ic)=>{"use strict";ic.exports={}});var z=m((yn,ac)=>{"use strict";var Hr=function(a){return a&&a.Math===Math&&a};ac.exports=Hr(typeof globalThis=="object"&&globalThis)||Hr(typeof window=="object"&&window)||Hr(typeof self=="object"&&self)||Hr(typeof global=="object"&&global)||Hr(typeof yn=="object"&&yn)||function(){return this}()||Function("return this")()});var Q=m((b$,sc)=>{"use strict";var Tn=typeof document=="object"&&document.all;sc.exports=typeof Tn=="undefined"&&Tn!==void 0?function(a){return typeof a=="function"||a===Tn}:function(a){return typeof a=="function"}});var uc=m((g$,oc)=>{"use strict";var Mv=z(),Cv=Q(),nc=Mv.WeakMap;oc.exports=Cv(nc)&&/native code/.test(String(nc))});var we=m((S$,lc)=>{"use strict";var Dv=Q();lc.exports=function(a){return typeof a=="object"?a!==null:Dv(a)}});var ke=m((v$,cc)=>{"use strict";var Ov=ye();cc.exports=!Ov(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ea=m((y$,pc)=>{"use strict";var Bv=z(),dc=we(),In=Bv.document,Vv=dc(In)&&dc(In.createElement);pc.exports=function(a){return Vv?In.createElement(a):{}}});var En=m((T$,hc)=>{"use strict";var _v=ke(),Nv=ye(),Fv=Ea();hc.exports=!_v&&!Nv(function(){return Object.defineProperty(Fv("div"),"a",{get:function(){return 7}}).a!==7})});var xn=m((I$,fc)=>{"use strict";var qv=ke(),Uv=ye();fc.exports=qv&&Uv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Qe=m((E$,mc)=>{"use strict";var Hv=we(),jv=String,Gv=TypeError;mc.exports=function(a){if(Hv(a))return a;throw new Gv(jv(a)+" is not an object")}});var Te=m((x$,bc)=>{"use strict";var Yv=qr(),xa=Function.prototype.call;bc.exports=Yv?xa.bind(xa):function(){return xa.apply(xa,arguments)}});var Pa=m((P$,gc)=>{"use strict";gc.exports={}});var Ze=m((A$,vc)=>{"use strict";var Pn=Pa(),An=z(),Wv=Q(),Sc=function(a){return Wv(a)?a:void 0};vc.exports=function(a,e){return arguments.length<2?Sc(Pn[a])||Sc(An[a]):Pn[a]&&Pn[a][e]||An[a]&&An[a][e]}});var jr=m((w$,yc)=>{"use strict";var Qv=pe();yc.exports=Qv({}.isPrototypeOf)});var nr=m((k$,Ec)=>{"use strict";var zv=z(),Tc=zv.navigator,Ic=Tc&&Tc.userAgent;Ec.exports=Ic?String(Ic):""});var kn=m((R$,Rc)=>{"use strict";var kc=z(),wn=nr(),xc=kc.process,Pc=kc.Deno,Ac=xc&&xc.versions||Pc&&Pc.version,wc=Ac&&Ac.v8,_e,Aa;wc&&(_e=wc.split("."),Aa=_e[0]>0&&_e[0]<4?1:+(_e[0]+_e[1]));!Aa&&wn&&(_e=wn.match(/Edge\/(\d+)/),(!_e||_e[1]>=74)&&(_e=wn.match(/Chrome\/(\d+)/),_e&&(Aa=+_e[1])));Rc.exports=Aa});var Rn=m((L$,$c)=>{"use strict";var Lc=kn(),Kv=ye(),Jv=z(),Xv=Jv.String;$c.exports=!!Object.getOwnPropertySymbols&&!Kv(function(){var a=Symbol("symbol detection");return!Xv(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Lc&&Lc<41})});var Ln=m(($$,Mc)=>{"use strict";var Zv=Rn();Mc.exports=Zv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var $n=m((M$,Cc)=>{"use strict";var ey=Ze(),ty=Q(),ry=jr(),iy=Ln(),ay=Object;Cc.exports=iy?function(a){return typeof a=="symbol"}:function(a){var e=ey("Symbol");return ty(e)&&ry(e.prototype,ay(a))}});var Gr=m((C$,Dc)=>{"use strict";var sy=String;Dc.exports=function(a){try{return sy(a)}catch(e){return"Object"}}});var et=m((D$,Oc)=>{"use strict";var ny=Q(),oy=Gr(),uy=TypeError;Oc.exports=function(a){if(ny(a))return a;throw new uy(oy(a)+" is not a function")}});var Yr=m((O$,Bc)=>{"use strict";var ly=et(),cy=ar();Bc.exports=function(a,e){var t=a[e];return cy(t)?void 0:ly(t)}});var _c=m((B$,Vc)=>{"use strict";var Mn=Te(),Cn=Q(),Dn=we(),dy=TypeError;Vc.exports=function(a,e){var t,r;if(e==="string"&&Cn(t=a.toString)&&!Dn(r=Mn(t,a))||Cn(t=a.valueOf)&&!Dn(r=Mn(t,a))||e!=="string"&&Cn(t=a.toString)&&!Dn(r=Mn(t,a)))return r;throw new dy("Can't convert object to primitive value")}});var Ne=m((V$,Nc)=>{"use strict";Nc.exports=!0});var Uc=m((_$,qc)=>{"use strict";var Fc=z(),py=Object.defineProperty;qc.exports=function(a,e){try{py(Fc,a,{value:e,configurable:!0,writable:!0})}catch(t){Fc[a]=e}return e}});var Wr=m((N$,Gc)=>{"use strict";var hy=Ne(),fy=z(),my=Uc(),Hc="__core-js_shared__",jc=Gc.exports=fy[Hc]||my(Hc,{});(jc.versions||(jc.versions=[])).push({version:"3.38.0",mode:hy?"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 On=m((F$,Wc)=>{"use strict";var Yc=Wr();Wc.exports=function(a,e){return Yc[a]||(Yc[a]=e||{})}});var Qr=m((q$,Qc)=>{"use strict";var by=Ur(),gy=Object;Qc.exports=function(a){return gy(by(a))}});var Fe=m((U$,zc)=>{"use strict";var Sy=pe(),vy=Qr(),yy=Sy({}.hasOwnProperty);zc.exports=Object.hasOwn||function(e,t){return yy(vy(e),t)}});var Bn=m((H$,Kc)=>{"use strict";var Ty=pe(),Iy=0,Ey=Math.random(),xy=Ty(1 .toString);Kc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+xy(++Iy+Ey,36)}});var ne=m((j$,Xc)=>{"use strict";var Py=z(),Ay=On(),Jc=Fe(),wy=Bn(),ky=Rn(),Ry=Ln(),or=Py.Symbol,Vn=Ay("wks"),Ly=Ry?or.for||or:or&&or.withoutSetter||wy;Xc.exports=function(a){return Jc(Vn,a)||(Vn[a]=ky&&Jc(or,a)?or[a]:Ly("Symbol."+a)),Vn[a]}});var rd=m((G$,td)=>{"use strict";var $y=Te(),Zc=we(),ed=$n(),My=Yr(),Cy=_c(),Dy=ne(),Oy=TypeError,By=Dy("toPrimitive");td.exports=function(a,e){if(!Zc(a)||ed(a))return a;var t=My(a,By),r;if(t){if(e===void 0&&(e="default"),r=$y(t,a,e),!Zc(r)||ed(r))return r;throw new Oy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Cy(a,e)}});var _n=m((Y$,id)=>{"use strict";var Vy=rd(),_y=$n();id.exports=function(a){var e=Vy(a,"string");return _y(e)?e:e+""}});var Ct=m(sd=>{"use strict";var Ny=ke(),Fy=En(),qy=xn(),wa=Qe(),ad=_n(),Uy=TypeError,Nn=Object.defineProperty,Hy=Object.getOwnPropertyDescriptor,Fn="enumerable",qn="configurable",Un="writable";sd.f=Ny?qy?function(e,t,r){if(wa(e),t=ad(t),wa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Un in r&&!r[Un]){var i=Hy(e,t);i&&i[Un]&&(e[t]=r.value,r={configurable:qn in r?r[qn]:i[qn],enumerable:Fn in r?r[Fn]:i[Fn],writable:!1})}return Nn(e,t,r)}:Nn:function(e,t,r){if(wa(e),t=ad(t),wa(r),Fy)try{return Nn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Uy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var zr=m((Q$,nd)=>{"use strict";nd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var ur=m((z$,od)=>{"use strict";var jy=ke(),Gy=Ct(),Yy=zr();od.exports=jy?function(a,e,t){return Gy.f(a,e,Yy(1,t))}:function(a,e,t){return a[e]=t,a}});var ka=m((K$,ld)=>{"use strict";var Wy=On(),Qy=Bn(),ud=Wy("keys");ld.exports=function(a){return ud[a]||(ud[a]=Qy(a))}});var Ra=m((J$,cd)=>{"use strict";cd.exports={}});var Yn=m((X$,hd)=>{"use strict";var zy=uc(),pd=z(),Ky=we(),Jy=ur(),Hn=Fe(),jn=Wr(),Xy=ka(),Zy=Ra(),dd="Object already initialized",Gn=pd.TypeError,eT=pd.WeakMap,La,Kr,$a,tT=function(a){return $a(a)?Kr(a):La(a,{})},rT=function(a){return function(e){var t;if(!Ky(e)||(t=Kr(e)).type!==a)throw new Gn("Incompatible receiver, "+a+" required");return t}};zy||jn.state?(qe=jn.state||(jn.state=new eT),qe.get=qe.get,qe.has=qe.has,qe.set=qe.set,La=function(a,e){if(qe.has(a))throw new Gn(dd);return e.facade=a,qe.set(a,e),e},Kr=function(a){return qe.get(a)||{}},$a=function(a){return qe.has(a)}):(Dt=Xy("state"),Zy[Dt]=!0,La=function(a,e){if(Hn(a,Dt))throw new Gn(dd);return e.facade=a,Jy(a,Dt,e),e},Kr=function(a){return Hn(a,Dt)?a[Dt]:{}},$a=function(a){return Hn(a,Dt)});var qe,Dt;hd.exports={set:La,get:Kr,has:$a,enforce:tT,getterFor:rT}});var Wn=m((Z$,gd)=>{"use strict";var iT=qr(),bd=Function.prototype,fd=bd.apply,md=bd.call;gd.exports=typeof Reflect=="object"&&Reflect.apply||(iT?md.bind(fd):function(){return md.apply(fd,arguments)})});var Qn=m((eM,Sd)=>{"use strict";var aT=ir(),sT=pe();Sd.exports=function(a){if(aT(a)==="Function")return sT(a)}});var Id=m(Td=>{"use strict";var vd={}.propertyIsEnumerable,yd=Object.getOwnPropertyDescriptor,nT=yd&&!vd.call({1:2},1);Td.f=nT?function(e){var t=yd(this,e);return!!t&&t.enumerable}:vd});var Pd=m(xd=>{"use strict";var oT=ke(),uT=Te(),lT=Id(),cT=zr(),dT=sr(),pT=_n(),hT=Fe(),fT=En(),Ed=Object.getOwnPropertyDescriptor;xd.f=oT?Ed:function(e,t){if(e=dT(e),t=pT(t),fT)try{return Ed(e,t)}catch(r){}if(hT(e,t))return cT(!uT(lT.f,e,t),e[t])}});var zn=m((iM,Ad)=>{"use strict";var mT=ye(),bT=Q(),gT=/#|\.prototype\./,Jr=function(a,e){var t=vT[ST(a)];return t===TT?!0:t===yT?!1:bT(e)?mT(e):!!e},ST=Jr.normalize=function(a){return String(a).replace(gT,".").toLowerCase()},vT=Jr.data={},yT=Jr.NATIVE="N",TT=Jr.POLYFILL="P";Ad.exports=Jr});var Xr=m((aM,kd)=>{"use strict";var wd=Qn(),IT=et(),ET=qr(),xT=wd(wd.bind);kd.exports=function(a,e){return IT(a),e===void 0?a:ET?xT(a,e):function(){return a.apply(e,arguments)}}});var Re=m((sM,Ld)=>{"use strict";var Zr=z(),PT=Wn(),AT=Qn(),wT=Q(),kT=Pd().f,RT=zn(),lr=Pa(),LT=Xr(),cr=ur(),Rd=Fe();Wr();var $T=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return PT(a,this,arguments)};return e.prototype=a.prototype,e};Ld.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Zr:i?Zr[t]:Zr[t]&&Zr[t].prototype,o=r?lr:lr[t]||cr(lr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,S;for(p in e)l=RT(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Rd(n,p),f=o[p],c&&(a.dontCallGetSet?(S=kT(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=LT(h,Zr):a.wrap&&c?g=$T(h):s&&wT(h)?g=AT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&cr(g,"sham",!0),cr(o,p,g),s&&(d=t+"Prototype",Rd(lr,d)||cr(lr,d,{}),cr(lr[d],p,h),a.real&&u&&(l||!u[p])&&cr(u,p,h)))}});var Cd=m((nM,Md)=>{"use strict";var Kn=ke(),MT=Fe(),$d=Function.prototype,CT=Kn&&Object.getOwnPropertyDescriptor,Jn=MT($d,"name"),DT=Jn&&function(){}.name==="something",OT=Jn&&(!Kn||Kn&&CT($d,"name").configurable);Md.exports={EXISTS:Jn,PROPER:DT,CONFIGURABLE:OT}});var Od=m((oM,Dd)=>{"use strict";var BT=Math.ceil,VT=Math.floor;Dd.exports=Math.trunc||function(e){var t=+e;return(t>0?VT:BT)(t)}});var Ma=m((uM,Bd)=>{"use strict";var _T=Od();Bd.exports=function(a){var e=+a;return e!==e||e===0?0:_T(e)}});var _d=m((lM,Vd)=>{"use strict";var NT=Ma(),FT=Math.max,qT=Math.min;Vd.exports=function(a,e){var t=NT(a);return t<0?FT(t+e,0):qT(t,e)}});var Fd=m((cM,Nd)=>{"use strict";var UT=Ma(),HT=Math.min;Nd.exports=function(a){var e=UT(a);return e>0?HT(e,9007199254740991):0}});var Ca=m((dM,qd)=>{"use strict";var jT=Fd();qd.exports=function(a){return jT(a.length)}});var jd=m((pM,Hd)=>{"use strict";var GT=sr(),YT=_d(),WT=Ca(),Ud=function(a){return function(e,t,r){var i=GT(e),s=WT(i);if(s===0)return!a&&-1;var n=YT(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}};Hd.exports={includes:Ud(!0),indexOf:Ud(!1)}});var Wd=m((hM,Yd)=>{"use strict";var QT=pe(),Xn=Fe(),zT=sr(),KT=jd().indexOf,JT=Ra(),Gd=QT([].push);Yd.exports=function(a,e){var t=zT(a),r=0,i=[],s;for(s in t)!Xn(JT,s)&&Xn(t,s)&&Gd(i,s);for(;e.length>r;)Xn(t,s=e[r++])&&(~KT(i,s)||Gd(i,s));return i}});var Zn=m((fM,Qd)=>{"use strict";Qd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Kd=m((mM,zd)=>{"use strict";var XT=Wd(),ZT=Zn();zd.exports=Object.keys||function(e){return XT(e,ZT)}});var Xd=m(Jd=>{"use strict";var eI=ke(),tI=xn(),rI=Ct(),iI=Qe(),aI=sr(),sI=Kd();Jd.f=eI&&!tI?Object.defineProperties:function(e,t){iI(e);for(var r=aI(t),i=sI(t),s=i.length,n=0,o;s>n;)rI.f(e,o=i[n++],r[o]);return e}});var eo=m((gM,Zd)=>{"use strict";var nI=Ze();Zd.exports=nI("document","documentElement")});var ao=m((SM,np)=>{"use strict";var oI=Qe(),uI=Xd(),ep=Zn(),lI=Ra(),cI=eo(),dI=Ea(),pI=ka(),tp=">",rp="<",ro="prototype",io="script",ap=pI("IE_PROTO"),to=function(){},sp=function(a){return rp+io+tp+a+rp+"/"+io+tp},ip=function(a){a.write(sp("")),a.close();var e=a.parentWindow.Object;return a=null,e},hI=function(){var a=dI("iframe"),e="java"+io+":",t;return a.style.display="none",cI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(sp("document.F=Object")),t.close(),t.F},Da,Oa=function(){try{Da=new ActiveXObject("htmlfile")}catch(e){}Oa=typeof document!="undefined"?document.domain&&Da?ip(Da):hI():ip(Da);for(var a=ep.length;a--;)delete Oa[ro][ep[a]];return Oa()};lI[ap]=!0;np.exports=Object.create||function(e,t){var r;return e!==null?(to[ro]=oI(e),r=new to,to[ro]=null,r[ap]=e):r=Oa(),t===void 0?r:uI.f(r,t)}});var up=m((vM,op)=>{"use strict";var fI=ye();op.exports=!fI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var no=m((yM,cp)=>{"use strict";var mI=Fe(),bI=Q(),gI=Qr(),SI=ka(),vI=up(),lp=SI("IE_PROTO"),so=Object,yI=so.prototype;cp.exports=vI?so.getPrototypeOf:function(a){var e=gI(a);if(mI(e,lp))return e[lp];var t=e.constructor;return bI(t)&&e instanceof t?t.prototype:e instanceof so?yI:null}});var dr=m((TM,dp)=>{"use strict";var TI=ur();dp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:TI(a,e,t),a}});var co=m((IM,fp)=>{"use strict";var II=ye(),EI=Q(),xI=we(),PI=ao(),pp=no(),AI=dr(),wI=ne(),kI=Ne(),lo=wI("iterator"),hp=!1,tt,oo,uo;[].keys&&(uo=[].keys(),"next"in uo?(oo=pp(pp(uo)),oo!==Object.prototype&&(tt=oo)):hp=!0);var RI=!xI(tt)||II(function(){var a={};return tt[lo].call(a)!==a});RI?tt={}:kI&&(tt=PI(tt));EI(tt[lo])||AI(tt,lo,function(){return this});fp.exports={IteratorPrototype:tt,BUGGY_SAFARI_ITERATORS:hp}});var Ba=m((EM,bp)=>{"use strict";var LI=ne(),$I=LI("toStringTag"),mp={};mp[$I]="z";bp.exports=String(mp)==="[object z]"});var ei=m((xM,gp)=>{"use strict";var MI=Ba(),CI=Q(),Va=ir(),DI=ne(),OI=DI("toStringTag"),BI=Object,VI=Va(function(){return arguments}())==="Arguments",_I=function(a,e){try{return a[e]}catch(t){}};gp.exports=MI?Va:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=_I(e=BI(a),OI))=="string"?t:VI?Va(e):(r=Va(e))==="Object"&&CI(e.callee)?"Arguments":r}});var vp=m((PM,Sp)=>{"use strict";var NI=Ba(),FI=ei();Sp.exports=NI?{}.toString:function(){return"[object "+FI(this)+"]"}});var ti=m((AM,Tp)=>{"use strict";var qI=Ba(),UI=Ct().f,HI=ur(),jI=Fe(),GI=vp(),YI=ne(),yp=YI("toStringTag");Tp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(jI(i,yp)||UI(i,yp,{configurable:!0,value:e}),r&&!qI&&HI(i,"toString",GI))}});var Ep=m((wM,Ip)=>{"use strict";var WI=co().IteratorPrototype,QI=ao(),zI=zr(),KI=ti(),JI=Mt(),XI=function(){return this};Ip.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=QI(WI,{next:zI(+!r,t)}),KI(a,i,!1,!0),JI[i]=XI,a}});var Pp=m((kM,xp)=>{"use strict";var ZI=pe(),eE=et();xp.exports=function(a,e,t){try{return ZI(eE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var wp=m((RM,Ap)=>{"use strict";var tE=we();Ap.exports=function(a){return tE(a)||a===null}});var Rp=m((LM,kp)=>{"use strict";var rE=wp(),iE=String,aE=TypeError;kp.exports=function(a){if(rE(a))return a;throw new aE("Can't set "+iE(a)+" as a prototype")}});var po=m(($M,Lp)=>{"use strict";var sE=Pp(),nE=we(),oE=Ur(),uE=Rp();Lp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=sE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return oE(i),uE(s),nE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var qp=m((MM,Fp)=>{"use strict";var lE=Re(),cE=Te(),_a=Ne(),_p=Cd(),dE=Q(),pE=Ep(),$p=no(),Mp=po(),hE=ti(),fE=ur(),ho=dr(),mE=ne(),Cp=Mt(),Np=co(),bE=_p.PROPER,gE=_p.CONFIGURABLE,Dp=Np.IteratorPrototype,Na=Np.BUGGY_SAFARI_ITERATORS,ri=mE("iterator"),Op="keys",ii="values",Bp="entries",Vp=function(){return this};Fp.exports=function(a,e,t,r,i,s,n){pE(t,e,r);var o=function(S){if(S===i&&p)return p;if(!Na&&S&&S in c)return c[S];switch(S){case Op:return function(){return new t(this,S)};case ii:return function(){return new t(this,S)};case Bp:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[ri]||c["@@iterator"]||i&&c[i],p=!Na&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=$p(h.call(new a)),f!==Object.prototype&&f.next&&(!_a&&$p(f)!==Dp&&(Mp?Mp(f,Dp):dE(f[ri])||ho(f,ri,Vp)),hE(f,u,!0,!0),_a&&(Cp[u]=Vp))),bE&&i===ii&&d&&d.name!==ii&&(!_a&&gE?fE(c,"name",ii):(l=!0,p=function(){return cE(d,this)})),i)if(b={values:o(ii),keys:s?p:o(Op),entries:o(Bp)},n)for(g in b)(Na||l||!(g in c))&&ho(c,g,b[g]);else lE({target:e,proto:!0,forced:Na||l},b);return(!_a||n)&&c[ri]!==p&&ho(c,ri,p,{name:i}),Cp[e]=p,b}});var Hp=m((CM,Up)=>{"use strict";Up.exports=function(a,e){return{value:a,done:e}}});var mo=m((DM,Qp)=>{"use strict";var SE=sr(),fo=vn(),jp=Mt(),Yp=Yn(),vE=Ct().f,yE=qp(),Fa=Hp(),TE=Ne(),IE=ke(),Wp="Array Iterator",EE=Yp.set,xE=Yp.getterFor(Wp);Qp.exports=yE(Array,"Array",function(a,e){EE(this,{type:Wp,target:SE(a),index:0,kind:e})},function(){var a=xE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Fa(void 0,!0);switch(a.kind){case"keys":return Fa(t,!1);case"values":return Fa(e[t],!1)}return Fa([t,e[t]],!1)},"values");var Gp=jp.Arguments=jp.Array;fo("keys");fo("values");fo("entries");if(!TE&&IE&&Gp.name!=="values")try{vE(Gp,"name",{value:"values"})}catch(a){}});var Kp=m((OM,zp)=>{"use strict";var PE=ne(),AE=Mt(),wE=PE("iterator"),kE=Array.prototype;zp.exports=function(a){return a!==void 0&&(AE.Array===a||kE[wE]===a)}});var bo=m((BM,Xp)=>{"use strict";var RE=ei(),Jp=Yr(),LE=ar(),$E=Mt(),ME=ne(),CE=ME("iterator");Xp.exports=function(a){if(!LE(a))return Jp(a,CE)||Jp(a,"@@iterator")||$E[RE(a)]}});var eh=m((VM,Zp)=>{"use strict";var DE=Te(),OE=et(),BE=Qe(),VE=Gr(),_E=bo(),NE=TypeError;Zp.exports=function(a,e){var t=arguments.length<2?_E(a):e;if(OE(t))return BE(DE(t,a));throw new NE(VE(a)+" is not iterable")}});var ih=m((_M,rh)=>{"use strict";var FE=Te(),th=Qe(),qE=Yr();rh.exports=function(a,e,t){var r,i;th(a);try{if(r=qE(a,"return"),!r){if(e==="throw")throw t;return t}r=FE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return th(r),t}});var Ua=m((NM,oh)=>{"use strict";var UE=Xr(),HE=Te(),jE=Qe(),GE=Gr(),YE=Kp(),WE=Ca(),ah=jr(),QE=eh(),zE=bo(),sh=ih(),KE=TypeError,qa=function(a,e){this.stopped=a,this.result=e},nh=qa.prototype;oh.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=UE(e,r),l,c,d,p,h,f,b,g=function(I){return l&&sh(l,"normal",I),new qa(!0,I)},S=function(I){return i?(jE(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=zE(a),!c)throw new KE(GE(a)+" is not iterable");if(YE(c)){for(d=0,p=WE(a);p>d;d++)if(h=S(a[d]),h&&ah(nh,h))return h;return new qa(!1)}l=QE(a,c)}for(f=s?a.next:l.next;!(b=HE(f,l)).done;){try{h=S(b.value)}catch(I){sh(l,"throw",I)}if(typeof h=="object"&&h&&ah(nh,h))return h}return new qa(!1)}});var lh=m((FM,uh)=>{"use strict";var JE=ke(),XE=Ct(),ZE=zr();uh.exports=function(a,e,t){JE?XE.f(a,e,ZE(0,t)):a[e]=t}});var ch=m(()=>{"use strict";var ex=Re(),tx=Ua(),rx=lh();ex({target:"Object",stat:!0},{fromEntries:function(e){var t={};return tx(e,function(r,i){rx(t,r,i)},{AS_ENTRIES:!0}),t}})});var ph=m((HM,dh)=>{"use strict";mo();ch();var ix=Pa();dh.exports=ix.Object.fromEntries});var fh=m((jM,hh)=>{"use strict";hh.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 bh=m(()=>{"use strict";mo();var ax=fh(),sx=z(),nx=ti(),mh=Mt();for(Ha in ax)nx(sx[Ha],Ha),mh[Ha]=mh.Array;var Ha});var Sh=m((WM,gh)=>{"use strict";var ox=ph();bh();gh.exports=ox});var go=m((QM,vh)=>{"use strict";var ux=Sh();vh.exports=ux});var yh=m(()=>{"use strict"});var So=m((JM,Th)=>{"use strict";var ai=z(),lx=nr(),cx=ir(),ja=function(a){return lx.slice(0,a.length)===a};Th.exports=function(){return ja("Bun/")?"BUN":ja("Cloudflare-Workers")?"CLOUDFLARE":ja("Deno/")?"DENO":ja("Node.js/")?"NODE":ai.Bun&&typeof Bun.version=="string"?"BUN":ai.Deno&&typeof Deno.version=="object"?"DENO":cx(ai.process)==="process"?"NODE":ai.window&&ai.document?"BROWSER":"REST"}()});var Ga=m((XM,Ih)=>{"use strict";var dx=So();Ih.exports=dx==="NODE"});var xh=m((ZM,Eh)=>{"use strict";var px=Ct();Eh.exports=function(a,e,t){return px.f(a,e,t)}});var wh=m((eC,Ah)=>{"use strict";var hx=Ze(),fx=xh(),mx=ne(),bx=ke(),Ph=mx("species");Ah.exports=function(a){var e=hx(a);bx&&e&&!e[Ph]&&fx(e,Ph,{configurable:!0,get:function(){return this}})}});var Rh=m((tC,kh)=>{"use strict";var gx=jr(),Sx=TypeError;kh.exports=function(a,e){if(gx(e,a))return a;throw new Sx("Incorrect invocation")}});var yo=m((rC,Lh)=>{"use strict";var vx=pe(),yx=Q(),vo=Wr(),Tx=vx(Function.toString);yx(vo.inspectSource)||(vo.inspectSource=function(a){return Tx(a)});Lh.exports=vo.inspectSource});var Bh=m((iC,Oh)=>{"use strict";var Ix=pe(),Ex=ye(),$h=Q(),xx=ei(),Px=Ze(),Ax=yo(),Mh=function(){},Ch=Px("Reflect","construct"),To=/^\s*(?:class|function)\b/,wx=Ix(To.exec),kx=!To.test(Mh),si=function(e){if(!$h(e))return!1;try{return Ch(Mh,[],e),!0}catch(t){return!1}},Dh=function(e){if(!$h(e))return!1;switch(xx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return kx||!!wx(To,Ax(e))}catch(t){return!0}};Dh.sham=!0;Oh.exports=!Ch||Ex(function(){var a;return si(si.call)||!si(Object)||!si(function(){a=!0})||a})?Dh:si});var _h=m((aC,Vh)=>{"use strict";var Rx=Bh(),Lx=Gr(),$x=TypeError;Vh.exports=function(a){if(Rx(a))return a;throw new $x(Lx(a)+" is not a constructor")}});var Io=m((sC,Fh)=>{"use strict";var Nh=Qe(),Mx=_h(),Cx=ar(),Dx=ne(),Ox=Dx("species");Fh.exports=function(a,e){var t=Nh(a).constructor,r;return t===void 0||Cx(r=Nh(t)[Ox])?e:Mx(r)}});var Uh=m((nC,qh)=>{"use strict";var Bx=pe();qh.exports=Bx([].slice)});var jh=m((oC,Hh)=>{"use strict";var Vx=TypeError;Hh.exports=function(a,e){if(a<e)throw new Vx("Not enough arguments");return a}});var Eo=m((uC,Gh)=>{"use strict";var _x=nr();Gh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(_x)});var Mo=m((lC,ef)=>{"use strict";var Ie=z(),Nx=Wn(),Fx=Xr(),Yh=Q(),qx=Fe(),Zh=ye(),Wh=eo(),Ux=Uh(),Qh=Ea(),Hx=jh(),jx=Eo(),Gx=Ga(),Ro=Ie.setImmediate,Lo=Ie.clearImmediate,Yx=Ie.process,xo=Ie.Dispatch,Wx=Ie.Function,zh=Ie.MessageChannel,Qx=Ie.String,Po=0,ni={},Kh="onreadystatechange",oi,Ot,Ao,wo;Zh(function(){oi=Ie.location});var $o=function(a){if(qx(ni,a)){var e=ni[a];delete ni[a],e()}},ko=function(a){return function(){$o(a)}},Jh=function(a){$o(a.data)},Xh=function(a){Ie.postMessage(Qx(a),oi.protocol+"//"+oi.host)};(!Ro||!Lo)&&(Ro=function(e){Hx(arguments.length,1);var t=Yh(e)?e:Wx(e),r=Ux(arguments,1);return ni[++Po]=function(){Nx(t,void 0,r)},Ot(Po),Po},Lo=function(e){delete ni[e]},Gx?Ot=function(a){Yx.nextTick(ko(a))}:xo&&xo.now?Ot=function(a){xo.now(ko(a))}:zh&&!jx?(Ao=new zh,wo=Ao.port2,Ao.port1.onmessage=Jh,Ot=Fx(wo.postMessage,wo)):Ie.addEventListener&&Yh(Ie.postMessage)&&!Ie.importScripts&&oi&&oi.protocol!=="file:"&&!Zh(Xh)?(Ot=Xh,Ie.addEventListener("message",Jh,!1)):Kh in Qh("script")?Ot=function(a){Wh.appendChild(Qh("script"))[Kh]=function(){Wh.removeChild(this),$o(a)}}:Ot=function(a){setTimeout(ko(a),0)});ef.exports={set:Ro,clear:Lo}});var af=m((cC,rf)=>{"use strict";var tf=z(),zx=ke(),Kx=Object.getOwnPropertyDescriptor;rf.exports=function(a){if(!zx)return tf[a];var e=Kx(tf,a);return e&&e.value}});var Co=m((dC,nf)=>{"use strict";var sf=function(){this.head=null,this.tail=null};sf.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}}};nf.exports=sf});var uf=m((pC,of)=>{"use strict";var Jx=nr();of.exports=/ipad|iphone|ipod/i.test(Jx)&&typeof Pebble!="undefined"});var cf=m((hC,lf)=>{"use strict";var Xx=nr();lf.exports=/web0s(?!.*chrome)/i.test(Xx)});var gf=m((fC,bf)=>{"use strict";var hr=z(),Zx=af(),df=Xr(),Do=Mo().set,eP=Co(),tP=Eo(),rP=uf(),iP=cf(),Oo=Ga(),pf=hr.MutationObserver||hr.WebKitMutationObserver,hf=hr.document,ff=hr.process,Ya=hr.Promise,_o=Zx("queueMicrotask"),pr,Bo,Vo,Wa,mf;_o||(ui=new eP,li=function(){var a,e;for(Oo&&(a=ff.domain)&&a.exit();e=ui.get();)try{e()}catch(t){throw ui.head&&pr(),t}a&&a.enter()},!tP&&!Oo&&!iP&&pf&&hf?(Bo=!0,Vo=hf.createTextNode(""),new pf(li).observe(Vo,{characterData:!0}),pr=function(){Vo.data=Bo=!Bo}):!rP&&Ya&&Ya.resolve?(Wa=Ya.resolve(void 0),Wa.constructor=Ya,mf=df(Wa.then,Wa),pr=function(){mf(li)}):Oo?pr=function(){ff.nextTick(li)}:(Do=df(Do,hr),pr=function(){Do(li)}),_o=function(a){ui.head||pr(),ui.add(a)});var ui,li;bf.exports=_o});var vf=m((mC,Sf)=>{"use strict";Sf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Qa=m((bC,yf)=>{"use strict";yf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Bt=m((gC,Tf)=>{"use strict";var aP=z();Tf.exports=aP.Promise});var fr=m((SC,Pf)=>{"use strict";var sP=z(),ci=Bt(),nP=Q(),oP=zn(),uP=yo(),lP=ne(),If=So(),cP=Ne(),No=kn(),Ef=ci&&ci.prototype,dP=lP("species"),Fo=!1,xf=nP(sP.PromiseRejectionEvent),pP=oP("Promise",function(){var a=uP(ci),e=a!==String(ci);if(!e&&No===66||cP&&!(Ef.catch&&Ef.finally))return!0;if(!No||No<51||!/native code/.test(a)){var t=new ci(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[dP]=r,Fo=t.then(function(){})instanceof r,!Fo)return!0}return!e&&(If==="BROWSER"||If==="DENO")&&!xf});Pf.exports={CONSTRUCTOR:pP,REJECTION_EVENT:xf,SUBCLASSING:Fo}});var mr=m((vC,wf)=>{"use strict";var Af=et(),hP=TypeError,fP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new hP("Bad Promise constructor");e=r,t=i}),this.resolve=Af(e),this.reject=Af(t)};wf.exports.f=function(a){return new fP(a)}});var Yf=m(()=>{"use strict";var mP=Re(),bP=Ne(),Xa=Ga(),mt=z(),vr=Te(),kf=dr(),Rf=po(),gP=ti(),SP=wh(),vP=et(),Ja=Q(),yP=we(),TP=Rh(),IP=Io(),Df=Mo().set,Go=gf(),EP=vf(),xP=Qa(),PP=Co(),Of=Yn(),Za=Bt(),Yo=fr(),Bf=mr(),es="Promise",Vf=Yo.CONSTRUCTOR,AP=Yo.REJECTION_EVENT,wP=Yo.SUBCLASSING,qo=Of.getterFor(es),kP=Of.set,br=Za&&Za.prototype,Vt=Za,za=br,_f=mt.TypeError,Uo=mt.document,Wo=mt.process,Ho=Bf.f,RP=Ho,LP=!!(Uo&&Uo.createEvent&&mt.dispatchEvent),Nf="unhandledrejection",$P="rejectionhandled",Lf=0,Ff=1,MP=2,Qo=1,qf=2,Ka,$f,CP,Mf,Uf=function(a){var e;return yP(a)&&Ja(e=a.then)?e:!1},Hf=function(a,e){var t=e.value,r=e.state===Ff,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===qf&&OP(e),e.rejection=Qo),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new _f("Promise-chain cycle")):(l=Uf(u))?vr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},jf=function(a,e){a.notified||(a.notified=!0,Go(function(){for(var t=a.reactions,r;r=t.get();)Hf(r,a);a.notified=!1,e&&!a.rejection&&DP(a)}))},Gf=function(a,e,t){var r,i;LP?(r=Uo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),mt.dispatchEvent(r)):r={promise:e,reason:t},!AP&&(i=mt["on"+a])?i(r):a===Nf&&EP("Unhandled promise rejection",t)},DP=function(a){vr(Df,mt,function(){var e=a.facade,t=a.value,r=Cf(a),i;if(r&&(i=xP(function(){Xa?Wo.emit("unhandledRejection",t,e):Gf(Nf,e,t)}),a.rejection=Xa||Cf(a)?qf:Qo,i.error))throw i.value})},Cf=function(a){return a.rejection!==Qo&&!a.parent},OP=function(a){vr(Df,mt,function(){var e=a.facade;Xa?Wo.emit("rejectionHandled",e):Gf($P,e,a.value)})},gr=function(a,e,t){return function(r){a(e,r,t)}},Sr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=MP,jf(a,!0))},jo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new _f("Promise can't be resolved itself");var r=Uf(e);r?Go(function(){var i={done:!1};try{vr(r,e,gr(jo,i,a),gr(Sr,i,a))}catch(s){Sr(i,s,a)}}):(a.value=e,a.state=Ff,jf(a,!1))}catch(i){Sr({done:!1},i,a)}}};if(Vf&&(Vt=function(e){TP(this,za),vP(e),vr(Ka,this);var t=qo(this);try{e(gr(jo,t),gr(Sr,t))}catch(r){Sr(t,r)}},za=Vt.prototype,Ka=function(e){kP(this,{type:es,done:!1,notified:!1,parent:!1,reactions:new PP,rejection:!1,state:Lf,value:void 0})},Ka.prototype=kf(za,"then",function(e,t){var r=qo(this),i=Ho(IP(this,Vt));return r.parent=!0,i.ok=Ja(e)?e:!0,i.fail=Ja(t)&&t,i.domain=Xa?Wo.domain:void 0,r.state===Lf?r.reactions.add(i):Go(function(){Hf(i,r)}),i.promise}),$f=function(){var a=new Ka,e=qo(a);this.promise=a,this.resolve=gr(jo,e),this.reject=gr(Sr,e)},Bf.f=Ho=function(a){return a===Vt||a===CP?new $f(a):RP(a)},!bP&&Ja(Za)&&br!==Object.prototype)){Mf=br.then,wP||kf(br,"then",function(e,t){var r=this;return new Vt(function(i,s){vr(Mf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete br.constructor}catch(a){}Rf&&Rf(br,za)}mP({global:!0,constructor:!0,wrap:!0,forced:Vf},{Promise:Vt});gP(Vt,es,!1,!0);SP(es)});var Jf=m((IC,Kf)=>{"use strict";var BP=ne(),Qf=BP("iterator"),zf=!1;try{Wf=0,zo={next:function(){return{done:!!Wf++}},return:function(){zf=!0}},zo[Qf]=function(){return this},Array.from(zo,function(){throw 2})}catch(a){}var Wf,zo;Kf.exports=function(a,e){try{if(!e&&!zf)return!1}catch(i){return!1}var t=!1;try{var r={};r[Qf]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Ko=m((EC,Xf)=>{"use strict";var VP=Bt(),_P=Jf(),NP=fr().CONSTRUCTOR;Xf.exports=NP||!_P(function(a){VP.all(a).then(void 0,function(){})})});var Zf=m(()=>{"use strict";var FP=Re(),qP=Te(),UP=et(),HP=mr(),jP=Qa(),GP=Ua(),YP=Ko();FP({target:"Promise",stat:!0,forced:YP},{all:function(e){var t=this,r=HP.f(t),i=r.resolve,s=r.reject,n=jP(function(){var o=UP(t.resolve),u=[],l=0,c=1;GP(e,function(d){var p=l++,h=!1;c++,qP(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 tm=m(()=>{"use strict";var WP=Re(),QP=Ne(),zP=fr().CONSTRUCTOR,Xo=Bt(),KP=Ze(),JP=Q(),XP=dr(),em=Xo&&Xo.prototype;WP({target:"Promise",proto:!0,forced:zP,real:!0},{catch:function(a){return this.then(void 0,a)}});!QP&&JP(Xo)&&(Jo=KP("Promise").prototype.catch,em.catch!==Jo&&XP(em,"catch",Jo,{unsafe:!0}));var Jo});var rm=m(()=>{"use strict";var ZP=Re(),eA=Te(),tA=et(),rA=mr(),iA=Qa(),aA=Ua(),sA=Ko();ZP({target:"Promise",stat:!0,forced:sA},{race:function(e){var t=this,r=rA.f(t),i=r.reject,s=iA(function(){var n=tA(t.resolve);aA(e,function(o){eA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var im=m(()=>{"use strict";var nA=Re(),oA=mr(),uA=fr().CONSTRUCTOR;nA({target:"Promise",stat:!0,forced:uA},{reject:function(e){var t=oA.f(this),r=t.reject;return r(e),t.promise}})});var Zo=m((MC,am)=>{"use strict";var lA=Qe(),cA=we(),dA=mr();am.exports=function(a,e){if(lA(a),cA(e)&&e.constructor===a)return e;var t=dA.f(a),r=t.resolve;return r(e),t.promise}});var om=m(()=>{"use strict";var pA=Re(),hA=Ze(),sm=Ne(),fA=Bt(),nm=fr().CONSTRUCTOR,mA=Zo(),bA=hA("Promise"),gA=sm&&!nm;pA({target:"Promise",stat:!0,forced:sm||nm},{resolve:function(e){return mA(gA&&this===bA?fA:this,e)}})});var um=m(()=>{"use strict";Yf();Zf();tm();rm();im();om()});var pm=m(()=>{"use strict";var SA=Re(),vA=Ne(),ts=Bt(),yA=ye(),cm=Ze(),dm=Q(),TA=Io(),lm=Zo(),IA=dr(),tu=ts&&ts.prototype,EA=!!ts&&yA(function(){tu.finally.call({then:function(){}},function(){})});SA({target:"Promise",proto:!0,real:!0,forced:EA},{finally:function(a){var e=TA(this,cm("Promise")),t=dm(a);return this.then(t?function(r){return lm(e,a()).then(function(){return r})}:a,t?function(r){return lm(e,a()).then(function(){throw r})}:a)}});!vA&&dm(ts)&&(eu=cm("Promise").prototype.finally,tu.finally!==eu&&IA(tu,"finally",eu,{unsafe:!0}));var eu});var rs=m((NC,hm)=>{"use strict";var xA=Ze();hm.exports=xA});var mm=m((FC,fm)=>{"use strict";yh();um();pm();var PA=rs();fm.exports=PA("Promise","finally")});var gm=m((qC,bm)=>{"use strict";var AA=mm();bm.exports=AA});var is=m((UC,Sm)=>{"use strict";var wA=gm();Sm.exports=wA});var Hm=m(()=>{"use strict";var rw=Re(),iw=Qr(),aw=Ca(),sw=Ma(),nw=vn();rw({target:"Array",proto:!0},{at:function(e){var t=iw(this),r=aw(t),i=sw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});nw("at")});var Gm=m((JD,jm)=>{"use strict";Hm();var ow=rs();jm.exports=ow("Array","at")});var Wm=m((XD,Ym)=>{"use strict";var uw=Gm();Ym.exports=uw});var fi=m((ZD,Qm)=>{"use strict";var lw=Wm();Qm.exports=lw});var Xb=m(()=>{"use strict"});var Zb=m(()=>{"use strict"});var tg=m((n_,eg)=>{"use strict";var bk=we(),gk=ir(),Sk=ne(),vk=Sk("match");eg.exports=function(a){var e;return bk(a)&&((e=a[vk])!==void 0?!!e:gk(a)==="RegExp")}});var ig=m((o_,rg)=>{"use strict";var yk=ei(),Tk=String;rg.exports=function(a){if(yk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Tk(a)}});var sg=m((u_,ag)=>{"use strict";var Ik=Qe();ag.exports=function(){var a=Ik(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 ug=m((l_,og)=>{"use strict";var Ek=Te(),xk=Fe(),Pk=jr(),Ak=sg(),ng=RegExp.prototype;og.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in ng)&&!xk(a,"flags")&&Pk(ng,a)?Ek(Ak,a):e}});var cg=m((c_,lg)=>{"use strict";var $u=pe(),wk=Qr(),kk=Math.floor,Ru=$u("".charAt),Rk=$u("".replace),Lu=$u("".slice),Lk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,$k=/\$([$&'`]|\d{1,2})/g;lg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=$k;return i!==void 0&&(i=wk(i),u=Lk),Rk(s,u,function(l,c){var d;switch(Ru(c,0)){case"$":return"$";case"&":return a;case"`":return Lu(e,0,t);case"'":return Lu(e,n);case"<":d=i[Lu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=kk(p/10);return h===0?l:h<=o?r[h-1]===void 0?Ru(c,1):r[h-1]+Ru(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var hg=m(()=>{"use strict";var Mk=Re(),Ck=Te(),Cu=pe(),dg=Ur(),Dk=Q(),Ok=ar(),Bk=tg(),Rr=ig(),Vk=Yr(),_k=ug(),Nk=cg(),Fk=ne(),qk=Ne(),Uk=Fk("replace"),Hk=TypeError,Mu=Cu("".indexOf),jk=Cu("".replace),pg=Cu("".slice),Gk=Math.max;Mk({target:"String",proto:!0},{replaceAll:function(e,t){var r=dg(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!Ok(e)){if(i=Bk(e),i&&(s=Rr(dg(_k(e))),!~Mu(s,"g")))throw new Hk("`.replaceAll` does not allow non-global regexes");if(n=Vk(e,Uk),n)return Ck(n,e,r,t);if(qk&&i)return jk(Rr(r),e,t)}for(o=Rr(r),u=Rr(e),l=Dk(t),l||(t=Rr(t)),c=u.length,d=Gk(1,c),p=Mu(o,u);p!==-1;)h=l?Rr(t(u,p,o)):Nk(u,o,p,[],void 0,t),b+=pg(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Mu(o,u,p+d);return f<o.length&&(b+=pg(o,f)),b}})});var mg=m((h_,fg)=>{"use strict";Xb();Zb();hg();var Yk=rs();fg.exports=Yk("String","replaceAll")});var gg=m((f_,bg)=>{"use strict";var Wk=mg();bg.exports=Wk});var vg=m((m_,Sg)=>{"use strict";var Qk=gg();Sg.exports=Qk});var Vl="2.0.108-dev.43b53ca1.0";var de=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(de||{}),ft=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(ft||{});var ya=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ya||{}),hn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(hn||{});var fn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(fn||{});import{assertNever as Hl,assertNonNullable as hv,isNonNullable as Ta,ValueSubject as mn,Subject as fv,Subscription as mv,merge as bv,observableFrom as gv,fromEvent as Nl,map as Fl,tap as ql,filterChanged as Sv,isNullable as bn,ErrorCategory as Ul}from"@vkontakte/videoplayer-shared";var _l=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Ia=class{constructor(e){this.connection$=new mn(void 0);this.castState$=new mn("NOT_AVAILABLE");this.errorEvent$=new fv;this.realCastState$=new mn("NOT_AVAILABLE");this.subscription=new mv;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=Ta((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||_l("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Ul.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ta(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();bn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();bn(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Nl(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Hl(i.sessionState)}})).add(bv(Nl(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ql(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Fl(i=>i.castState)),gv([r.getCastState()])).pipe(Sv(),Fl(vv),ql(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o;let s=i==="CONNECTED",n=Ta(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();hv(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;(bn(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?Ta(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Ul.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},vv=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Hl(a)}};var SS=We(go(),1);var km=We(is(),1);import{assertNever as vm}from"@vkontakte/videoplayer-shared";var se=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:vm(t)}return a},ru=(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 kA,Subject as as,merge as ym}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new as;this.transitionEnded$=new as;this.transitionUpdated$=new as;this.forceChanged$=new as;this.stateChangeStarted$=ym(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=ym(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||kA(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 RA}from"@vkontakte/videoplayer-shared";var Tm=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 RA(a)}};import{assertNever as yr,assertNonNullable as _t,debounce as Im,ErrorCategory as Em,fromEvent as Nt,isNonNullable as xm,map as Pm,merge as Am,observableFrom as LA,Subject as $A,Subscription as iu,timeout as MA,getHighestQuality as CA}from"@vkontakte/videoplayer-shared";var DA=5,OA=5,BA=500,wm=7e3,di=class{constructor(e){this.subscription=new iu;this.loadMediaTimeoutSubscription=new iu;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:yr(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:yr(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:yr(e)}break}default:yr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Tm(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new iu;this.subscription.add(e),this.subscription.add(Am(this.videoState.stateChangeStarted$.pipe(Pm(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Pm(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new $A;e.add(i.pipe(Im(BA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Nt(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)>DA)&&i.next(o),s=o})),e.add(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Nt(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<OA&&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:yr(n)}}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Am(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,LA(["init"])).pipe(Im(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&E(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];_t(c);let d=CA(Object.keys(c));_t(d);let p=c[d];_t(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];_t(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];_t(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];_t(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];_t(c),r=se(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Em.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return yr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return xm(o)&&(n.metadata.title=o),xm(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(MA(wm).subscribe(()=>s(`timeout(${wm})`)))});(0,km.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:Em.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Lm}from"@vkontakte/videoplayer-shared";import{clearVideoElement as VA}from"@vkontakte/videoplayer-shared";var Rm=a=>{try{a.pause(),a.playbackRate=0,VA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as _A,Subscription as NA}from"@vkontakte/videoplayer-shared";var au=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)}},su=window.WeakMap?new WeakMap:new au,nu=window.WeakMap?new WeakMap:new Map,FA=(a,e=20)=>{let t=0;return _A(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},he=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Lm(t):(t=document.createElement("video"),a.appendChild(t)),su.set(t,r);let i=new NA;return i.add(FA(t,e)),nu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},fe=a=>{let e=nu.get(a);e==null||e.unsubscribe(),nu.delete(a);let t=su.get(a);su.delete(a),t?Lm(a):Rm(a)};import{assertNonNullable as pi,isNonNullable as Ke,isNullable as HA,fromEvent as Tr,merge as $m,observableFrom as Mm,filterChanged as Cm,map as hi,Subject as Dm,Subscription as jA,ValueSubject as GA,ErrorCategory as YA}from"@vkontakte/videoplayer-shared";import{isNonNullable as ou,isNullable as qA,Subscription as UA}from"@vkontakte/videoplayer-shared";var ss=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=qA(i),l=new UA;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},ze=(a,e,t)=>ss(e,()=>a.loop,r=>{ou(r)&&(a.loop=r)},{onError:t}),me=(a,e,t,r)=>ss(e,()=>({muted:a.muted,volume:a.volume}),i=>{ou(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)=>ss(e,()=>a.playbackRate,i=>{ou(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),bt=ss;var WA=a=>["__",a.language,a.label].join("|"),QA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},uu=class a{constructor(){this.available$=new Dm;this.current$=new GA(void 0);this.error$=new Dm;this.subscription=new jA;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:YA.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(bt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Ke(s)&&this.setInternal(s)},{equal:(s,n)=>Ke(s)&&Ke(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(hi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(bt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Ke(s)&&this.setExternal(s)},{equal:(s,n)=>Ke(s)&&Ke(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(hi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(bt(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(bt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){pi(this.video);let{textTracks:e}=this.video;this.subscription.add(Tr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add($m(Tr(e,"addtrack"),Tr(e,"removetrack"),Mm(["init"])).pipe(hi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Cm((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add($m(Tr(e,"change"),Mm(["init"])).pipe(hi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),hi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Cm()).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(Tr(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(Tr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;Ke(t.align)&&(i.align=t.align),Ke(t.position)&&(i.position=t.position),Ke(t.size)&&(i.size=t.size),Ke(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){pi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,i=e.id?e.id:WA(e),s=this.externalTracks.has(i),n=i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(i))==null?void 0:o.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(i))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){pi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(HA(e)||!QA(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){pi(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){pi(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)}},$e=uu;var it=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 Om=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},lu=a=>{let e=Om(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Bm=a=>{let e=Om(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Me,map as gt,merge as _m,filterChanged as KA,isNonNullable as Nm,Subject as JA,filter as Fm,mapTo as qm,combine as XA,once as ZA,ErrorCategory as ew,ValueSubject as Um,clientChecker as tw}from"@vkontakte/videoplayer-shared";var zA=3,Vm=(a,e,t=zA)=>{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 be=a=>{let e=v=>Me(a,v).pipe(qm(void 0)),r=_m(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>Me(a,v))).pipe(gt(v=>v.type==="ended"?a.readyState<2:a.readyState<3),KA()),i=_m(Me(a,"progress"),Me(a,"timeupdate")).pipe(gt(()=>Vm(a.buffered,a.currentTime))),s=tw.isSafari?XA({play:e("play").pipe(ZA()),playing:e("playing")}).pipe(qm(void 0)):e("playing"),n=Me(a,"volumechange").pipe(gt(()=>({muted:a.muted,volume:a.volume}))),o=Me(a,"ratechange").pipe(gt(()=>a.playbackRate)),u=Me(a,"error").pipe(Fm(()=>!!(a.error||a.played.length)),gt(()=>{var y;let v=a.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:ew.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(y=a.error)!=null?y:void 0}})),l=Me(a,"timeupdate").pipe(gt(()=>a.currentTime)),c=new JA,d=.3,p;l.subscribe(v=>{a.loop&&Nm(p)&&Nm(v)&&p>=a.duration-d&&v<=d&&c.next(p),p=v});let h=e("pause").pipe(Fm(()=>!a.error&&p!==a.duration)),f=Me(a,"enterpictureinpicture"),b=Me(a,"leavepictureinpicture"),g=new Um(Bm(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new Um(lu(a));return Me(a,"fullscreenchange").pipe(gt(()=>lu(a))).subscribe(S),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Me(a,"durationchange").pipe(gt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S}};import{VideoQuality as St}from"@vkontakte/videoplayer-shared";var vt=a=>{switch(a){case"mobile":return St.Q_144P;case"lowest":return St.Q_240P;case"low":return St.Q_360P;case"sd":case"medium":return St.Q_480P;case"hd":case"high":return St.Q_720P;case"fullhd":case"full":return St.Q_1080P;case"quadhd":case"quad":return St.Q_1440P;case"ultrahd":case"ultra":return St.Q_2160P}};var Ft=We(fi(),1);import{isNonNullable as Ee,isNullable as du,now as tb,isHigher as pu,isHigherOrEqual as Xm,isInvariantQuality as Zm,isLower as hu,isLowerOrEqual as cw,videoSizeToQuality as dw,assertNotEmptyArray as rb,assertNonNullable as pw}from"@vkontakte/videoplayer-shared";var cu=!1,at={},zm=a=>{cu=a},Km=()=>{at={}},Jm=a=>{a(at)},mi=(a,e)=>{var t;cu&&(at.meta=(t=at.meta)!=null?t:{},at.meta[a]=e)},oe=class{constructor(e){this.name=e}next(e){var r,i;if(!cu)return;at.series=(r=at.series)!=null?r:{};let t=(i=at.series[this.name])!=null?i:[];t.push([Date.now(),e]),at.series[this.name]=t}};var hw=new oe("best_bitrate"),ib=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var fu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),bi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=tb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ab='Assertion "ABR Tracks is empty array" failed',ns=(a,e,t,r)=>{var u;let i=[...e].sort(fu(1)),s=[...t].sort(fu(1)),n=s.filter(l=>Ee(l.bitrate)&&Ee(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Ft.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Ft.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Ft.default)(n,-1):(0,Ft.default)(s,0)},eb=a=>"quality"in a,sb=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&tb()-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=eb(s)?"video":"audio",o=eb(s)?s.quality:s.bitrate;return e({message:`
|
|
7
|
-
[
|
|
8
|
-
`}),s}return r==null||r.recordSwitch(t),t},yt=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{var O,q,$,A,U;rb(a,ab);let p=r.usePixelRatio&&(O=window.devicePixelRatio)!=null?O:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},f=h&&dw(h),b=r.considerPlaybackRate&&Ee(o)?o:1,g=a.filter(k=>!Zm(k.quality)).sort((k,J)=>pu(k.quality,J.quality)?-1:1),S=(q=(0,Ft.default)(g,-1))==null?void 0:q.quality,I=($=(0,Ft.default)(g,0))==null?void 0:$.quality,v=du(i)||Ee(i.min)&&Ee(i.max)&&hu(i.max,i.min)||Ee(i.min)&&I&&pu(i.min,I)||Ee(i.max)&&S&&hu(i.max,S),y=b*ib(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),T={},D=g.filter(k=>(f?hu(k.quality,f):!0)?(Ee(t)&&isFinite(t)&&Ee(k.bitrate)?t-s>=k.bitrate*y:!0)?r.lazyQualitySwitch&&Ee(r.minBufferToSwitchUp)&&u&&!Zm(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&pu(k.quality,u.quality)?(T[k.quality]="Buffer",!1):!!c&&Xm(k.quality,c)?(T[k.quality]="DroppedFramesLimit",!1):v||(du(i.max)||cw(k.quality,i.max))&&(du(i.min)||Xm(k.quality,i.min))?!0:(T[k.quality]="FitsQualityLimits",!1):(T[k.quality]="FitsThroughput",!1):(T[k.quality]="FitsContainer",!1))[0];D&&D.bitrate&&hw.next(D.bitrate);let j=(A=D!=null?D:g[Math.ceil((g.length-1)/2)])!=null?A:a[0];return j.quality!==((U=l==null?void 0:l.last)==null?void 0:U.quality)&&d({message:`
|
|
9
|
-
[VIDEO TRACKS ABR]
|
|
10
|
-
[available video tracks]
|
|
6
|
+
var zS=Object.create;var cn=Object.defineProperty,KS=Object.defineProperties,JS=Object.getOwnPropertyDescriptor,XS=Object.getOwnPropertyDescriptors,ZS=Object.getOwnPropertyNames,Ml=Object.getOwnPropertySymbols,ev=Object.getPrototypeOf,Dl=Object.prototype.hasOwnProperty,tv=Object.prototype.propertyIsEnumerable;var rv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var je=Math.pow,Cl=(a,e,t)=>e in a?cn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,R=(a,e)=>{for(var t in e||(e={}))Dl.call(e,t)&&Cl(a,t,e[t]);if(Ml)for(var t of Ml(e))tv.call(e,t)&&Cl(a,t,e[t]);return a},q=(a,e)=>KS(a,XS(e));var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var iv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ZS(e))!Dl.call(a,i)&&i!==t&&cn(a,i,{get:()=>e[i],enumerable:!(r=JS(e,i))||r.enumerable});return a};var Ge=(a,e,t)=>(t=a!=null?zS(ev(a)):{},iv(e||!a||!a.__esModule?cn(t,"default",{value:a,enumerable:!0}):t,a));var A=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),av=function(a,e){this[0]=a,this[1]=e},te=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof av,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[rv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var ye=m((t$,Ul)=>{"use strict";Ul.exports=function(a){try{return!!a()}catch(e){return!0}}});var Fr=m((r$,Hl)=>{"use strict";var pv=ye();Hl.exports=!pv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var de=m((i$,Yl)=>{"use strict";var jl=Fr(),Gl=Function.prototype,mn=Gl.call,hv=jl&&Gl.bind.bind(mn,mn);Yl.exports=jl?hv:function(a){return function(){return mn.apply(a,arguments)}}});var rr=m((a$,Ql)=>{"use strict";var Wl=de(),fv=Wl({}.toString),mv=Wl("".slice);Ql.exports=function(a){return mv(fv(a),8,-1)}});var Kl=m((s$,zl)=>{"use strict";var bv=de(),gv=ye(),Sv=rr(),bn=Object,vv=bv("".split);zl.exports=gv(function(){return!bn("z").propertyIsEnumerable(0)})?function(a){return Sv(a)==="String"?vv(a,""):bn(a)}:bn});var ir=m((n$,Jl)=>{"use strict";Jl.exports=function(a){return a==null}});var qr=m((o$,Xl)=>{"use strict";var yv=ir(),Tv=TypeError;Xl.exports=function(a){if(yv(a))throw new Tv("Can't call method on "+a);return a}});var ar=m((u$,Zl)=>{"use strict";var Iv=Kl(),Ev=qr();Zl.exports=function(a){return Iv(Ev(a))}});var gn=m((l$,ec)=>{"use strict";ec.exports=function(){}});var Lt=m((c$,tc)=>{"use strict";tc.exports={}});var K=m((Sn,rc)=>{"use strict";var Ur=function(a){return a&&a.Math===Math&&a};rc.exports=Ur(typeof globalThis=="object"&&globalThis)||Ur(typeof window=="object"&&window)||Ur(typeof self=="object"&&self)||Ur(typeof global=="object"&&global)||Ur(typeof Sn=="object"&&Sn)||function(){return this}()||Function("return this")()});var z=m((d$,ic)=>{"use strict";var vn=typeof document=="object"&&document.all;ic.exports=typeof vn=="undefined"&&vn!==void 0?function(a){return typeof a=="function"||a===vn}:function(a){return typeof a=="function"}});var nc=m((p$,sc)=>{"use strict";var xv=K(),Pv=z(),ac=xv.WeakMap;sc.exports=Pv(ac)&&/native code/.test(String(ac))});var we=m((h$,oc)=>{"use strict";var wv=z();oc.exports=function(a){return typeof a=="object"?a!==null:wv(a)}});var Ae=m((f$,uc)=>{"use strict";var Av=ye();uc.exports=!Av(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ta=m((m$,cc)=>{"use strict";var kv=K(),lc=we(),yn=kv.document,Rv=lc(yn)&&lc(yn.createElement);cc.exports=function(a){return Rv?yn.createElement(a):{}}});var Tn=m((b$,dc)=>{"use strict";var Lv=Ae(),$v=ye(),Mv=Ta();dc.exports=!Lv&&!$v(function(){return Object.defineProperty(Mv("div"),"a",{get:function(){return 7}}).a!==7})});var In=m((g$,pc)=>{"use strict";var Cv=Ae(),Dv=ye();pc.exports=Cv&&Dv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ye=m((S$,hc)=>{"use strict";var Ov=we(),Bv=String,Vv=TypeError;hc.exports=function(a){if(Ov(a))return a;throw new Vv(Bv(a)+" is not an object")}});var Te=m((v$,fc)=>{"use strict";var _v=Fr(),Ia=Function.prototype.call;fc.exports=_v?Ia.bind(Ia):function(){return Ia.apply(Ia,arguments)}});var Ea=m((y$,mc)=>{"use strict";mc.exports={}});var Ke=m((T$,gc)=>{"use strict";var En=Ea(),xn=K(),Nv=z(),bc=function(a){return Nv(a)?a:void 0};gc.exports=function(a,e){return arguments.length<2?bc(En[a])||bc(xn[a]):En[a]&&En[a][e]||xn[a]&&xn[a][e]}});var Hr=m((I$,Sc)=>{"use strict";var Fv=de();Sc.exports=Fv({}.isPrototypeOf)});var sr=m((E$,Tc)=>{"use strict";var qv=K(),vc=qv.navigator,yc=vc&&vc.userAgent;Tc.exports=yc?String(yc):""});var wn=m((x$,Ac)=>{"use strict";var wc=K(),Pn=sr(),Ic=wc.process,Ec=wc.Deno,xc=Ic&&Ic.versions||Ec&&Ec.version,Pc=xc&&xc.v8,Be,xa;Pc&&(Be=Pc.split("."),xa=Be[0]>0&&Be[0]<4?1:+(Be[0]+Be[1]));!xa&&Pn&&(Be=Pn.match(/Edge\/(\d+)/),(!Be||Be[1]>=74)&&(Be=Pn.match(/Chrome\/(\d+)/),Be&&(xa=+Be[1])));Ac.exports=xa});var An=m((P$,Rc)=>{"use strict";var kc=wn(),Uv=ye(),Hv=K(),jv=Hv.String;Rc.exports=!!Object.getOwnPropertySymbols&&!Uv(function(){var a=Symbol("symbol detection");return!jv(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&kc&&kc<41})});var kn=m((w$,Lc)=>{"use strict";var Gv=An();Lc.exports=Gv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Rn=m((A$,$c)=>{"use strict";var Yv=Ke(),Wv=z(),Qv=Hr(),zv=kn(),Kv=Object;$c.exports=zv?function(a){return typeof a=="symbol"}:function(a){var e=Yv("Symbol");return Wv(e)&&Qv(e.prototype,Kv(a))}});var jr=m((k$,Mc)=>{"use strict";var Jv=String;Mc.exports=function(a){try{return Jv(a)}catch(e){return"Object"}}});var Je=m((R$,Cc)=>{"use strict";var Xv=z(),Zv=jr(),ey=TypeError;Cc.exports=function(a){if(Xv(a))return a;throw new ey(Zv(a)+" is not a function")}});var Gr=m((L$,Dc)=>{"use strict";var ty=Je(),ry=ir();Dc.exports=function(a,e){var t=a[e];return ry(t)?void 0:ty(t)}});var Bc=m(($$,Oc)=>{"use strict";var Ln=Te(),$n=z(),Mn=we(),iy=TypeError;Oc.exports=function(a,e){var t,r;if(e==="string"&&$n(t=a.toString)&&!Mn(r=Ln(t,a))||$n(t=a.valueOf)&&!Mn(r=Ln(t,a))||e!=="string"&&$n(t=a.toString)&&!Mn(r=Ln(t,a)))return r;throw new iy("Can't convert object to primitive value")}});var Ve=m((M$,Vc)=>{"use strict";Vc.exports=!0});var Fc=m((C$,Nc)=>{"use strict";var _c=K(),ay=Object.defineProperty;Nc.exports=function(a,e){try{ay(_c,a,{value:e,configurable:!0,writable:!0})}catch(t){_c[a]=e}return e}});var Yr=m((D$,Hc)=>{"use strict";var sy=Ve(),ny=K(),oy=Fc(),qc="__core-js_shared__",Uc=Hc.exports=ny[qc]||oy(qc,{});(Uc.versions||(Uc.versions=[])).push({version:"3.38.0",mode:sy?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Cn=m((O$,Gc)=>{"use strict";var jc=Yr();Gc.exports=function(a,e){return jc[a]||(jc[a]=e||{})}});var Wr=m((B$,Yc)=>{"use strict";var uy=qr(),ly=Object;Yc.exports=function(a){return ly(uy(a))}});var _e=m((V$,Wc)=>{"use strict";var cy=de(),dy=Wr(),py=cy({}.hasOwnProperty);Wc.exports=Object.hasOwn||function(e,t){return py(dy(e),t)}});var Dn=m((_$,Qc)=>{"use strict";var hy=de(),fy=0,my=Math.random(),by=hy(1 .toString);Qc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+by(++fy+my,36)}});var se=m((N$,Kc)=>{"use strict";var gy=K(),Sy=Cn(),zc=_e(),vy=Dn(),yy=An(),Ty=kn(),nr=gy.Symbol,On=Sy("wks"),Iy=Ty?nr.for||nr:nr&&nr.withoutSetter||vy;Kc.exports=function(a){return zc(On,a)||(On[a]=yy&&zc(nr,a)?nr[a]:Iy("Symbol."+a)),On[a]}});var ed=m((F$,Zc)=>{"use strict";var Ey=Te(),Jc=we(),Xc=Rn(),xy=Gr(),Py=Bc(),wy=se(),Ay=TypeError,ky=wy("toPrimitive");Zc.exports=function(a,e){if(!Jc(a)||Xc(a))return a;var t=xy(a,ky),r;if(t){if(e===void 0&&(e="default"),r=Ey(t,a,e),!Jc(r)||Xc(r))return r;throw new Ay("Can't convert object to primitive value")}return e===void 0&&(e="number"),Py(a,e)}});var Bn=m((q$,td)=>{"use strict";var Ry=ed(),Ly=Rn();td.exports=function(a){var e=Ry(a,"string");return Ly(e)?e:e+""}});var $t=m(id=>{"use strict";var $y=Ae(),My=Tn(),Cy=In(),Pa=Ye(),rd=Bn(),Dy=TypeError,Vn=Object.defineProperty,Oy=Object.getOwnPropertyDescriptor,_n="enumerable",Nn="configurable",Fn="writable";id.f=$y?Cy?function(e,t,r){if(Pa(e),t=rd(t),Pa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Fn in r&&!r[Fn]){var i=Oy(e,t);i&&i[Fn]&&(e[t]=r.value,r={configurable:Nn in r?r[Nn]:i[Nn],enumerable:_n in r?r[_n]:i[_n],writable:!1})}return Vn(e,t,r)}:Vn:function(e,t,r){if(Pa(e),t=rd(t),Pa(r),My)try{return Vn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Dy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Qr=m((H$,ad)=>{"use strict";ad.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var or=m((j$,sd)=>{"use strict";var By=Ae(),Vy=$t(),_y=Qr();sd.exports=By?function(a,e,t){return Vy.f(a,e,_y(1,t))}:function(a,e,t){return a[e]=t,a}});var wa=m((G$,od)=>{"use strict";var Ny=Cn(),Fy=Dn(),nd=Ny("keys");od.exports=function(a){return nd[a]||(nd[a]=Fy(a))}});var Aa=m((Y$,ud)=>{"use strict";ud.exports={}});var jn=m((W$,dd)=>{"use strict";var qy=nc(),cd=K(),Uy=we(),Hy=or(),qn=_e(),Un=Yr(),jy=wa(),Gy=Aa(),ld="Object already initialized",Hn=cd.TypeError,Yy=cd.WeakMap,ka,zr,Ra,Wy=function(a){return Ra(a)?zr(a):ka(a,{})},Qy=function(a){return function(e){var t;if(!Uy(e)||(t=zr(e)).type!==a)throw new Hn("Incompatible receiver, "+a+" required");return t}};qy||Un.state?(Ne=Un.state||(Un.state=new Yy),Ne.get=Ne.get,Ne.has=Ne.has,Ne.set=Ne.set,ka=function(a,e){if(Ne.has(a))throw new Hn(ld);return e.facade=a,Ne.set(a,e),e},zr=function(a){return Ne.get(a)||{}},Ra=function(a){return Ne.has(a)}):(Mt=jy("state"),Gy[Mt]=!0,ka=function(a,e){if(qn(a,Mt))throw new Hn(ld);return e.facade=a,Hy(a,Mt,e),e},zr=function(a){return qn(a,Mt)?a[Mt]:{}},Ra=function(a){return qn(a,Mt)});var Ne,Mt;dd.exports={set:ka,get:zr,has:Ra,enforce:Wy,getterFor:Qy}});var Gn=m((Q$,md)=>{"use strict";var zy=Fr(),fd=Function.prototype,pd=fd.apply,hd=fd.call;md.exports=typeof Reflect=="object"&&Reflect.apply||(zy?hd.bind(pd):function(){return hd.apply(pd,arguments)})});var Yn=m((z$,bd)=>{"use strict";var Ky=rr(),Jy=de();bd.exports=function(a){if(Ky(a)==="Function")return Jy(a)}});var yd=m(vd=>{"use strict";var gd={}.propertyIsEnumerable,Sd=Object.getOwnPropertyDescriptor,Xy=Sd&&!gd.call({1:2},1);vd.f=Xy?function(e){var t=Sd(this,e);return!!t&&t.enumerable}:gd});var Ed=m(Id=>{"use strict";var Zy=Ae(),eT=Te(),tT=yd(),rT=Qr(),iT=ar(),aT=Bn(),sT=_e(),nT=Tn(),Td=Object.getOwnPropertyDescriptor;Id.f=Zy?Td:function(e,t){if(e=iT(e),t=aT(t),nT)try{return Td(e,t)}catch(r){}if(sT(e,t))return rT(!eT(tT.f,e,t),e[t])}});var Wn=m((X$,xd)=>{"use strict";var oT=ye(),uT=z(),lT=/#|\.prototype\./,Kr=function(a,e){var t=dT[cT(a)];return t===hT?!0:t===pT?!1:uT(e)?oT(e):!!e},cT=Kr.normalize=function(a){return String(a).replace(lT,".").toLowerCase()},dT=Kr.data={},pT=Kr.NATIVE="N",hT=Kr.POLYFILL="P";xd.exports=Kr});var Jr=m((Z$,wd)=>{"use strict";var Pd=Yn(),fT=Je(),mT=Fr(),bT=Pd(Pd.bind);wd.exports=function(a,e){return fT(a),e===void 0?a:mT?bT(a,e):function(){return a.apply(e,arguments)}}});var ke=m((eM,kd)=>{"use strict";var Xr=K(),gT=Gn(),ST=Yn(),vT=z(),yT=Ed().f,TT=Wn(),ur=Ea(),IT=Jr(),lr=or(),Ad=_e();Yr();var ET=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return gT(a,this,arguments)};return e.prototype=a.prototype,e};kd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Xr:i?Xr[t]:Xr[t]&&Xr[t].prototype,o=r?ur:ur[t]||lr(ur,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,S;for(p in e)l=TT(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Ad(n,p),f=o[p],c&&(a.dontCallGetSet?(S=yT(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=IT(h,Xr):a.wrap&&c?g=ET(h):s&&vT(h)?g=ST(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&lr(g,"sham",!0),lr(o,p,g),s&&(d=t+"Prototype",Ad(ur,d)||lr(ur,d,{}),lr(ur[d],p,h),a.real&&u&&(l||!u[p])&&lr(u,p,h)))}});var $d=m((tM,Ld)=>{"use strict";var Qn=Ae(),xT=_e(),Rd=Function.prototype,PT=Qn&&Object.getOwnPropertyDescriptor,zn=xT(Rd,"name"),wT=zn&&function(){}.name==="something",AT=zn&&(!Qn||Qn&&PT(Rd,"name").configurable);Ld.exports={EXISTS:zn,PROPER:wT,CONFIGURABLE:AT}});var Cd=m((rM,Md)=>{"use strict";var kT=Math.ceil,RT=Math.floor;Md.exports=Math.trunc||function(e){var t=+e;return(t>0?RT:kT)(t)}});var La=m((iM,Dd)=>{"use strict";var LT=Cd();Dd.exports=function(a){var e=+a;return e!==e||e===0?0:LT(e)}});var Bd=m((aM,Od)=>{"use strict";var $T=La(),MT=Math.max,CT=Math.min;Od.exports=function(a,e){var t=$T(a);return t<0?MT(t+e,0):CT(t,e)}});var _d=m((sM,Vd)=>{"use strict";var DT=La(),OT=Math.min;Vd.exports=function(a){var e=DT(a);return e>0?OT(e,9007199254740991):0}});var $a=m((nM,Nd)=>{"use strict";var BT=_d();Nd.exports=function(a){return BT(a.length)}});var Ud=m((oM,qd)=>{"use strict";var VT=ar(),_T=Bd(),NT=$a(),Fd=function(a){return function(e,t,r){var i=VT(e),s=NT(i);if(s===0)return!a&&-1;var n=_T(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};qd.exports={includes:Fd(!0),indexOf:Fd(!1)}});var Gd=m((uM,jd)=>{"use strict";var FT=de(),Kn=_e(),qT=ar(),UT=Ud().indexOf,HT=Aa(),Hd=FT([].push);jd.exports=function(a,e){var t=qT(a),r=0,i=[],s;for(s in t)!Kn(HT,s)&&Kn(t,s)&&Hd(i,s);for(;e.length>r;)Kn(t,s=e[r++])&&(~UT(i,s)||Hd(i,s));return i}});var Jn=m((lM,Yd)=>{"use strict";Yd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Qd=m((cM,Wd)=>{"use strict";var jT=Gd(),GT=Jn();Wd.exports=Object.keys||function(e){return jT(e,GT)}});var Kd=m(zd=>{"use strict";var YT=Ae(),WT=In(),QT=$t(),zT=Ye(),KT=ar(),JT=Qd();zd.f=YT&&!WT?Object.defineProperties:function(e,t){zT(e);for(var r=KT(t),i=JT(t),s=i.length,n=0,o;s>n;)QT.f(e,o=i[n++],r[o]);return e}});var Xn=m((pM,Jd)=>{"use strict";var XT=Ke();Jd.exports=XT("document","documentElement")});var ro=m((hM,ap)=>{"use strict";var ZT=Ye(),eI=Kd(),Xd=Jn(),tI=Aa(),rI=Xn(),iI=Ta(),aI=wa(),Zd=">",ep="<",eo="prototype",to="script",rp=aI("IE_PROTO"),Zn=function(){},ip=function(a){return ep+to+Zd+a+ep+"/"+to+Zd},tp=function(a){a.write(ip("")),a.close();var e=a.parentWindow.Object;return a=null,e},sI=function(){var a=iI("iframe"),e="java"+to+":",t;return a.style.display="none",rI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(ip("document.F=Object")),t.close(),t.F},Ma,Ca=function(){try{Ma=new ActiveXObject("htmlfile")}catch(e){}Ca=typeof document!="undefined"?document.domain&&Ma?tp(Ma):sI():tp(Ma);for(var a=Xd.length;a--;)delete Ca[eo][Xd[a]];return Ca()};tI[rp]=!0;ap.exports=Object.create||function(e,t){var r;return e!==null?(Zn[eo]=ZT(e),r=new Zn,Zn[eo]=null,r[rp]=e):r=Ca(),t===void 0?r:eI.f(r,t)}});var np=m((fM,sp)=>{"use strict";var nI=ye();sp.exports=!nI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ao=m((mM,up)=>{"use strict";var oI=_e(),uI=z(),lI=Wr(),cI=wa(),dI=np(),op=cI("IE_PROTO"),io=Object,pI=io.prototype;up.exports=dI?io.getPrototypeOf:function(a){var e=lI(a);if(oI(e,op))return e[op];var t=e.constructor;return uI(t)&&e instanceof t?t.prototype:e instanceof io?pI:null}});var cr=m((bM,lp)=>{"use strict";var hI=or();lp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:hI(a,e,t),a}});var uo=m((gM,pp)=>{"use strict";var fI=ye(),mI=z(),bI=we(),gI=ro(),cp=ao(),SI=cr(),vI=se(),yI=Ve(),oo=vI("iterator"),dp=!1,Xe,so,no;[].keys&&(no=[].keys(),"next"in no?(so=cp(cp(no)),so!==Object.prototype&&(Xe=so)):dp=!0);var TI=!bI(Xe)||fI(function(){var a={};return Xe[oo].call(a)!==a});TI?Xe={}:yI&&(Xe=gI(Xe));mI(Xe[oo])||SI(Xe,oo,function(){return this});pp.exports={IteratorPrototype:Xe,BUGGY_SAFARI_ITERATORS:dp}});var Da=m((SM,fp)=>{"use strict";var II=se(),EI=II("toStringTag"),hp={};hp[EI]="z";fp.exports=String(hp)==="[object z]"});var Zr=m((vM,mp)=>{"use strict";var xI=Da(),PI=z(),Oa=rr(),wI=se(),AI=wI("toStringTag"),kI=Object,RI=Oa(function(){return arguments}())==="Arguments",LI=function(a,e){try{return a[e]}catch(t){}};mp.exports=xI?Oa:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=LI(e=kI(a),AI))=="string"?t:RI?Oa(e):(r=Oa(e))==="Object"&&PI(e.callee)?"Arguments":r}});var gp=m((yM,bp)=>{"use strict";var $I=Da(),MI=Zr();bp.exports=$I?{}.toString:function(){return"[object "+MI(this)+"]"}});var ei=m((TM,vp)=>{"use strict";var CI=Da(),DI=$t().f,OI=or(),BI=_e(),VI=gp(),_I=se(),Sp=_I("toStringTag");vp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(BI(i,Sp)||DI(i,Sp,{configurable:!0,value:e}),r&&!CI&&OI(i,"toString",VI))}});var Tp=m((IM,yp)=>{"use strict";var NI=uo().IteratorPrototype,FI=ro(),qI=Qr(),UI=ei(),HI=Lt(),jI=function(){return this};yp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=FI(NI,{next:qI(+!r,t)}),UI(a,i,!1,!0),HI[i]=jI,a}});var Ep=m((EM,Ip)=>{"use strict";var GI=de(),YI=Je();Ip.exports=function(a,e,t){try{return GI(YI(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Pp=m((xM,xp)=>{"use strict";var WI=we();xp.exports=function(a){return WI(a)||a===null}});var Ap=m((PM,wp)=>{"use strict";var QI=Pp(),zI=String,KI=TypeError;wp.exports=function(a){if(QI(a))return a;throw new KI("Can't set "+zI(a)+" as a prototype")}});var lo=m((wM,kp)=>{"use strict";var JI=Ep(),XI=we(),ZI=qr(),eE=Ap();kp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=JI(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return ZI(i),eE(s),XI(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Np=m((AM,_p)=>{"use strict";var tE=ke(),rE=Te(),Ba=Ve(),Bp=$d(),iE=z(),aE=Tp(),Rp=ao(),Lp=lo(),sE=ei(),nE=or(),co=cr(),oE=se(),$p=Lt(),Vp=uo(),uE=Bp.PROPER,lE=Bp.CONFIGURABLE,Mp=Vp.IteratorPrototype,Va=Vp.BUGGY_SAFARI_ITERATORS,ti=oE("iterator"),Cp="keys",ri="values",Dp="entries",Op=function(){return this};_p.exports=function(a,e,t,r,i,s,n){aE(t,e,r);var o=function(S){if(S===i&&p)return p;if(!Va&&S&&S in c)return c[S];switch(S){case Cp:return function(){return new t(this,S)};case ri:return function(){return new t(this,S)};case Dp:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[ti]||c["@@iterator"]||i&&c[i],p=!Va&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=Rp(h.call(new a)),f!==Object.prototype&&f.next&&(!Ba&&Rp(f)!==Mp&&(Lp?Lp(f,Mp):iE(f[ti])||co(f,ti,Op)),sE(f,u,!0,!0),Ba&&($p[u]=Op))),uE&&i===ri&&d&&d.name!==ri&&(!Ba&&lE?nE(c,"name",ri):(l=!0,p=function(){return rE(d,this)})),i)if(b={values:o(ri),keys:s?p:o(Cp),entries:o(Dp)},n)for(g in b)(Va||l||!(g in c))&&co(c,g,b[g]);else tE({target:e,proto:!0,forced:Va||l},b);return(!Ba||n)&&c[ti]!==p&&co(c,ti,p,{name:i}),$p[e]=p,b}});var qp=m((kM,Fp)=>{"use strict";Fp.exports=function(a,e){return{value:a,done:e}}});var ho=m((RM,Yp)=>{"use strict";var cE=ar(),po=gn(),Up=Lt(),jp=jn(),dE=$t().f,pE=Np(),_a=qp(),hE=Ve(),fE=Ae(),Gp="Array Iterator",mE=jp.set,bE=jp.getterFor(Gp);Yp.exports=pE(Array,"Array",function(a,e){mE(this,{type:Gp,target:cE(a),index:0,kind:e})},function(){var a=bE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,_a(void 0,!0);switch(a.kind){case"keys":return _a(t,!1);case"values":return _a(e[t],!1)}return _a([t,e[t]],!1)},"values");var Hp=Up.Arguments=Up.Array;po("keys");po("values");po("entries");if(!hE&&fE&&Hp.name!=="values")try{dE(Hp,"name",{value:"values"})}catch(a){}});var Qp=m((LM,Wp)=>{"use strict";var gE=se(),SE=Lt(),vE=gE("iterator"),yE=Array.prototype;Wp.exports=function(a){return a!==void 0&&(SE.Array===a||yE[vE]===a)}});var fo=m(($M,Kp)=>{"use strict";var TE=Zr(),zp=Gr(),IE=ir(),EE=Lt(),xE=se(),PE=xE("iterator");Kp.exports=function(a){if(!IE(a))return zp(a,PE)||zp(a,"@@iterator")||EE[TE(a)]}});var Xp=m((MM,Jp)=>{"use strict";var wE=Te(),AE=Je(),kE=Ye(),RE=jr(),LE=fo(),$E=TypeError;Jp.exports=function(a,e){var t=arguments.length<2?LE(a):e;if(AE(t))return kE(wE(t,a));throw new $E(RE(a)+" is not iterable")}});var th=m((CM,eh)=>{"use strict";var ME=Te(),Zp=Ye(),CE=Gr();eh.exports=function(a,e,t){var r,i;Zp(a);try{if(r=CE(a,"return"),!r){if(e==="throw")throw t;return t}r=ME(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Zp(r),t}});var Fa=m((DM,sh)=>{"use strict";var DE=Jr(),OE=Te(),BE=Ye(),VE=jr(),_E=Qp(),NE=$a(),rh=Hr(),FE=Xp(),qE=fo(),ih=th(),UE=TypeError,Na=function(a,e){this.stopped=a,this.result=e},ah=Na.prototype;sh.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=DE(e,r),l,c,d,p,h,f,b,g=function(I){return l&&ih(l,"normal",I),new Na(!0,I)},S=function(I){return i?(BE(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=qE(a),!c)throw new UE(VE(a)+" is not iterable");if(_E(c)){for(d=0,p=NE(a);p>d;d++)if(h=S(a[d]),h&&rh(ah,h))return h;return new Na(!1)}l=FE(a,c)}for(f=s?a.next:l.next;!(b=OE(f,l)).done;){try{h=S(b.value)}catch(I){ih(l,"throw",I)}if(typeof h=="object"&&h&&rh(ah,h))return h}return new Na(!1)}});var oh=m((OM,nh)=>{"use strict";var HE=Ae(),jE=$t(),GE=Qr();nh.exports=function(a,e,t){HE?jE.f(a,e,GE(0,t)):a[e]=t}});var uh=m(()=>{"use strict";var YE=ke(),WE=Fa(),QE=oh();YE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return WE(e,function(r,i){QE(t,r,i)},{AS_ENTRIES:!0}),t}})});var ch=m((_M,lh)=>{"use strict";ho();uh();var zE=Ea();lh.exports=zE.Object.fromEntries});var ph=m((NM,dh)=>{"use strict";dh.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 fh=m(()=>{"use strict";ho();var KE=ph(),JE=K(),XE=ei(),hh=Lt();for(qa in KE)XE(JE[qa],qa),hh[qa]=hh.Array;var qa});var bh=m((UM,mh)=>{"use strict";var ZE=ch();fh();mh.exports=ZE});var mo=m((HM,gh)=>{"use strict";var ex=bh();gh.exports=ex});var Sh=m(()=>{"use strict"});var bo=m((YM,vh)=>{"use strict";var ii=K(),tx=sr(),rx=rr(),Ua=function(a){return tx.slice(0,a.length)===a};vh.exports=function(){return Ua("Bun/")?"BUN":Ua("Cloudflare-Workers")?"CLOUDFLARE":Ua("Deno/")?"DENO":Ua("Node.js/")?"NODE":ii.Bun&&typeof Bun.version=="string"?"BUN":ii.Deno&&typeof Deno.version=="object"?"DENO":rx(ii.process)==="process"?"NODE":ii.window&&ii.document?"BROWSER":"REST"}()});var Ha=m((WM,yh)=>{"use strict";var ix=bo();yh.exports=ix==="NODE"});var Ih=m((QM,Th)=>{"use strict";var ax=$t();Th.exports=function(a,e,t){return ax.f(a,e,t)}});var Ph=m((zM,xh)=>{"use strict";var sx=Ke(),nx=Ih(),ox=se(),ux=Ae(),Eh=ox("species");xh.exports=function(a){var e=sx(a);ux&&e&&!e[Eh]&&nx(e,Eh,{configurable:!0,get:function(){return this}})}});var Ah=m((KM,wh)=>{"use strict";var lx=Hr(),cx=TypeError;wh.exports=function(a,e){if(lx(e,a))return a;throw new cx("Incorrect invocation")}});var So=m((JM,kh)=>{"use strict";var dx=de(),px=z(),go=Yr(),hx=dx(Function.toString);px(go.inspectSource)||(go.inspectSource=function(a){return hx(a)});kh.exports=go.inspectSource});var Dh=m((XM,Ch)=>{"use strict";var fx=de(),mx=ye(),Rh=z(),bx=Zr(),gx=Ke(),Sx=So(),Lh=function(){},$h=gx("Reflect","construct"),vo=/^\s*(?:class|function)\b/,vx=fx(vo.exec),yx=!vo.test(Lh),ai=function(e){if(!Rh(e))return!1;try{return $h(Lh,[],e),!0}catch(t){return!1}},Mh=function(e){if(!Rh(e))return!1;switch(bx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return yx||!!vx(vo,Sx(e))}catch(t){return!0}};Mh.sham=!0;Ch.exports=!$h||mx(function(){var a;return ai(ai.call)||!ai(Object)||!ai(function(){a=!0})||a})?Mh:ai});var Bh=m((ZM,Oh)=>{"use strict";var Tx=Dh(),Ix=jr(),Ex=TypeError;Oh.exports=function(a){if(Tx(a))return a;throw new Ex(Ix(a)+" is not a constructor")}});var yo=m((eC,_h)=>{"use strict";var Vh=Ye(),xx=Bh(),Px=ir(),wx=se(),Ax=wx("species");_h.exports=function(a,e){var t=Vh(a).constructor,r;return t===void 0||Px(r=Vh(t)[Ax])?e:xx(r)}});var Fh=m((tC,Nh)=>{"use strict";var kx=de();Nh.exports=kx([].slice)});var Uh=m((rC,qh)=>{"use strict";var Rx=TypeError;qh.exports=function(a,e){if(a<e)throw new Rx("Not enough arguments");return a}});var To=m((iC,Hh)=>{"use strict";var Lx=sr();Hh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Lx)});var Lo=m((aC,Xh)=>{"use strict";var Ie=K(),$x=Gn(),Mx=Jr(),jh=z(),Cx=_e(),Jh=ye(),Gh=Xn(),Dx=Fh(),Yh=Ta(),Ox=Uh(),Bx=To(),Vx=Ha(),Ao=Ie.setImmediate,ko=Ie.clearImmediate,_x=Ie.process,Io=Ie.Dispatch,Nx=Ie.Function,Wh=Ie.MessageChannel,Fx=Ie.String,Eo=0,si={},Qh="onreadystatechange",ni,Ct,xo,Po;Jh(function(){ni=Ie.location});var Ro=function(a){if(Cx(si,a)){var e=si[a];delete si[a],e()}},wo=function(a){return function(){Ro(a)}},zh=function(a){Ro(a.data)},Kh=function(a){Ie.postMessage(Fx(a),ni.protocol+"//"+ni.host)};(!Ao||!ko)&&(Ao=function(e){Ox(arguments.length,1);var t=jh(e)?e:Nx(e),r=Dx(arguments,1);return si[++Eo]=function(){$x(t,void 0,r)},Ct(Eo),Eo},ko=function(e){delete si[e]},Vx?Ct=function(a){_x.nextTick(wo(a))}:Io&&Io.now?Ct=function(a){Io.now(wo(a))}:Wh&&!Bx?(xo=new Wh,Po=xo.port2,xo.port1.onmessage=zh,Ct=Mx(Po.postMessage,Po)):Ie.addEventListener&&jh(Ie.postMessage)&&!Ie.importScripts&&ni&&ni.protocol!=="file:"&&!Jh(Kh)?(Ct=Kh,Ie.addEventListener("message",zh,!1)):Qh in Yh("script")?Ct=function(a){Gh.appendChild(Yh("script"))[Qh]=function(){Gh.removeChild(this),Ro(a)}}:Ct=function(a){setTimeout(wo(a),0)});Xh.exports={set:Ao,clear:ko}});var tf=m((sC,ef)=>{"use strict";var Zh=K(),qx=Ae(),Ux=Object.getOwnPropertyDescriptor;ef.exports=function(a){if(!qx)return Zh[a];var e=Ux(Zh,a);return e&&e.value}});var $o=m((nC,af)=>{"use strict";var rf=function(){this.head=null,this.tail=null};rf.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}}};af.exports=rf});var nf=m((oC,sf)=>{"use strict";var Hx=sr();sf.exports=/ipad|iphone|ipod/i.test(Hx)&&typeof Pebble!="undefined"});var uf=m((uC,of)=>{"use strict";var jx=sr();of.exports=/web0s(?!.*chrome)/i.test(jx)});var mf=m((lC,ff)=>{"use strict";var pr=K(),Gx=tf(),lf=Jr(),Mo=Lo().set,Yx=$o(),Wx=To(),Qx=nf(),zx=uf(),Co=Ha(),cf=pr.MutationObserver||pr.WebKitMutationObserver,df=pr.document,pf=pr.process,ja=pr.Promise,Bo=Gx("queueMicrotask"),dr,Do,Oo,Ga,hf;Bo||(oi=new Yx,ui=function(){var a,e;for(Co&&(a=pf.domain)&&a.exit();e=oi.get();)try{e()}catch(t){throw oi.head&&dr(),t}a&&a.enter()},!Wx&&!Co&&!zx&&cf&&df?(Do=!0,Oo=df.createTextNode(""),new cf(ui).observe(Oo,{characterData:!0}),dr=function(){Oo.data=Do=!Do}):!Qx&&ja&&ja.resolve?(Ga=ja.resolve(void 0),Ga.constructor=ja,hf=lf(Ga.then,Ga),dr=function(){hf(ui)}):Co?dr=function(){pf.nextTick(ui)}:(Mo=lf(Mo,pr),dr=function(){Mo(ui)}),Bo=function(a){oi.head||dr(),oi.add(a)});var oi,ui;ff.exports=Bo});var gf=m((cC,bf)=>{"use strict";bf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ya=m((dC,Sf)=>{"use strict";Sf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Dt=m((pC,vf)=>{"use strict";var Kx=K();vf.exports=Kx.Promise});var hr=m((hC,Ef)=>{"use strict";var Jx=K(),li=Dt(),Xx=z(),Zx=Wn(),eP=So(),tP=se(),yf=bo(),rP=Ve(),Vo=wn(),Tf=li&&li.prototype,iP=tP("species"),_o=!1,If=Xx(Jx.PromiseRejectionEvent),aP=Zx("Promise",function(){var a=eP(li),e=a!==String(li);if(!e&&Vo===66||rP&&!(Tf.catch&&Tf.finally))return!0;if(!Vo||Vo<51||!/native code/.test(a)){var t=new li(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[iP]=r,_o=t.then(function(){})instanceof r,!_o)return!0}return!e&&(yf==="BROWSER"||yf==="DENO")&&!If});Ef.exports={CONSTRUCTOR:aP,REJECTION_EVENT:If,SUBCLASSING:_o}});var fr=m((fC,Pf)=>{"use strict";var xf=Je(),sP=TypeError,nP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new sP("Bad Promise constructor");e=r,t=i}),this.resolve=xf(e),this.reject=xf(t)};Pf.exports.f=function(a){return new nP(a)}});var jf=m(()=>{"use strict";var oP=ke(),uP=Ve(),Ka=Ha(),ht=K(),Sr=Te(),wf=cr(),Af=lo(),lP=ei(),cP=Ph(),dP=Je(),za=z(),pP=we(),hP=Ah(),fP=yo(),Mf=Lo().set,Ho=mf(),mP=gf(),bP=Ya(),gP=$o(),Cf=jn(),Ja=Dt(),jo=hr(),Df=fr(),Xa="Promise",Of=jo.CONSTRUCTOR,SP=jo.REJECTION_EVENT,vP=jo.SUBCLASSING,No=Cf.getterFor(Xa),yP=Cf.set,mr=Ja&&Ja.prototype,Ot=Ja,Wa=mr,Bf=ht.TypeError,Fo=ht.document,Go=ht.process,qo=Df.f,TP=qo,IP=!!(Fo&&Fo.createEvent&&ht.dispatchEvent),Vf="unhandledrejection",EP="rejectionhandled",kf=0,_f=1,xP=2,Yo=1,Nf=2,Qa,Rf,PP,Lf,Ff=function(a){var e;return pP(a)&&za(e=a.then)?e:!1},qf=function(a,e){var t=e.value,r=e.state===_f,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Nf&&AP(e),e.rejection=Yo),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Bf("Promise-chain cycle")):(l=Ff(u))?Sr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Uf=function(a,e){a.notified||(a.notified=!0,Ho(function(){for(var t=a.reactions,r;r=t.get();)qf(r,a);a.notified=!1,e&&!a.rejection&&wP(a)}))},Hf=function(a,e,t){var r,i;IP?(r=Fo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),ht.dispatchEvent(r)):r={promise:e,reason:t},!SP&&(i=ht["on"+a])?i(r):a===Vf&&mP("Unhandled promise rejection",t)},wP=function(a){Sr(Mf,ht,function(){var e=a.facade,t=a.value,r=$f(a),i;if(r&&(i=bP(function(){Ka?Go.emit("unhandledRejection",t,e):Hf(Vf,e,t)}),a.rejection=Ka||$f(a)?Nf:Yo,i.error))throw i.value})},$f=function(a){return a.rejection!==Yo&&!a.parent},AP=function(a){Sr(Mf,ht,function(){var e=a.facade;Ka?Go.emit("rejectionHandled",e):Hf(EP,e,a.value)})},br=function(a,e,t){return function(r){a(e,r,t)}},gr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=xP,Uf(a,!0))},Uo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Bf("Promise can't be resolved itself");var r=Ff(e);r?Ho(function(){var i={done:!1};try{Sr(r,e,br(Uo,i,a),br(gr,i,a))}catch(s){gr(i,s,a)}}):(a.value=e,a.state=_f,Uf(a,!1))}catch(i){gr({done:!1},i,a)}}};if(Of&&(Ot=function(e){hP(this,Wa),dP(e),Sr(Qa,this);var t=No(this);try{e(br(Uo,t),br(gr,t))}catch(r){gr(t,r)}},Wa=Ot.prototype,Qa=function(e){yP(this,{type:Xa,done:!1,notified:!1,parent:!1,reactions:new gP,rejection:!1,state:kf,value:void 0})},Qa.prototype=wf(Wa,"then",function(e,t){var r=No(this),i=qo(fP(this,Ot));return r.parent=!0,i.ok=za(e)?e:!0,i.fail=za(t)&&t,i.domain=Ka?Go.domain:void 0,r.state===kf?r.reactions.add(i):Ho(function(){qf(i,r)}),i.promise}),Rf=function(){var a=new Qa,e=No(a);this.promise=a,this.resolve=br(Uo,e),this.reject=br(gr,e)},Df.f=qo=function(a){return a===Ot||a===PP?new Rf(a):TP(a)},!uP&&za(Ja)&&mr!==Object.prototype)){Lf=mr.then,vP||wf(mr,"then",function(e,t){var r=this;return new Ot(function(i,s){Sr(Lf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete mr.constructor}catch(a){}Af&&Af(mr,Wa)}oP({global:!0,constructor:!0,wrap:!0,forced:Of},{Promise:Ot});lP(Ot,Xa,!1,!0);cP(Xa)});var zf=m((gC,Qf)=>{"use strict";var kP=se(),Yf=kP("iterator"),Wf=!1;try{Gf=0,Wo={next:function(){return{done:!!Gf++}},return:function(){Wf=!0}},Wo[Yf]=function(){return this},Array.from(Wo,function(){throw 2})}catch(a){}var Gf,Wo;Qf.exports=function(a,e){try{if(!e&&!Wf)return!1}catch(i){return!1}var t=!1;try{var r={};r[Yf]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Qo=m((SC,Kf)=>{"use strict";var RP=Dt(),LP=zf(),$P=hr().CONSTRUCTOR;Kf.exports=$P||!LP(function(a){RP.all(a).then(void 0,function(){})})});var Jf=m(()=>{"use strict";var MP=ke(),CP=Te(),DP=Je(),OP=fr(),BP=Ya(),VP=Fa(),_P=Qo();MP({target:"Promise",stat:!0,forced:_P},{all:function(e){var t=this,r=OP.f(t),i=r.resolve,s=r.reject,n=BP(function(){var o=DP(t.resolve),u=[],l=0,c=1;VP(e,function(d){var p=l++,h=!1;c++,CP(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Zf=m(()=>{"use strict";var NP=ke(),FP=Ve(),qP=hr().CONSTRUCTOR,Ko=Dt(),UP=Ke(),HP=z(),jP=cr(),Xf=Ko&&Ko.prototype;NP({target:"Promise",proto:!0,forced:qP,real:!0},{catch:function(a){return this.then(void 0,a)}});!FP&&HP(Ko)&&(zo=UP("Promise").prototype.catch,Xf.catch!==zo&&jP(Xf,"catch",zo,{unsafe:!0}));var zo});var em=m(()=>{"use strict";var GP=ke(),YP=Te(),WP=Je(),QP=fr(),zP=Ya(),KP=Fa(),JP=Qo();GP({target:"Promise",stat:!0,forced:JP},{race:function(e){var t=this,r=QP.f(t),i=r.reject,s=zP(function(){var n=WP(t.resolve);KP(e,function(o){YP(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var tm=m(()=>{"use strict";var XP=ke(),ZP=fr(),ew=hr().CONSTRUCTOR;XP({target:"Promise",stat:!0,forced:ew},{reject:function(e){var t=ZP.f(this),r=t.reject;return r(e),t.promise}})});var Jo=m((AC,rm)=>{"use strict";var tw=Ye(),rw=we(),iw=fr();rm.exports=function(a,e){if(tw(a),rw(e)&&e.constructor===a)return e;var t=iw.f(a),r=t.resolve;return r(e),t.promise}});var sm=m(()=>{"use strict";var aw=ke(),sw=Ke(),im=Ve(),nw=Dt(),am=hr().CONSTRUCTOR,ow=Jo(),uw=sw("Promise"),lw=im&&!am;aw({target:"Promise",stat:!0,forced:im||am},{resolve:function(e){return ow(lw&&this===uw?nw:this,e)}})});var nm=m(()=>{"use strict";jf();Jf();Zf();em();tm();sm()});var cm=m(()=>{"use strict";var cw=ke(),dw=Ve(),Za=Dt(),pw=ye(),um=Ke(),lm=z(),hw=yo(),om=Jo(),fw=cr(),Zo=Za&&Za.prototype,mw=!!Za&&pw(function(){Zo.finally.call({then:function(){}},function(){})});cw({target:"Promise",proto:!0,real:!0,forced:mw},{finally:function(a){var e=hw(this,um("Promise")),t=lm(a);return this.then(t?function(r){return om(e,a()).then(function(){return r})}:a,t?function(r){return om(e,a()).then(function(){throw r})}:a)}});!dw&&lm(Za)&&(Xo=um("Promise").prototype.finally,Zo.finally!==Xo&&fw(Zo,"finally",Xo,{unsafe:!0}));var Xo});var es=m((DC,dm)=>{"use strict";var bw=Ke();dm.exports=bw});var hm=m((OC,pm)=>{"use strict";Sh();nm();cm();var gw=es();pm.exports=gw("Promise","finally")});var mm=m((BC,fm)=>{"use strict";var Sw=hm();fm.exports=Sw});var ts=m((VC,bm)=>{"use strict";var vw=mm();bm.exports=vw});var qm=m(()=>{"use strict";var Qw=ke(),zw=Wr(),Kw=$a(),Jw=La(),Xw=gn();Qw({target:"Array",proto:!0},{at:function(e){var t=zw(this),r=Kw(t),i=Jw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});Xw("at")});var Hm=m((YD,Um)=>{"use strict";qm();var Zw=es();Um.exports=Zw("Array","at")});var Gm=m((WD,jm)=>{"use strict";var eA=Hm();jm.exports=eA});var hi=m((QD,Ym)=>{"use strict";var tA=Gm();Ym.exports=tA});var jb=m(()=>{"use strict"});var Gb=m(()=>{"use strict"});var Wb=m((t_,Yb)=>{"use strict";var dk=we(),pk=rr(),hk=se(),fk=hk("match");Yb.exports=function(a){var e;return dk(a)&&((e=a[fk])!==void 0?!!e:pk(a)==="RegExp")}});var zb=m((r_,Qb)=>{"use strict";var mk=Zr(),bk=String;Qb.exports=function(a){if(mk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return bk(a)}});var Jb=m((i_,Kb)=>{"use strict";var gk=Ye();Kb.exports=function(){var a=gk(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 eg=m((a_,Zb)=>{"use strict";var Sk=Te(),vk=_e(),yk=Hr(),Tk=Jb(),Xb=RegExp.prototype;Zb.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Xb)&&!vk(a,"flags")&&yk(Xb,a)?Sk(Tk,a):e}});var rg=m((s_,tg)=>{"use strict";var Ru=de(),Ik=Wr(),Ek=Math.floor,Au=Ru("".charAt),xk=Ru("".replace),ku=Ru("".slice),Pk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,wk=/\$([$&'`]|\d{1,2})/g;tg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=wk;return i!==void 0&&(i=Ik(i),u=Pk),xk(s,u,function(l,c){var d;switch(Au(c,0)){case"$":return"$";case"&":return a;case"`":return ku(e,0,t);case"'":return ku(e,n);case"<":d=i[ku(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=Ek(p/10);return h===0?l:h<=o?r[h-1]===void 0?Au(c,1):r[h-1]+Au(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var sg=m(()=>{"use strict";var Ak=ke(),kk=Te(),$u=de(),ig=qr(),Rk=z(),Lk=ir(),$k=Wb(),kr=zb(),Mk=Gr(),Ck=eg(),Dk=rg(),Ok=se(),Bk=Ve(),Vk=Ok("replace"),_k=TypeError,Lu=$u("".indexOf),Nk=$u("".replace),ag=$u("".slice),Fk=Math.max;Ak({target:"String",proto:!0},{replaceAll:function(e,t){var r=ig(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!Lk(e)){if(i=$k(e),i&&(s=kr(ig(Ck(e))),!~Lu(s,"g")))throw new _k("`.replaceAll` does not allow non-global regexes");if(n=Mk(e,Vk),n)return kk(n,e,r,t);if(Bk&&i)return Nk(kr(r),e,t)}for(o=kr(r),u=kr(e),l=Rk(t),l||(t=kr(t)),c=u.length,d=Fk(1,c),p=Lu(o,u);p!==-1;)h=l?kr(t(u,p,o)):Dk(u,o,p,[],void 0,t),b+=ag(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Lu(o,u,p+d);return f<o.length&&(b+=ag(o,f)),b}})});var og=m((u_,ng)=>{"use strict";jb();Gb();sg();var qk=es();ng.exports=qk("String","replaceAll")});var lg=m((l_,ug)=>{"use strict";var Uk=og();ug.exports=Uk});var dg=m((c_,cg)=>{"use strict";var Hk=lg();cg.exports=Hk});var Ol="2.0.108-dev.9b636631.0";var ce=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ce||{}),pt=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(pt||{});var Sa=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Sa||{}),dn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(dn||{});var pn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(pn||{});import{assertNever as ql,assertNonNullable as sv,isNonNullable as va,ValueSubject as hn,Subject as nv,Subscription as ov,merge as uv,observableFrom as lv,fromEvent as Vl,map as _l,tap as Nl,filterChanged as cv,isNullable as fn,ErrorCategory as Fl}from"@vkontakte/videoplayer-shared";var Bl=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var ya=class{constructor(e){this.connection$=new hn(void 0);this.castState$=new hn("NOT_AVAILABLE");this.errorEvent$=new nv;this.realCastState$=new hn("NOT_AVAILABLE");this.subscription=new ov;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=va((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Bl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Fl.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){va(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();fn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();fn(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Vl(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return ql(i.sessionState)}})).add(uv(Vl(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Nl(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),_l(i=>i.castState)),lv([r.getCastState()])).pipe(cv(),_l(dv),Nl(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o;let s=i==="CONNECTED",n=va(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();sv(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;(fn(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?va(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Fl.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},dv=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return ql(a)}};var cS=Ge(mo(),1);var wm=Ge(ts(),1);import{assertNever as gm}from"@vkontakte/videoplayer-shared";var ae=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:gm(t)}return a},eu=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:gm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as yw,Subject as rs,merge as Sm}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new rs;this.transitionEnded$=new rs;this.transitionUpdated$=new rs;this.forceChanged$=new rs;this.stateChangeStarted$=Sm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Sm(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||yw(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 Tw}from"@vkontakte/videoplayer-shared";var vm=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 Tw(a)}};import{assertNever as vr,assertNonNullable as Bt,debounce as ym,ErrorCategory as Tm,fromEvent as Vt,isNonNullable as Im,map as Em,merge as xm,observableFrom as Iw,Subject as Ew,Subscription as tu,timeout as xw,getHighestQuality as Pw}from"@vkontakte/videoplayer-shared";var ww=5,Aw=5,kw=500,Pm=7e3,ci=class{constructor(e){this.subscription=new tu;this.loadMediaTimeoutSubscription=new tu;this.videoState=new M("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:vr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:vr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:vr(e)}break}default:vr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(vm(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new tu;this.subscription.add(e),this.subscription.add(xm(this.videoState.stateChangeStarted$.pipe(Em(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Em(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 Ew;e.add(i.pipe(ym(kw)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>ww)&&i.next(o),s=o})),e.add(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Aw&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:vr(n)}}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=xm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Iw(["init"])).pipe(ym(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&E(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];Bt(c);let d=Pw(Object.keys(c));Bt(d);let p=c[d];Bt(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Bt(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];Bt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Bt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Bt(c),r=ae(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Tm.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return vr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Im(o)&&(n.metadata.title=o),Im(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(xw(Pm).subscribe(()=>s(`timeout(${Pm})`)))});(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:Tm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as km}from"@vkontakte/videoplayer-shared";import{clearVideoElement as Rw}from"@vkontakte/videoplayer-shared";var Am=a=>{try{a.pause(),a.playbackRate=0,Rw(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as Lw,Subscription as $w}from"@vkontakte/videoplayer-shared";var ru=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},iu=window.WeakMap?new WeakMap:new ru,au=window.WeakMap?new WeakMap:new Map,Mw=(a,e=20)=>{let t=0;return Lw(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},pe=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?km(t):(t=document.createElement("video"),a.appendChild(t)),iu.set(t,r);let i=new $w;return i.add(Mw(t,e)),au.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},he=a=>{let e=au.get(a);e==null||e.unsubscribe(),au.delete(a);let t=iu.get(a);iu.delete(a),t?km(a):Am(a)};import{assertNonNullable as di,isNonNullable as Qe,isNullable as Ow,fromEvent as yr,merge as Rm,observableFrom as Lm,filterChanged as $m,map as pi,Subject as Mm,Subscription as Bw,ValueSubject as Vw,ErrorCategory as _w}from"@vkontakte/videoplayer-shared";import{isNonNullable as su,isNullable as Cw,Subscription as Dw}from"@vkontakte/videoplayer-shared";var is=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=Cw(i),l=new Dw;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},We=(a,e,t)=>is(e,()=>a.loop,r=>{su(r)&&(a.loop=r)},{onError:t}),fe=(a,e,t,r)=>is(e,()=>({muted:a.muted,volume:a.volume}),i=>{su(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Re=(a,e,t,r)=>is(e,()=>a.playbackRate,i=>{su(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),ft=is;var Nw=a=>["__",a.language,a.label].join("|"),Fw=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},nu=class a{constructor(){this.available$=new Mm;this.current$=new Vw(void 0);this.error$=new Mm;this.subscription=new Bw;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:_w.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(ft(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Qe(s)&&this.setInternal(s)},{equal:(s,n)=>Qe(s)&&Qe(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(pi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(ft(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Qe(s)&&this.setExternal(s)},{equal:(s,n)=>Qe(s)&&Qe(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(pi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(ft(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(ft(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){di(this.video);let{textTracks:e}=this.video;this.subscription.add(yr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Rm(yr(e,"addtrack"),yr(e,"removetrack"),Lm(["init"])).pipe(pi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),$m((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Rm(yr(e,"change"),Lm(["init"])).pipe(pi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),pi(r=>r&&this.htmlTextTrackToITextTrack(r).id),$m()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(yr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(yr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;Qe(t.align)&&(i.align=t.align),Qe(t.position)&&(i.position=t.position),Qe(t.size)&&(i.size=t.size),Qe(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){di(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,i=e.id?e.id:Nw(e),s=this.externalTracks.has(i),n=i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(i))==null?void 0:o.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(i))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){di(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Ow(e)||!Fw(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){di(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){di(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Le=nu;var et=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Cm=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},ou=a=>{let e=Cm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Dm=a=>{let e=Cm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as $e,map as mt,merge as Bm,filterChanged as Uw,isNonNullable as Vm,Subject as Hw,filter as _m,mapTo as Nm,combine as jw,once as Gw,ErrorCategory as Yw,ValueSubject as Fm,clientChecker as Ww}from"@vkontakte/videoplayer-shared";var qw=3,Om=(a,e,t=qw)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var me=a=>{let e=v=>$e(a,v).pipe(Nm(void 0)),r=Bm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>$e(a,v))).pipe(mt(v=>v.type==="ended"?a.readyState<2:a.readyState<3),Uw()),i=Bm($e(a,"progress"),$e(a,"timeupdate")).pipe(mt(()=>Om(a.buffered,a.currentTime))),s=Ww.isSafari?jw({play:e("play").pipe(Gw()),playing:e("playing")}).pipe(Nm(void 0)):e("playing"),n=$e(a,"volumechange").pipe(mt(()=>({muted:a.muted,volume:a.volume}))),o=$e(a,"ratechange").pipe(mt(()=>a.playbackRate)),u=$e(a,"error").pipe(_m(()=>!!(a.error||a.played.length)),mt(()=>{var T;let v=a.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:Yw.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(T=a.error)!=null?T:void 0}})),l=$e(a,"timeupdate").pipe(mt(()=>a.currentTime)),c=new Hw,d=.3,p;l.subscribe(v=>{a.loop&&Vm(p)&&Vm(v)&&p>=a.duration-d&&v<=d&&c.next(p),p=v});let h=e("pause").pipe(_m(()=>!a.error&&p!==a.duration)),f=$e(a,"enterpictureinpicture"),b=$e(a,"leavepictureinpicture"),g=new Fm(Dm(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new Fm(ou(a));return $e(a,"fullscreenchange").pipe(mt(()=>ou(a))).subscribe(S),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:$e(a,"durationchange").pipe(mt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S}};import{VideoQuality as bt}from"@vkontakte/videoplayer-shared";var gt=a=>{switch(a){case"mobile":return bt.Q_144P;case"lowest":return bt.Q_240P;case"low":return bt.Q_360P;case"sd":case"medium":return bt.Q_480P;case"hd":case"high":return bt.Q_720P;case"fullhd":case"full":return bt.Q_1080P;case"quadhd":case"quad":return bt.Q_1440P;case"ultrahd":case"ultra":return bt.Q_2160P}};var pu=Ge(hi(),1);import{isNonNullable as St,isNullable as lu,now as Xm,isHigher as cu,isHigherOrEqual as Km,isInvariantQuality as Jm,isLower as du,isLowerOrEqual as rA,videoSizeToQuality as iA,assertNotEmptyArray as aA}from"@vkontakte/videoplayer-shared";var uu=!1,tt={},Wm=a=>{uu=a},Qm=()=>{tt={}},zm=a=>{a(tt)},fi=(a,e)=>{var t;uu&&(tt.meta=(t=tt.meta)!=null?t:{},tt.meta[a]=e)},ne=class{constructor(e){this.name=e}next(e){var r,i;if(!uu)return;tt.series=(r=tt.series)!=null?r:{};let t=(i=tt.series[this.name])!=null?i:[];t.push([Date.now(),e]),tt.series[this.name]=t}};var sA=new ne("best_bitrate"),nA=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t,as=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Xm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},oA='Assertion "ABR Tracks is empty array" failed',uA=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{var U,L,w,H,W;aA(a,oA);let p=r.usePixelRatio&&(U=window.devicePixelRatio)!=null?U:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},f=h&&iA(h),b=r.considerPlaybackRate&&St(o)?o:1,g=a.filter(k=>!Jm(k.quality)).sort((k,x)=>cu(k.quality,x.quality)?-1:1),S=(L=(0,pu.default)(g,-1))==null?void 0:L.quality,I=(w=(0,pu.default)(g,0))==null?void 0:w.quality,v=lu(i)||St(i.min)&&St(i.max)&&du(i.max,i.min)||St(i.min)&&I&&cu(i.min,I)||St(i.max)&&S&&du(i.max,S),T=b*nA(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),y={},D=g.filter(k=>(f?du(k.quality,f):!0)?(St(t)&&isFinite(t)&&St(k.bitrate)?t-s>=k.bitrate*T:!0)?r.lazyQualitySwitch&&St(r.minBufferToSwitchUp)&&u&&!Jm(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&cu(k.quality,u.quality)?(y[k.quality]="Buffer",!1):!!c&&Km(k.quality,c)?(y[k.quality]="DroppedFramesLimit",!1):v||(lu(i.max)||rA(k.quality,i.max))&&(lu(i.min)||Km(k.quality,i.min))?!0:(y[k.quality]="FitsQualityLimits",!1):(y[k.quality]="FitsThroughput",!1):(y[k.quality]="FitsContainer",!1))[0];D&&D.bitrate&&sA.next(D.bitrate);let $=(H=D!=null?D:g[Math.ceil((g.length-1)/2)])!=null?H:a[0];$.quality!==((W=l==null?void 0:l.last)==null?void 0:W.quality)&&d({message:`
|
|
7
|
+
[available tracks]
|
|
11
8
|
${a.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
|
|
12
9
|
`)}
|
|
13
10
|
|
|
14
11
|
[tuning]
|
|
15
|
-
${Object.entries(r!=null?r:{}).map(([k,
|
|
12
|
+
${Object.entries(r!=null?r:{}).map(([k,x])=>`${k}: ${x}`).join(`
|
|
16
13
|
`)}
|
|
17
14
|
|
|
18
15
|
[limit params]
|
|
@@ -22,40 +19,22 @@ var iv=Object.create;var pn=Object.defineProperty,av=Object.defineProperties,sv=
|
|
|
22
19
|
playbackRate: ${o},
|
|
23
20
|
playbackRateFactor: ${b},
|
|
24
21
|
forwardBufferHealth: ${n},
|
|
25
|
-
bitrateFactor: ${
|
|
22
|
+
bitrateFactor: ${T},
|
|
26
23
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
27
24
|
droppedVideoMaxQualityLimit: ${c},
|
|
28
25
|
limitsAreInvalid: ${v},
|
|
29
26
|
maxQualityLimit: ${i==null?void 0:i.max},
|
|
30
27
|
minQualityLimit: ${i==null?void 0:i.min},
|
|
31
28
|
|
|
32
|
-
[limited
|
|
33
|
-
${Object.entries(
|
|
29
|
+
[limited tracks]
|
|
30
|
+
${Object.entries(y).map(([k,x])=>`${k}: ${x}`).join(`
|
|
34
31
|
`)||"All tracks are available"}
|
|
35
32
|
|
|
36
|
-
[best
|
|
37
|
-
[selected
|
|
38
|
-
`})
|
|
39
|
-
[
|
|
40
|
-
[available audio tracks]
|
|
41
|
-
${e.map(b=>`{ id: ${b.id}, quality: ${b.quality}, bitrate: ${b.bitrate} }`).join(`
|
|
42
|
-
`)}
|
|
43
|
-
|
|
44
|
-
[tuning]
|
|
45
|
-
${Object.entries(i!=null?i:{}).map(([b,g])=>`${b}: ${g}`).join(`
|
|
46
|
-
`)}
|
|
47
|
-
|
|
48
|
-
[limit params]
|
|
49
|
-
throughput: ${r},
|
|
50
|
-
reserve: ${d},
|
|
51
|
-
playbackRate: ${s},
|
|
52
|
-
playbackRateFactor: ${l},
|
|
53
|
-
forwardBufferHealth: ${n},
|
|
54
|
-
bitrateFactor: ${p},
|
|
55
|
-
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
56
|
-
|
|
57
|
-
[selected audio track] ${h==null?void 0:h.bitrate}
|
|
58
|
-
`}),h&&sb(i,u,h,o)};var ie=a=>new URL(a).hostname;import{assertNever as pb,assertNonNullable as hb,combine as Cw,debounce as Dw,ErrorCategory as fb,filter as mb,filterChanged as Ow,isNonNullable as vu,map as ds,merge as bb,observableFrom as Bw,once as Vw,Subscription as _w,ValueSubject as yu,videoQualityToHeight as Nw,videoSizeToQuality as Fw}from"@vkontakte/videoplayer-shared";var ob=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},ge=a=>w(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!ob(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return ob(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as us,isNullable as bw,assertNonNullable as vi}from"@vkontakte/videoplayer-shared";import{isNonNullable as ub,assertNonNullable as os,now as fw}from"@vkontakte/videoplayer-shared";function ae(){return fw()}function mu(a){return ae()-a}function bu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function lb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Ir(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;os(c);let A=mu(c),U;if(A<b){U=b-A,setTimeout(g,U);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,B()},S=A=>(s=A,$),I=A=>(d=A,$),v=()=>(h="json",$),y=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},T=A=>(p=A,$),B=()=>{c=ae(),n=new i,n.open("get",a);let A=0,U,k=0,J=()=>(os(c),Math.max(c,Math.max(U||0,k||0)));if(s&&n.addEventListener("progress",P=>{let N=ae();s.updateChunk&&P.loaded>A&&(s.updateChunk(J(),P.loaded-A),A=P.loaded,U=N)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;os(n);let P=n.status;if(P>=200&&P<300){if(n.response.byteLength&&s){let N=n.response.byteLength-A;N&&s.updateChunk&&s.updateChunk(J(),N)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),p){let P=()=>{os(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(k=ae(),n.removeEventListener("readystatechange",P))};n.addEventListener("readystatechange",P)}return n.responseType=h,n.send(),$},$={withBitrateReporting:S,withParallel:T,withJSONResponse:v,withRetryCount:A=>(l=A,$),withRetryInterval:(A,U)=>(ub(A)&&(b=A),ub(U)&&(f=U),$),withTimeout:A=>(o=A,$),withFinally:I,send:B,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return $}var gi=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 Si=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ae(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ae()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ir(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ae()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ae();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var ls=1e4,gu=3;var gw=6e4,Sw=10,vw=1,yw=500,yi=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 gi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=bu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=bu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||us(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{lb(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 Si(gu,ls,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,B)=>{u&&u.abort(),u=Ir(this.urlResolver.resolve(y,!1),T,B,()=>this._retryCallback()).withTimeout(ls).withBitrateReporting(this.bitrateSwitcher).withRetryCount(gu).withFinally(()=>{u=null}).send()},h=(y,T,B)=>{vi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),T,B,()=>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 B=ae()-1e4,D=0;for(let O=0;O<this.bufferStates.length;O++){let q=this.bufferStates[O];y=Math.min(y,q.buf),q.ts<B&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${y} drop=${D} jitter=${this.sourceJitter}`);let j=y-vw;this.sourceJitter>=0?j-=this.sourceJitter/2:this.sourceJitter-=1,j>3?f(1.15):j>1?f(1.1):j>.3?f(1.05):f(1)}},S=y=>{let T,B=()=>T&&T.start?T.start.length:0,D=P=>T.start[P]/1e3,j=P=>T.dur[P]/1e3,O=P=>T.fragIndex+P,q=(P,N)=>({chunkIdx:O(P),startTS:D(P),dur:j(P),discontinuity:N}),$=()=>{let P=0;if(T&&T.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,W=N;this.sourceJitter>1&&(W+=this.sourceJitter-1);let Z=T.dur.length-1;for(;Z>=0&&(W-=T.dur[Z],!(W<=0));--Z);P=Math.min(Z,T.dur.length-1-G),P=Math.max(P,0)}return q(P,!0)},A=P=>{let N=B();if(!(N<=0)){if(us(P)){for(let G=0;G<N;G++)if(D(G)>P)return q(G)}return $()}},U=P=>{let N=B(),G=P?P.chunkIdx+1:0,W=G-T.fragIndex;if(!(N<=0)){if(!P||W<0||W-N>Sw)return t(`Resync: offset=${W} bChunks=${N} chunk=`+JSON.stringify(P)),$();if(!(W>=N))return q(G-T.fragIndex,!1)}},k=(P,N,G)=>{l&&l.abort(),l=Ir(this.urlResolver.resolve(P,!0,this.lowLatency),N,G,()=>this._retryCallback()).withTimeout(ls).withRetryCount(gu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(P,N)=>{k(y,G=>{if(!d())return;T=G;let W=!!T.lowLatency;W!==this.lowLatency&&b(W);let Z=0;for(let Ae=0;Ae<T.dur.length;++Ae)Z+=T.dur[Ae];Z>0&&(vi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Z/T.dur.length)),i({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,P(A(N))},()=>this._handleNetworkError())},nextChunk:U}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),vi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:T,logger:B}=this.params,D=S(e.jidxUrl),j,O,q,$,A=0,U,k,J,P=()=>{U&&(clearTimeout(U),U=void 0);let V=Math.max(yw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ee=A+V,L=ae(),le=Math.min(1e4,ee-L);A=L;let Be=()=>{l||d()&&D.seek(()=>{d()&&(A=ae(),N(),P())})};le>0?U=window.setTimeout(()=>{this.paused?P():Be()},le):Be()},N=()=>{let V;for(;V=D.nextChunk($);)$=V,Pt(V);let ee=D.nextChunk(q);if(ee){if(q&&ee.discontinuity){B("Detected discontinuity; restarting playback"),this.paused?P():(I(),this._initPlayerWith(e));return}Ae(ee)}else P()},G=(V,ee)=>{if(!d()||!this.sourceBuffer)return;let L,le,Be,Xe=pt=>{window.setTimeout(()=>{d()&&G(V,ee)},pt)};if(this.sourceBuffer.updating)B("Source buffer is updating; delaying appendBuffer"),Xe(100);else{let pt=ae(),At=T.currentTime;!this.paused&&T.buffered.length>1&&k===At&&pt-J>500&&(B("Stall suspected; trying to fix"),this._fixupStall()),k!==At&&(k=At,J=pt);let Zt=this._getBufferSizeSec();if(Zt>30)B(`Buffered ${Zt} seconds; delaying appendBuffer`),Xe(2e3);else try{this.sourceBuffer.appendBuffer(V),this.videoPlayStarted?(this.bufferStates.push({ts:pt,buf:Zt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ee&&ee()}catch(Br){if(Br.name==="QuotaExceededError")B("QuotaExceededError; delaying appendBuffer"),Be=this.sourceBuffer.buffered.length,Be!==0&&(L=this.sourceBuffer.buffered.start(0),le=At,le-L>4&&this.sourceBuffer.remove(L,le-3)),Xe(1e3);else throw Br}}},W=()=>{O&&j&&(B([`Appending chunk, sz=${O.byteLength}:`,JSON.stringify(q)]),G(O,function(){O=null,N()}))},Z=V=>e.fragUrlTemplate.replace("%%id%%",V.chunkIdx),Ae=V=>{d()&&h(Z(V),(ee,L)=>{if(d()){if(L/=1e3,O=ee,q=V,n=V.startTS,L){let le=Math.min(10,V.dur/L);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*le:le}W()}},()=>this._handleNetworkError())},Pt=V=>{d()&&(vi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Z(V),!1)))},dt=V=>{d()&&(e.cachedHeader=V,G(V,()=>{j=!0,W()}))};s=!0,D.seek(V=>{if(d()){if(A=ae(),!V){P();return}$=V,!bw(y)||V.startTS>y?Ae(V):(q=V,N())}},y),e.cachedHeader?dt(e.cachedHeader):p(e.headerUrl,dt,()=>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(),us(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,vi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return us(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=ae();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&mu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ae();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Ir(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ls).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;ge(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))},gw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Tw,filter as cb,fromEvent as Iw,interval as Ew,isHigher as xw,isInvariantQuality as Pw,isLower as Aw,merge as ww,Subject as db,Subscription as kw}from"@vkontakte/videoplayer-shared";var Su=class{constructor(){this.onDroopedVideoFramesLimit$=new db;this.subscription=new kw;this.playing=!1;this.tracks=[];this.forceChecker$=new db;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&&!Pw(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&&xw(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(Iw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Ew(this.droppedFramesChecker.checkTime).pipe(cb(()=>this.playing),cb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(Tw(this.droppedFramesChecker.checkTime)),r=ww(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])=>Aw(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},cs=Su;import{map as Rw,Observable as Lw}from"@vkontakte/videoplayer-shared";import{fromEvent as $w}from"@vkontakte/videoplayer-shared";var Ti=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Mw=(a,e)=>new Lw(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ti()))},R(R({},r),e));i.observe(a);let s=$w(document,"visibilitychange").pipe(Rw(n=>!document.hidden||Ti())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ce=Mw;var qw=["paused","playing","ready"],Uw=["paused","playing","ready"],Ii=class{constructor(e){this.subscription=new _w;this.videoState=new M("stopped");this.representations$=new yu([]);this.textTracksManager=new $e;this.droppedFramesManager=new cs;this.maxSeekBackTime$=new yu(1/0);this.zeroTime$=new yu(void 0);this.liveOffset=new it;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:fb.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=vt(u.name))!=null?r:Fw(u.video),d=u.bitrate/1e3,p=R({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),vu(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(Uw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&qw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(se(this.params.source.url,u))}return;default:return pb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:fb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};bb(this.videoState.stateChangeStarted$.pipe(ds(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ds(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=he(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=be(this.video);this.subscription.add(this.representations$.pipe(ds(i=>i.map(({track:s})=>s)),mb(i=>!!i.length),Vw()).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(Ow(),ds(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Cw({zeroTime:this.zeroTime$.pipe(mb(vu)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(ze(this.video,this.params.desiredState.isLooped,t)).add(me(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(Ce(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&Nw(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 pb(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$,Bw(["init"])).pipe(Dw(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),fe(this.video)}createLiveDashPlayer(){let e=new yi({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&&vu(t)?t:yt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;hb(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;hb(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(se(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var gb=Ii;var st=(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 dR,assertNonNullable as pR,debounce as hR,ErrorCategory as Qu,filter as jg,filterChanged as zu,fromEvent as fR,isLowerOrEqual as Gg,isNonNullable as mR,isInvariantQuality as bR,map as Yg,merge as Bs,observableFrom as gR,observeElementSize as SR,once as Wg,Subscription as vR,ValueSubject as yR}from"@vkontakte/videoplayer-shared";var ps=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Er=class extends ps{constructor(){super(),this.listeners||ps.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Ei=class{constructor(){Object.defineProperty(this,"signal",{value:new Er,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&&(Ei.prototype[Symbol.toStringTag]="AbortController",Er.prototype[Symbol.toStringTag]="AbortSignal");function hs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Tu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!hs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(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 xi=hs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Sb=xi?Tu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,nt=xi?Sb.fetch:window.fetch,xO=xi?Sb.Request:window.Request,ot=xi?Ei:window.AbortController,PO=xi?Er:window.AbortSignal;var $b=We(fi(),1);var ut=()=>window.ManagedMediaSource||window.MediaSource,fs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},vb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},yb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Es,clientChecker as Is}from"@vkontakte/videoplayer-shared";var De=document.createElement("video"),Gw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Yw='video/mp4; codecs="hev1.1.6.L93.B0"',Mb='video/webm; codecs="vp09.00.10.08"',Cb='video/webm; codecs="av01.0.00M.08"',Ww='audio/mp4; codecs="mp4a.40.2"',Qw='audio/webm; codecs="opus"',Tb,Ib,qt={mms:fs(),mse:vb(),hls:!!((Tb=De.canPlayType)!=null&&Tb.call(De,"application/x-mpegurl")||(Ib=De.canPlayType)!=null&&Ib.call(De,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Eb,xb,Se={mp4:!!((Eb=De.canPlayType)!=null&&Eb.call(De,"video/mp4")),webm:!!((xb=De.canPlayType)!=null&&xb.call(De,"video/webm")),cmaf:!0},bs,Pb,gs,Ab,Ss,wb,vs,kb,ys,Rb,Ts,Lb,ve={h264:!!((Pb=(bs=ut())==null?void 0:bs.isTypeSupported)!=null&&Pb.call(bs,Gw)),h265:!!((Ab=(gs=ut())==null?void 0:gs.isTypeSupported)!=null&&Ab.call(gs,Yw)),vp9:!!((wb=(Ss=ut())==null?void 0:Ss.isTypeSupported)!=null&&wb.call(Ss,Mb)),av1:!!((kb=(vs=ut())==null?void 0:vs.isTypeSupported)!=null&&kb.call(vs,Cb)),aac:!!((Rb=(ys=ut())==null?void 0:ys.isTypeSupported)!=null&&Rb.call(ys,Ww)),opus:!!((Lb=(Ts=ut())==null?void 0:Ts.isTypeSupported)!=null&&Lb.call(Ts,Qw))},xr=(ve.h264||ve.h265)&&ve.aac,Ut,zw=()=>w(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(F(R({},a),{video:F(R({},a.video),{contentType:Cb})})),window.navigator.mediaCapabilities.decodingInfo(F(R({},a),{video:F(R({},a.video),{contentType:Mb})}))]);Ut={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{zw()}catch(a){console.error(a)}var Pr=qt.hls&&Se.mp4,Db=()=>Object.keys(ve).filter(a=>ve[a]),Ob=(a,e=!1,t=!1)=>{let r=qt.mse||qt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&Se.mp4&&xr;case"DASH_WEBM":return r&&Se.webm&&ve.vp9&&ve.opus;case"DASH_WEBM_AV1":return r&&Se.webm&&ve.av1&&ve.opus;case"DASH_STREAMS":return r&&(Se.mp4&&xr||Se.webm&&(ve.vp9||ve.av1)&&(ve.opus||ve.aac));case"DASH_LIVE":return qt.mse&&Se.mp4&&xr;case"DASH_LIVE_CMAF":return r&&Se.mp4&&xr&&Se.cmaf;case"DASH_ONDEMAND":return r&&Se.mp4&&xr;case"HLS":case"HLS_ONDEMAND":return Pr||e&&qt.mse&&Se.mp4&&xr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Pr;case"MPEG":return Se.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return qt.webrtc&&qt.ws&&ve.h264&&(Se.mp4||Se.webm);default:return Es(i)}})},ms=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Ut?Ut[t].smooth?[t,e]:Ut[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Ut?Ut[t].powerEfficient?[t,e]:Ut[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Es(a)}return[e,t]},Bb=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ms(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Is.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...ms(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ms(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ms(a),...i,"HLS","HLS_ONDEMAND"];default:Es(e)}return Pr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Vb=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=Is.isMac&&Is.isSafari;if(Is.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Es(a)}else Pr&&!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"]},Iu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],_b=a=>{if(a.size!==0){if(a.size===1)return a.values().next().value.split(".").at(0);for(let e of a){let t=(0,$b.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as Pi}from"@vkontakte/videoplayer-shared";var Nb=a=>{if(!a)return{id:"EmptyResponse",category:Pi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Pi.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:Pi.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:Pi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Pi.PARSER,message:"Response is valid XML, but parser failed"}};var Ai=(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 Gu,assertNonNullable as Jt,combine as Ls,ErrorCategory as It,filter as $s,filterChanged as Vg,fromEvent as Mr,interval as Yu,isNonNullable as _g,map as Wu,merge as Cr,Subject as Ng,Subscription as Fg,tap as aR,throttle as sR,clientChecker as nR,ValueSubject as ue}from"@vkontakte/videoplayer-shared";var $r=We(fi(),1);var Kw=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},Jw=a=>window.clearTimeout(a),Fb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Eu=Fb?Kw:window.requestIdleCallback,FO=Fb?Jw:window.cancelIdleCallback;var Lg=We(is(),1);import{assertNever as Xw,ErrorCategory as qb,clientChecker as xu,Subject as Ub}from"@vkontakte/videoplayer-shared";var Zw=16,Hb=!1;try{Hb=xu.isSafari&&!!xu.macVersion&&xu.macVersion<=Zw}catch(a){console.error(a)}var Pu=class{constructor(e){this.bufferFull$=new Ub;this.error$=new Ub;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:qb.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return w(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return w(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return w(this,null,function*(){return new Promise(t=>{let r;Hb&&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:qb.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:Xw(t)}}},jb=Pu;var Au=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 Lr,assertNonNullable as Je,ErrorCategory as Qt,fromEvent as Nu,getExponentialDelay as Fu,isNonNullable as Rg,isNullable as He,once as Kk,Subject as Jk,Subscription as Xk,ValueSubject as zi}from"@vkontakte/videoplayer-shared";var H=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 Ar=class extends H{};var wi=class extends H{};var ki=class extends H{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 Ri=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Li=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends H{constructor(e,t){super(e,t),this.data=this.content}};var K=class extends H{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ht=class extends K{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 Mi=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ci=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends K{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 Oi=class extends K{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Bi=class extends K{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Vi=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends K{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 Ni=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Fi=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qi=class extends K{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ui=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Hi=class extends K{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 ji=class extends K{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 Gi=class extends K{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 tk={ftyp:ki,moov:Ri,moof:Li,mdat:$i,sidx:Ht,trak:Mi,mdia:Vi,mfhd:qi,tkhd:_i,traf:Ui,tfhd:Hi,tfdt:ji,trun:Gi,minf:Ni,sv3d:Ci,st3d:Di,prhd:Oi,proj:Fi,equi:Bi,uuid:wi,unknown:Ar},jt=class a{constructor(e={}){this.options=R({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=tk[e];return r?new r(t,new a):new Ar(t,new a)}};var wr=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 ik=new TextDecoder("ascii"),ak=a=>ik.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",sk=a=>{let e=new Ht(a,new jt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},nk=(a,e)=>{let r=new jt().parse(a),i=new wr(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)},ok=(a,e)=>{let r=new jt().parse(a),s=new wr(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},uk=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 wr(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},Gb={validateData:ak,parseInit:uk,getIndexRange:()=>{},parseSegments:sk,parseFeedableSegmentChunk:nk,getSegmentEndTime:ok};import{assertNonNullable as ku,isNonNullable as zb,isNullable as ck}from"@vkontakte/videoplayer-shared";import{assertNever as lk}from"@vkontakte/videoplayer-shared";var Yb={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"}},Wb=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=Yi(a,t),i=r in Yb,s=i?Yb[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=Yi(u),d=l*Ye(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}},Yi=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*Ye(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*Ye(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*Ye(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ue=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Yi(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:lk(e)}},Gt=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Wb(r);if(!e(i))return;i.type==="master"&&Gt(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Qb=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Wb(a);return Gt(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ue(o,n):s===17026?t=Ue(o,n):s===17029&&(r=Ue(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Kb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],dk=[231,22612,22743,167,171,163,160,175],pk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Gt(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Ue(f,h);l=Yi(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=Ue(f,h):p===17545?i=Ue(f,h):p===21420&&l===475249515?u=Ue(f,h):p===374648427?Gt(f,({tag:g,type:S,value:I})=>g===30321?(c=Ue(I,S)===1,!1):!0):s&&n&&Kb.includes(p)&&(o=!0),!o}),ku(e,"Failed to parse webm Segment start"),ku(t,"Failed to parse webm Segment end"),ku(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}}}},hk=a=>{if(ck(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},fk=(a,e)=>{let t=!1,r=!1,i=o=>zb(o.time)&&zb(o.position),s=[],n;return Gt(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ue(l,u));break;case 183:break;case 241:n&&(n.position=Ue(l,u));break;default:t&&Kb.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},mk=a=>{let e=0,t=!1;try{Gt(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):dk.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Jb={validateData:Qb,parseInit:pk,getIndexRange:hk,parseSegments:fk,parseFeedableSegmentChunk:mk};var kr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Jb;case"mp4":return Gb}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Ou=We(vg(),1);var Du=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 Tg,isNullable as Ig}from"@vkontakte/videoplayer-shared";var yg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Eg=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},Yt=(a,e)=>{let t=a;t=(0,Ou.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,Ou.default)(t,n,(o,u)=>Ig(s)?o:Ig(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Pg=(a,e)=>{var y,T,B,D,j,O,q,$,A,U,k,J,P,N,G,W,Z,Ae,Pt,dt,V,ee,L,le,Be,Xe,pt,At,Zt,Br,cl,dl,pl,hl,fl,ml,bl,gl,Sl,vl,yl,Tl,Il,El,xl,Pl,Al,wl,kl,Rl;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(B=(T=(y=s.querySelector("BaseURL"))==null?void 0:y.textContent)==null?void 0:T.trim())!=null?B:"",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=Eg(h);else if(f){let ce=Eg(f);Tg(ce)&&(p=ce)}else g&&(p=parseInt(g,10));let S=0,I=(j=(D=s.getAttribute("profiles"))==null?void 0:D.split(","))!=null?j:[];for(let ce of u){let BS=(O=ce.getAttribute("id"))!=null?O:"id"+(S++).toString(10),Vr=(q=ce.getAttribute("mimeType"))!=null?q:"",Xs=($=ce.getAttribute("codecs"))!=null?$:"",Zs=(A=ce.getAttribute("contentType"))!=null?A:Vr==null?void 0:Vr.split("/")[0],VS=(k=(U=ce.getAttribute("profiles"))==null?void 0:U.split(","))!=null?k:[],_S=(J=ce.getAttribute("lang"))!=null?J:void 0,NS=(G=(N=(P=ce.querySelector("Label"))==null?void 0:P.textContent)==null?void 0:N.trim())!=null?G:void 0,FS=ce.querySelectorAll("Representation"),qS=ce.querySelector("SegmentTemplate"),US=(Z=(W=ce.querySelector("Role"))==null?void 0:W.getAttribute("value"))!=null?Z:void 0,_r=Zs,te={id:BS,language:_S,isDefault:US==="main",label:NS,codecs:Xs,hdr:_r==="video"&&Du(Xs),mime:Vr,representations:[]};for(let X of FS){let HS=(Ae=X.getAttribute("lang"))!=null?Ae:void 0,jS=(Pt=X.getAttribute("label"))!=null?Pt:void 0,GS=(ee=(V=(dt=X.querySelector("BaseURL"))==null?void 0:dt.textContent)==null?void 0:V.trim())!=null?ee:"",en=new URL(GS||o,e).toString(),er=(L=X.getAttribute("mimeType"))!=null?L:Vr,ma=(Be=(le=X.getAttribute("codecs"))!=null?le:Xs)!=null?Be:"",tn;if(Zs==="text"){let wt=X.getAttribute("id")||"",rn=wt.includes("_auto");tn={id:wt,isAuto:rn,kind:"text",url:en}}else{let wt=(pt=(Xe=X.getAttribute("contentType"))!=null?Xe:er==null?void 0:er.split("/")[0])!=null?pt:Zs,rn=(Zt=(At=ce.getAttribute("profiles"))==null?void 0:At.split(","))!=null?Zt:[],YS=parseInt((Br=X.getAttribute("width"))!=null?Br:"",10),Ll=parseInt((cl=X.getAttribute("height"))!=null?cl:"",10),$l=parseInt((dl=X.getAttribute("bandwidth"))!=null?dl:"",10)/1e3,Ml=(pl=X.getAttribute("frameRate"))!=null?pl:"",WS=(hl=X.getAttribute("quality"))!=null?hl:void 0,QS=Ml?yg(Ml):void 0,zS=(fl=X.getAttribute("id"))!=null?fl:"id"+(S++).toString(10),KS=wt==="video"?`${Ll}p`:wt==="audio"?`${$l}Kbps`:ma,JS=`${zS}@${KS}`,XS=[...I,...VS,...rn],an,ZS=X.querySelector("SegmentBase"),kt=(ml=X.querySelector("SegmentTemplate"))!=null?ml:qS;if(ZS){let Rt=(gl=(bl=X.querySelector("SegmentBase Initialization"))==null?void 0:bl.getAttribute("range"))!=null?gl:"",[Lt,nn]=Rt.split("-").map(tr=>parseInt(tr,10)),ht={from:Lt,to:nn},Nr=(Sl=X.querySelector("SegmentBase"))==null?void 0:Sl.getAttribute("indexRange"),[on,ba]=Nr?Nr.split("-").map(tr=>parseInt(tr,10)):[],Fr=Nr?{from:on,to:ba}:void 0;an={type:"byteRange",url:en,initRange:ht,indexRange:Fr}}else if(kt){let Rt={representationId:(vl=X.getAttribute("id"))!=null?vl:void 0,bandwidth:(yl=X.getAttribute("bandwidth"))!=null?yl:void 0},Lt=parseInt((Tl=kt.getAttribute("timescale"))!=null?Tl:"",10),nn=(Il=kt.getAttribute("initialization"))!=null?Il:"",ht=kt.getAttribute("media"),Nr=(xl=parseInt((El=kt.getAttribute("startNumber"))!=null?El:"",10))!=null?xl:1,on=Yt(nn,Rt);if(!ht)throw new ReferenceError("No media attribute in SegmentTemplate");let ba=(Pl=kt.querySelectorAll("SegmentTimeline S"))!=null?Pl:[],Fr=[],tr=0,un="",ln=0;if(ba.length){let ga=Nr,Ve=0;for(let rr of ba){let Ge=parseInt((Al=rr.getAttribute("d"))!=null?Al:"",10),$t=parseInt((wl=rr.getAttribute("r"))!=null?wl:"",10)||0,Sa=parseInt((kl=rr.getAttribute("t"))!=null?kl:"",10);Ve=Number.isFinite(Sa)?Sa:Ve;let cn=Ge/Lt*1e3,dn=Ve/Lt*1e3;for(let va=0;va<$t+1;va++){let tv=Yt(ht,F(R({},Rt),{segmentNumber:ga.toString(10),segmentTime:(Ve+va*Ge).toString(10)})),Cl=(dn!=null?dn:0)+va*cn,rv=Cl+cn;ga++,Fr.push({time:{from:Cl,to:rv},url:tv})}Ve+=($t+1)*Ge,tr+=($t+1)*cn}ln=Ve/Lt*1e3,un=Yt(ht,F(R({},Rt),{segmentNumber:ga.toString(10),segmentTime:Ve.toString(10)}))}else if(Tg(p)){let Ve=parseInt((Rl=kt.getAttribute("duration"))!=null?Rl:"",10)/Lt*1e3,rr=Math.ceil(p/Ve),Ge=0;for(let $t=1;$t<rr;$t++){let Sa=Yt(ht,F(R({},Rt),{segmentNumber:$t.toString(10),segmentTime:Ge.toString(10)}));Fr.push({time:{from:Ge,to:Ge+Ve},url:Sa}),Ge+=Ve}ln=Ge,un=Yt(ht,F(R({},Rt),{segmentNumber:rr.toString(10),segmentTime:Ge.toString(10)}))}let ev={time:{from:ln,to:1/0},url:un};an={type:"template",baseUrl:en,segmentTemplateUrl:ht,initUrl:on,totalSegmentsDurationMs:tr,segments:Fr,nextSegmentBeyondManifest:ev,timescale:Lt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!wt||!er)continue;let sn={video:"video",audio:"audio",text:"text"}[wt];if(!sn)continue;_r||(_r=sn),tn={id:JS,kind:sn,segmentReference:an,profiles:XS,duration:p,bitrate:$l,mime:er,codecs:ma,width:YS,height:Ll,fps:QS,quality:WS}}te.language||(te.language=HS),te.label||(te.label=jS),te.mime||(te.mime=er),te.codecs||(te.codecs=ma),te.hdr||(te.hdr=_r==="video"&&Du(ma)),te.representations.push(tn)}_r&&i[_r].push(te)}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,streams:i}};var Wi=We(fi(),1);import{videoSizeToQuality as zk}from"@vkontakte/videoplayer-shared";var Ag=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?vt(s):void 0)!=null?o:zk({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}),xs=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Wi.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Wi.default)(t,-1)},kg=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Vu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Wi.default)(r.split("."),0),isDefault:i}),_u=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Wi.default)(i.split("."),0)}),Ps=a=>"url"in a,Wt=a=>a.type==="template",Qi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Ki=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new zi(0);this.onLastSegment$=new zi(!1);this.fullyBuffered$=new zi(!1);this.playingRepresentation$=new zi(void 0);this.playingRepresentationInit$=new zi(void 0);this.error$=new Jk;this.gaps=[];this.subscription=new Xk;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.loadByteRangeSegmentsTimeoutId=0;this.startWith=Lr(this.destroyAbortController.signal,function(e){return re(this,null,function*(){let t=this.representations.get(e);Je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new jb(this.sourceBuffer),this.subscription.add(Nu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Qt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Qt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Nu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Qt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,Au(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=st(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,l<c)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Je(r,"No init buffer for starting representation"),Je(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=Lr(this.destroyAbortController.signal,function(e,t=!1){return re(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Je(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(He(s)||He(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Je(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Rg(n)&&(this.isLive||(i.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Lr(this.destroyAbortController.signal,function(e){return re(this,null,function*(){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!Wt(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);Je(i);let s=this.segments.get(r);Je(s,"No segments for starting representation");let n=this.initData.get(r);if(Je(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.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(He(e)||He(this.downloadingRepresentationId)||He(this.playingRepresentationId)||He(this.sourceBuffer)||!He(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Je(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((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=st(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)&&Au(this.sourceBuffer.buffered)>=this.bufferLimit){let d=st(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,$r.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&&st(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,$r.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;Rg(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||!Wt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>F(R({},p),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,$r.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;Je(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Wt(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=Yt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&I&&this.sourceBuffer&&!Ai(this.sourceBuffer.buffered,r))&&g&&I});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return w(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return w(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Lr(o,function(){return re(this,null,function*(){let c=Fu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=kr(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Qi(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return w(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Lr(n,function(){return re(this,null,function*(){let u=Fu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Nu(window,"online").pipe(Kk()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Qi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(Wt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,$r.default)(e,0).byte.from,to:(0,$r.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Qt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Wt(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Qt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return w(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=kr(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,l=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:l;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,g=p?d.byte.to-r:e.byteLength,S=b<i,I=g<=i;if(d.status==="downloading"&&S&&I){d.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+b,h);this.sourceBufferTaskQueue.append(v,s).then(y=>y&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(c.loadedBytes=Math.min(h,i-b),c.loadedBytes>c.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),y=c.loadedBytes===h?v:kr(o.mime).parseFeedableSegmentChunk(v);y!=null&&y.byteLength&&(d.status="partially_fed",c.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(T=>{if(s.aborted)n();else if(T)c.fedBytes+=y.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return w(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,f=d<i,b=p<=i;if(f){if(c.status==="downloading"&&b){c.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(g,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?g:kr(u.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):n())}}}})}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ps(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Eu(()=>(0,Lg.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return w(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Lr(this.destroyAbortController.signal,function(){return re(this,null,function*(){let o=Fu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,kr(e.mime),i)).then(o=>w(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Wt(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Qt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return w(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return w(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return w(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||He(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=Ps(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}pruneBufferOld(e,t,r=!1){return w(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||He(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=Ps(l)?(d=l.size)!=null?d:0:l.byte.to-l.byte.from;i+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){i=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let c of l){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let c=this.sourceBuffer.buffered.start(l)*1e3,d=this.sourceBuffer.buffered.end(l)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){i=0,s=1/0,n=-1/0;let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+l&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Eu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Qt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(He(this.sourceBuffer)||He(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=1;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var Ji=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var $g=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 Xi,assertNever as Mg,fromEvent as Cg,merge as Zk,now as qu,Subscription as eR,ValueSubject as Uu}from"@vkontakte/videoplayer-shared";var As=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new Uu(void 0);this.lastConnectionReused$=new Uu(void 0);this.lastRequestFirstBytes$=new Uu(void 0);this.abortAllController=new ot;this.subscription=new eR;this.fetchManifest=Xi(this.abortAllController.signal,function(e){return re(this,null,function*(){let t=e;this.requestQuic&&(t=Ji(t));let r=yield nt(t,{signal:this.abortAllController.signal}).catch(Zi);return r?(this.onHeadersReceived(r.headers),r.text()):null})}.bind(this));this.fetch=Xi(this.abortAllController.signal,function(l){return re(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var O,q;let c=e,d=new Headers;if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let $=new URL(c,location.href);$.searchParams.append("bytes",`${r.from}-${r.to}`),c=$.toString();break}default:Mg(t)}this.requestQuic&&(c=Ji(c));let p=this.abortAllController.signal,h;if(n){let $=new ot;if(h=Zk(Cg(this.abortAllController.signal,"abort"),Cg(n,"abort")).subscribe(()=>{try{$.abort()}catch(A){Zi(A)}}),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(A){Zi(A)}p=$.signal}let f=qu(),b=yield nt(c,{priority:s,headers:d,signal:p}).catch(Zi),g=qu();if(!b)return h==null||h.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(g-f),!b.ok||!b.body)return h==null||h.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!i&&!o)return h==null||h.unsubscribe(),b.arrayBuffer();let[S,I]=b.body.tee(),v=S.getReader();o&&((q=this.throughputEstimator)==null||q.trackStream(I,u));let y=0,T=new Uint8Array(0),B=!1,D=$=>{h==null||h.unsubscribe(),B=!0,Zi($)},j=Xi(p,function(U){return re(this,arguments,function*({done:$,value:A}){if(y===0&&this.lastRequestFirstBytes$.next(qu()-f),p.aborted){h==null||h.unsubscribe();return}if(!$&&A){let k=new Uint8Array(T.length+A.length);k.set(T),k.set(A,T.length),T=k,y+=A.byteLength,i==null||i(new DataView(T.buffer),y),yield v==null?void 0:v.read().then(j,D)}})}.bind(this));return yield v==null?void 0:v.read().then(j,D),h==null||h.unsubscribe(),B?null:T.buffer})}.bind(this));this.fetchByteRangeRepresentation=Xi(this.abortAllController.signal,function(e,t,r){return re(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(S=e.indexRange)!=null?S:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let I=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!I)return null;b=new DataView(I)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Xi(this.abortAllController.signal,function(e,t){return re(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>F(R({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){let{type:t,reused:r}=$g(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return w(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Mg(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Zi=a=>{if(!Qi(a))throw a};var zt=(a,e,t)=>t*e+(1-t)*a,Hu=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Dg=(a,e,t,r)=>{let i=0,s=t,n=Hu(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 tR,ValueSubject as Og}from"@vkontakte/videoplayer-shared";var Tt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Og(e.initial),this.debounced$=new Og(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new oe(`raw_${t}`),this.smoothedSeries$=new oe(`smoothed_${t}`),this.reportedSeries$=new oe(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Ye(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(tR(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var ws=class extends Tt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=zt(this.slow,e,this.params.emaAlphaSlow),this.fast=zt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ks=class extends Tt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Hu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=zt(this.emaSmoothed,e,this.params.emaAlpha);let r=Dg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Rs=class extends Tt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?zt(this.smoothed,t,this.params.emaAlpha):t}};var Kt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ws({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ks({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Rs(R({initial:e,label:"liveEdgeDelay"},t))}};var ju=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var qg=["timeupdate","progress","play","seeked","stalled","waiting"];var Ms=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Fg;this.representationSubscription=new Fg;this.state$=new M("none");this.currentVideoRepresentation$=new ue(void 0);this.currentVideoRepresentationInit$=new ue(void 0);this.currentAudioRepresentation$=new ue(void 0);this.currentVideoSegmentLength$=new ue(0);this.currentAudioSegmentLength$=new ue(0);this.error$=new Ng;this.lastConnectionType$=new ue(void 0);this.lastConnectionReused$=new ue(void 0);this.lastRequestFirstBytes$=new ue(void 0);this.isLive$=new ue(!1);this.liveDuration$=new ue(0);this.liveAvailabilityStartTime$=new ue(void 0);this.bufferLength$=new ue(0);this.liveLoadBufferLength$=new ue(0);this.livePositionFromPlayer$=new ue(0);this.timeInWaiting=0;this.isActiveLowLatency$=new ue(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Ng;this.gapWatchdogActive=!1;this.destroyController=new ot;this.initManifest=Gu(this.destroyController.signal,function(e,t,r){return re(this,null,function*(){var i;this.element=e,this.manifestUrlString=se(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:It.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Gu(this.destroyController.signal,function(){return re(this,null,function*(){var s,n;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:It.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t;try{t=Pg(e!=null?e:"",this.manifestUrlString)}catch(o){let u=(s=Nb(e))!=null?s:{id:"ManifestParsing",category:It.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(u)}if(!t)return null;let r=(o,u,l)=>{var c,d,p,h;return!!((d=(c=this.element)==null?void 0:c.canPlayType)!=null&&d.call(c,u)&&((h=(p=ut())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${l}"`))||o==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((n=t.duration)!=null?n:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let o of["video","audio"]){let l=t.streams[o].filter(({mime:p,codecs:h})=>r(o,p,h)),c=new Set(l.map(({codecs:p})=>p)),d=_b(c);if(d&&(i[o]=l.filter(({codecs:p})=>p.startsWith(d))),o==="video"){let p=this.tuning.preferHDR,h=i.video.some(b=>b.hdr),f=i.video.some(b=>!b.hdr);nR.isHDR&&p&&h?i.video=i.video.filter(b=>b.hdr):f&&(i.video=i.video.filter(b=>!b.hdr))}}return F(R({},t),{streams:i})})}.bind(this));this.initRepresentations=Gu(this.destroyController.signal,function(e,t,r){return re(this,null,function*(){var d;Jt(this.manifest),Jt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Mr(p,"error").pipe($s(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:It.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?yb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&fs())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Ki("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],_g(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Ki("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Yu(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=ru(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Cr(...qg.filter(p=>p!=="waiting").map(p=>Mr(this.element,p))).pipe(Wu(p=>this.element?st(this.element.buffered,this.element.currentTime*1e3):0),Vg(),$s(p=>!!p),aR(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Vg()).subscribe(h=>ju(this.element,1))),this.representationSubscription.add(Ls({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe($s(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(Ls({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b,v=1;Math.abs(I)>g&&(v=1+Math.sign(I)*S),ju(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let S=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(v=>{var y,T;return(T=(y=v.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?T:S}))-S}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(Ls({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(sR(1e3)).subscribe(b=>w(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(Jt(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,S=ru(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,B=isFinite(h)?h:f,D=this.isActiveLowLatency$.getValue(),j=I<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLowLatency$.next(D&&j);let O="none";if(D?O="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&j?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(q=>q.proceedLowLatencyLive()),O="active_low_latency"):S!==0&&B<v?O="live_forward_buffering":B<v+T&&(O="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),O==="live_forward_buffering"||O==="live_with_target_offset"){let q=p-(v+y),$=this.normolizeLiveOffset(Math.trunc(S+q/g)),A=Math.abs($-S),U;!h||A<=this.tuning.dashCmafLive.offsetCalculationError?U=S:$>0&&A>this.tuning.dashCmafLive.offsetCalculationError?U=$:U=0,this.manifestUrlString=se(this.manifestUrlString,U,2)}O!=="none"&&O!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=Cr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Wu(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=Cr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Wu(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Cr(this.forceEnded$,Ls({allBuffersFull:u,someBufferEnded:l}).pipe($s(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:It.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Cr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let c=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{var h;return(h=p.duration)!=null?h:0})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&_g(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")})}.bind(this));this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Yu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:It.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new As({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Kt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,R({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return w(this,null,function*(){var r,i,s,n;Jt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=se(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio))})}initBuffer(){Jt(this.element),this.state$.setState("running"),this.subscription.add(Cr(...qg.map(e=>Mr(this.element,e)),Mr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:It.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Mr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Mr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ai(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var r,i;if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset);else{let s=this.element.currentTime*1e3;(r=this.videoBufferManager)==null||r.maintain(s),(i=this.audioBufferManager)==null||i.maintain(s)}}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Yu(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:It.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return w(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u;Jt(this.element),Jt(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Ai(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3}stop(){var e,t,r;(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return w(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],i=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-i<=t&&n.to+i>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var Cs=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ds=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Ye(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=R({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*Ye(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Ug=`attribute vec2 a_vertex;
|
|
33
|
+
[best track] ${D==null?void 0:D.quality}
|
|
34
|
+
[selected track] ${$==null?void 0:$.quality}
|
|
35
|
+
`});let O=$&&l&&l.history[$.id]&&Xm()-l.history[$.id]<=r.trackCooldown&&(!l.last||$.id!==l.last.id);if($!=null&&$.id&&l&&!O&&l.recordSelection($),O&&(l!=null&&l.last)){let k=l.last;return l==null||l.recordSwitch(k),d({message:`
|
|
36
|
+
[last selected] ${k==null?void 0:k.quality}
|
|
37
|
+
`}),k}return l==null||l.recordSwitch($),$},vt=uA;var re=a=>new URL(a).hostname;import{assertNever as ab,assertNonNullable as sb,combine as kA,debounce as RA,ErrorCategory as nb,filter as ob,filterChanged as LA,isNonNullable as gu,map as ls,merge as ub,observableFrom as $A,once as MA,Subscription as CA,ValueSubject as Su,videoQualityToHeight as DA,videoSizeToQuality as OA}from"@vkontakte/videoplayer-shared";var Zm=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},be=a=>A(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!Zm(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return Zm(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as ns,isNullable as dA,assertNonNullable as gi}from"@vkontakte/videoplayer-shared";import{isNonNullable as eb,assertNonNullable as ss,now as lA}from"@vkontakte/videoplayer-shared";function ie(){return lA()}function hu(a){return ie()-a}function fu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function tb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Tr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;ss(c);let w=hu(c),H;if(w<b){H=b-w,setTimeout(g,H);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,B()},S=w=>(s=w,L),I=w=>(d=w,L),v=()=>(h="json",L),T=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},y=w=>(p=w,L),B=()=>{c=ie(),n=new i,n.open("get",a);let w=0,H,W=0,k=()=>(ss(c),Math.max(c,Math.max(H||0,W||0)));if(s&&n.addEventListener("progress",x=>{let N=ie();s.updateChunk&&x.loaded>w&&(s.updateChunk(k(),x.loaded-w),w=x.loaded,H=N)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;ss(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let N=n.response.byteLength-w;N&&s.updateChunk&&s.updateChunk(k(),N)}n.responseType==="json"&&!Object.values(n.response).length?T():(d&&d(),e(n.response))}else T()}),n.addEventListener("error",()=>{T()}),p){let x=()=>{ss(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(W=ie(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),L},L={withBitrateReporting:S,withParallel:y,withJSONResponse:v,withRetryCount:w=>(l=w,L),withRetryInterval:(w,H)=>(eb(w)&&(b=w),eb(H)&&(f=H),L),withTimeout:w=>(o=w,L),withFinally:I,send:B,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return L}var mi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var bi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ie(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ie()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Tr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ie()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ie();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var os=1e4,mu=3;var pA=6e4,hA=10,fA=1,mA=500,Si=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new mi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=fu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=fu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||ns(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{tb(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new bi(mu,os,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let T=s&&(!c||c===this.rep);return T||t("Not running!"),T},p=(T,y,B)=>{u&&u.abort(),u=Tr(this.urlResolver.resolve(T,!1),y,B,()=>this._retryCallback()).withTimeout(os).withBitrateReporting(this.bitrateSwitcher).withRetryCount(mu).withFinally(()=>{u=null}).send()},h=(T,y,B)=>{gi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),y,B,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=T=>{let y=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${y}=>${T}`),r.playbackRate=T)},b=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let B=ie()-1e4,D=0;for(let O=0;O<this.bufferStates.length;O++){let U=this.bufferStates[O];T=Math.min(T,U.buf),U.ts<B&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${T} drop=${D} jitter=${this.sourceJitter}`);let $=T-fA;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?f(1.15):$>1?f(1.1):$>.3?f(1.05):f(1)}},S=T=>{let y,B=()=>y&&y.start?y.start.length:0,D=x=>y.start[x]/1e3,$=x=>y.dur[x]/1e3,O=x=>y.fragIndex+x,U=(x,N)=>({chunkIdx:O(x),startTS:D(x),dur:$(x),discontinuity:N}),L=()=>{let x=0;if(y&&y.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Q=N;this.sourceJitter>1&&(Q+=this.sourceJitter-1);let Z=y.dur.length-1;for(;Z>=0&&(Q-=y.dur[Z],!(Q<=0));--Z);x=Math.min(Z,y.dur.length-1-G),x=Math.max(x,0)}return U(x,!0)},w=x=>{let N=B();if(!(N<=0)){if(ns(x)){for(let G=0;G<N;G++)if(D(G)>x)return U(G)}return L()}},H=x=>{let N=B(),G=x?x.chunkIdx+1:0,Q=G-y.fragIndex;if(!(N<=0)){if(!x||Q<0||Q-N>hA)return t(`Resync: offset=${Q} bChunks=${N} chunk=`+JSON.stringify(x)),L();if(!(Q>=N))return U(G-y.fragIndex,!1)}},W=(x,N,G)=>{l&&l.abort(),l=Tr(this.urlResolver.resolve(x,!0,this.lowLatency),N,G,()=>this._retryCallback()).withTimeout(os).withRetryCount(mu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(x,N)=>{W(T,G=>{if(!d())return;y=G;let Q=!!y.lowLatency;Q!==this.lowLatency&&b(Q);let Z=0;for(let F=0;F<y.dur.length;++F)Z+=y.dur[F];Z>0&&(gi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Z/y.dur.length)),i({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,x(w(N))},()=>this._handleNetworkError())},nextChunk:H}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),gi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{let{videoElement:y,logger:B}=this.params,D=S(e.jidxUrl),$,O,U,L,w=0,H,W,k,x=()=>{H&&(clearTimeout(H),H=void 0);let V=Math.max(mA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ue=w+V,ve=ie(),Pe=Math.min(1e4,ue-ve);w=ve;let lt=()=>{l||d()&&D.seek(()=>{d()&&(w=ie(),N(),x())})};Pe>0?H=window.setTimeout(()=>{this.paused?x():lt()},Pe):lt()},N=()=>{let V;for(;V=D.nextChunk(L);)L=V,Kt(V);let ue=D.nextChunk(U);if(ue){if(U&&ue.discontinuity){B("Detected discontinuity; restarting playback"),this.paused?x():(I(),this._initPlayerWith(e));return}F(ue)}else x()},G=(V,ue)=>{if(!d()||!this.sourceBuffer)return;let ve,Pe,lt,Jt=ct=>{window.setTimeout(()=>{d()&&G(V,ue)},ct)};if(this.sourceBuffer.updating)B("Source buffer is updating; delaying appendBuffer"),Jt(100);else{let ct=ie(),xt=y.currentTime;!this.paused&&y.buffered.length>1&&W===xt&&ct-k>500&&(B("Stall suspected; trying to fix"),this._fixupStall()),W!==xt&&(W=xt,k=ct);let Xt=this._getBufferSizeSec();if(Xt>30)B(`Buffered ${Xt} seconds; delaying appendBuffer`),Jt(2e3);else try{this.sourceBuffer.appendBuffer(V),this.videoPlayStarted?(this.bufferStates.push({ts:ct,buf:Xt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ue&&ue()}catch(Or){if(Or.name==="QuotaExceededError")B("QuotaExceededError; delaying appendBuffer"),lt=this.sourceBuffer.buffered.length,lt!==0&&(ve=this.sourceBuffer.buffered.start(0),Pe=xt,Pe-ve>4&&this.sourceBuffer.remove(ve,Pe-3)),Jt(1e3);else throw Or}}},Q=()=>{O&&$&&(B([`Appending chunk, sz=${O.byteLength}:`,JSON.stringify(U)]),G(O,function(){O=null,N()}))},Z=V=>e.fragUrlTemplate.replace("%%id%%",V.chunkIdx),F=V=>{d()&&h(Z(V),(ue,ve)=>{if(d()){if(ve/=1e3,O=ue,U=V,n=V.startTS,ve){let Pe=Math.min(10,V.dur/ve);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}Q()}},()=>this._handleNetworkError())},Kt=V=>{d()&&(gi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Z(V),!1)))},ut=V=>{d()&&(e.cachedHeader=V,G(V,()=>{$=!0,Q()}))};s=!0,D.seek(V=>{if(d()){if(w=ie(),!V){x();return}L=V,!dA(T)||V.startTS>T?F(V):(U=V,N())}},T),e.cachedHeader?ut(e.cachedHeader):p(e.headerUrl,ut,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),ns(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,gi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return ns(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=ie();if(this.chunkRateEstimator.addInterval(p,f,h)){let 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&&hu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ie();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Tr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(os).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;be(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},pA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as bA,filter as rb,fromEvent as gA,interval as SA,isHigher as vA,isInvariantQuality as yA,isLower as TA,merge as IA,Subject as ib,Subscription as EA}from"@vkontakte/videoplayer-shared";var bu=class{constructor(){this.onDroopedVideoFramesLimit$=new ib;this.subscription=new EA;this.playing=!1;this.tracks=[];this.forceChecker$=new ib;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&&!yA(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&&vA(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(gA(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=SA(this.droppedFramesChecker.checkTime).pipe(rb(()=>this.playing),rb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(bA(this.droppedFramesChecker.checkTime)),r=IA(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])=>TA(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},us=bu;import{map as xA,Observable as PA}from"@vkontakte/videoplayer-shared";import{fromEvent as wA}from"@vkontakte/videoplayer-shared";var vi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var AA=(a,e)=>new PA(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||vi()))},R(R({},r),e));i.observe(a);let s=wA(document,"visibilitychange").pipe(xA(n=>!document.hidden||vi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Me=AA;var BA=["paused","playing","ready"],VA=["paused","playing","ready"],yi=class{constructor(e){this.subscription=new CA;this.videoState=new M("stopped");this.representations$=new Su([]);this.textTracksManager=new Le;this.droppedFramesManager=new us;this.maxSeekBackTime$=new Su(1/0);this.zeroTime$=new Su(void 0);this.liveOffset=new et;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:nb.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=gt(u.name))!=null?r:OA(u.video),d=u.bitrate/1e3,p=R({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),gu(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(VA.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&BA.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ae(this.params.source.url,u))}return;default:return ab(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:nb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};ub(this.videoState.stateChangeStarted$.pipe(ls(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ls(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=me(this.video);this.subscription.add(this.representations$.pipe(ls(i=>i.map(({track:s})=>s)),ob(i=>!!i.length),MA()).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(LA(),ls(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(kA({zeroTime:this.zeroTime$.pipe(ob(gu)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(We(this.video,this.params.desiredState.isLooped,t)).add(fe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Re(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Me(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&DA(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 ab(i.to)}},t)).add(ub(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,$A(["init"])).pipe(RA(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),he(this.video)}createLiveDashPlayer(){let e=new Si({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&&gu(t)?t:vt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;sb(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;sb(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ae(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var lb=yi;var rt=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as nR,assertNonNullable as oR,debounce as uR,ErrorCategory as Yu,filter as Bg,filterChanged as Wu,fromEvent as lR,isLowerOrEqual as Vg,isNonNullable as cR,isInvariantQuality as dR,map as _g,merge as Ds,observableFrom as pR,observeElementSize as hR,once as Ng,Subscription as fR,ValueSubject as mR}from"@vkontakte/videoplayer-shared";var cs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Ir=class extends cs{constructor(){super(),this.listeners||cs.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Ti=class{constructor(){Object.defineProperty(this,"signal",{value:new Ir,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ti.prototype[Symbol.toStringTag]="AbortController",Ir.prototype[Symbol.toStringTag]="AbortSignal");function ds(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function vu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!ds({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Ii=ds({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),cb=Ii?vu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,it=Ii?cb.fetch:window.fetch,vO=Ii?cb.Request:window.Request,at=Ii?Ti:window.AbortController,yO=Ii?Ir:window.AbortSignal;var Eb=Ge(hi(),1);var st=()=>window.ManagedMediaSource||window.MediaSource,ps=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},db=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},pb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Ts,clientChecker as ys}from"@vkontakte/videoplayer-shared";var Ce=document.createElement("video"),FA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',qA='video/mp4; codecs="hev1.1.6.L93.B0"',xb='video/webm; codecs="vp09.00.10.08"',Pb='video/webm; codecs="av01.0.00M.08"',UA='audio/mp4; codecs="mp4a.40.2"',HA='audio/webm; codecs="opus"',hb,fb,_t={mms:ps(),mse:db(),hls:!!((hb=Ce.canPlayType)!=null&&hb.call(Ce,"application/x-mpegurl")||(fb=Ce.canPlayType)!=null&&fb.call(Ce,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},mb,bb,ge={mp4:!!((mb=Ce.canPlayType)!=null&&mb.call(Ce,"video/mp4")),webm:!!((bb=Ce.canPlayType)!=null&&bb.call(Ce,"video/webm")),cmaf:!0},fs,gb,ms,Sb,bs,vb,gs,yb,Ss,Tb,vs,Ib,Se={h264:!!((gb=(fs=st())==null?void 0:fs.isTypeSupported)!=null&&gb.call(fs,FA)),h265:!!((Sb=(ms=st())==null?void 0:ms.isTypeSupported)!=null&&Sb.call(ms,qA)),vp9:!!((vb=(bs=st())==null?void 0:bs.isTypeSupported)!=null&&vb.call(bs,xb)),av1:!!((yb=(gs=st())==null?void 0:gs.isTypeSupported)!=null&&yb.call(gs,Pb)),aac:!!((Tb=(Ss=st())==null?void 0:Ss.isTypeSupported)!=null&&Tb.call(Ss,UA)),opus:!!((Ib=(vs=st())==null?void 0:vs.isTypeSupported)!=null&&Ib.call(vs,HA))},Er=(Se.h264||Se.h265)&&Se.aac,Nt,jA=()=>A(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(q(R({},a),{video:q(R({},a.video),{contentType:Pb})})),window.navigator.mediaCapabilities.decodingInfo(q(R({},a),{video:q(R({},a.video),{contentType:xb})}))]);Nt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{jA()}catch(a){console.error(a)}var xr=_t.hls&&ge.mp4,wb=()=>Object.keys(Se).filter(a=>Se[a]),Ab=(a,e=!1,t=!1)=>{let r=_t.mse||_t.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&ge.mp4&&Er;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&&Er||ge.webm&&(Se.vp9||Se.av1)&&(Se.opus||Se.aac));case"DASH_LIVE":return _t.mse&&ge.mp4&&Er;case"DASH_LIVE_CMAF":return r&&ge.mp4&&Er&&ge.cmaf;case"DASH_ONDEMAND":return r&&ge.mp4&&Er;case"HLS":case"HLS_ONDEMAND":return xr||e&&_t.mse&&ge.mp4&&Er;case"HLS_LIVE":case"HLS_LIVE_CMAF":return xr;case"MPEG":return ge.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return _t.webrtc&&_t.ws&&Se.h264&&(ge.mp4||ge.webm);default:return Ts(i)}})},hs=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Nt?Nt[t].smooth?[t,e]:Nt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Nt?Nt[t].powerEfficient?[t,e]:Nt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ts(a)}return[e,t]},kb=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...hs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ys.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...hs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...hs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...hs(a),...i,"HLS","HLS_ONDEMAND"];default:Ts(e)}return xr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Rb=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=ys.isMac&&ys.isSafari;if(ys.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Ts(a)}else xr&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},yu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Lb=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,Eb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as Ei}from"@vkontakte/videoplayer-shared";var $b=a=>{if(!a)return{id:"EmptyResponse",category:Ei.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Ei.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ei.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ei.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ei.PARSER,message:"Response is valid XML, but parser failed"}};var xi=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};import{abortable as Hu,assertNonNullable as Qt,combine as ks,ErrorCategory as Tt,filter as Rs,filterChanged as Rg,fromEvent as $r,interval as ju,isNonNullable as Lg,map as Gu,merge as Mr,Subject as $g,Subscription as Mg,tap as Zk,throttle as eR,clientChecker as tR,ValueSubject as oe}from"@vkontakte/videoplayer-shared";var Lr=Ge(hi(),1);var GA=(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)},YA=a=>window.clearTimeout(a),Mb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Tu=Mb?GA:window.requestIdleCallback,OO=Mb?YA:window.cancelIdleCallback;var Ig=Ge(ts(),1);import{assertNever as WA,ErrorCategory as Cb,clientChecker as Iu,Subject as Db}from"@vkontakte/videoplayer-shared";var QA=16,Ob=!1;try{Ob=Iu.isSafari&&!!Iu.macVersion&&Iu.macVersion<=QA}catch(a){console.error(a)}var Eu=class{constructor(e){this.bufferFull$=new Db;this.error$=new Db;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:Cb.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return A(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return A(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return A(this,null,function*(){return new Promise(t=>{let r;Ob&&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:Cb.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:WA(t)}}},Bb=Eu;var xu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Rr,assertNonNullable as ze,ErrorCategory as Gt,fromEvent as Vu,getExponentialDelay as _u,isNonNullable as Tg,isNullable as qe,once as Gk,Subject as Yk,Subscription as Wk,ValueSubject as Wi}from"@vkontakte/videoplayer-shared";var j=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Pr=class extends j{};var Pi=class extends j{};var wi=class extends j{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var Ai=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ki=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var J=class extends j{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ft=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Li=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mi=class extends J{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ci=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Di=class extends J{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Oi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Vi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ni=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Fi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qi=class extends J{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Ui=class extends J{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Hi=class extends J{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var KA={ftyp:wi,moov:Ai,moof:ki,mdat:Ri,sidx:Ft,trak:Li,mdia:Oi,mfhd:Ni,tkhd:Bi,traf:Fi,tfhd:qi,tfdt:Ui,trun:Hi,minf:Vi,sv3d:$i,st3d:Mi,prhd:Ci,proj:_i,equi:Di,uuid:Pi,unknown:Pr},qt=class a{constructor(e={}){this.options=R({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=KA[e];return r?new r(t,new a):new Pr(t,new a)}};var wr=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 XA=new TextDecoder("ascii"),ZA=a=>XA.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",ek=a=>{let e=new Ft(a,new qt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},tk=(a,e)=>{let r=new qt().parse(a),i=new wr(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},rk=(a,e)=>{let r=new qt().parse(a),s=new wr(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},ik=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new qt().parse(a),i=new wr(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},Vb={validateData:ZA,parseInit:ik,getIndexRange:()=>{},parseSegments:ek,parseFeedableSegmentChunk:tk,getSegmentEndTime:rk};import{assertNonNullable as wu,isNonNullable as qb,isNullable as sk}from"@vkontakte/videoplayer-shared";import{assertNever as ak}from"@vkontakte/videoplayer-shared";var _b={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"}},Nb=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=ji(a,t),i=r in _b,s=i?_b[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=ji(u),d=l*je(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ji=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*je(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*je(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*je(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Fe=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ji(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:ak(e)}},Ut=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Nb(r);if(!e(i))return;i.type==="master"&&Ut(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Fb=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Nb(a);return Ut(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Fe(o,n):s===17026?t=Fe(o,n):s===17029&&(r=Fe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Ub=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],nk=[231,22612,22743,167,171,163,160,175],ok=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Ut(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Fe(f,h);l=ji(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=Fe(f,h):p===17545?i=Fe(f,h):p===21420&&l===475249515?u=Fe(f,h):p===374648427?Ut(f,({tag:g,type:S,value:I})=>g===30321?(c=Fe(I,S)===1,!1):!0):s&&n&&Ub.includes(p)&&(o=!0),!o}),wu(e,"Failed to parse webm Segment start"),wu(t,"Failed to parse webm Segment end"),wu(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},uk=a=>{if(sk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},lk=(a,e)=>{let t=!1,r=!1,i=o=>qb(o.time)&&qb(o.position),s=[],n;return Ut(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Fe(l,u));break;case 183:break;case 241:n&&(n.position=Fe(l,u));break;default:t&&Ub.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},ck=a=>{let e=0,t=!1;try{Ut(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):nk.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Hb={validateData:Fb,parseInit:ok,getIndexRange:uk,parseSegments:lk,parseFeedableSegmentChunk:ck};var Ar=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Hb;case"mp4":return Vb}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Cu=Ge(dg(),1);var Mu=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as hg,isNullable as fg}from"@vkontakte/videoplayer-shared";var pg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var mg=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Ht=(a,e)=>{let t=a;t=(0,Cu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Cu.default)(t,n,(o,u)=>fg(s)?o:fg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},gg=(a,e)=>{var T,y,B,D,$,O,U,L,w,H,W,k,x,N,G,Q,Z,F,Kt,ut,V,ue,ve,Pe,lt,Jt,ct,xt,Xt,Or,ul,ll,cl,dl,pl,hl,fl,ml,bl,gl,Sl,vl,yl,Tl,Il,El,xl,Pl,wl,Al;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(B=(y=(T=s.querySelector("BaseURL"))==null?void 0:T.textContent)==null?void 0:y.trim())!=null?B:"",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=mg(h);else if(f){let le=mg(f);hg(le)&&(p=le)}else g&&(p=parseInt(g,10));let S=0,I=($=(D=s.getAttribute("profiles"))==null?void 0:D.split(","))!=null?$:[];for(let le of u){let kS=(O=le.getAttribute("id"))!=null?O:"id"+(S++).toString(10),Br=(U=le.getAttribute("mimeType"))!=null?U:"",Ks=(L=le.getAttribute("codecs"))!=null?L:"",Js=(w=le.getAttribute("contentType"))!=null?w:Br==null?void 0:Br.split("/")[0],RS=(W=(H=le.getAttribute("profiles"))==null?void 0:H.split(","))!=null?W:[],LS=(k=le.getAttribute("lang"))!=null?k:void 0,$S=(G=(N=(x=le.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:N.trim())!=null?G:void 0,MS=le.querySelectorAll("Representation"),CS=le.querySelector("SegmentTemplate"),DS=(Z=(Q=le.querySelector("Role"))==null?void 0:Q.getAttribute("value"))!=null?Z:void 0,Vr=Js,ee={id:kS,language:LS,isDefault:DS==="main",label:$S,codecs:Ks,hdr:Vr==="video"&&Mu(Ks),mime:Br,representations:[]};for(let X of MS){let OS=(F=X.getAttribute("lang"))!=null?F:void 0,BS=(Kt=X.getAttribute("label"))!=null?Kt:void 0,VS=(ue=(V=(ut=X.querySelector("BaseURL"))==null?void 0:ut.textContent)==null?void 0:V.trim())!=null?ue:"",Xs=new URL(VS||o,e).toString(),Zt=(ve=X.getAttribute("mimeType"))!=null?ve:Br,ha=(lt=(Pe=X.getAttribute("codecs"))!=null?Pe:Ks)!=null?lt:"",Zs;if(Js==="text"){let Pt=X.getAttribute("id")||"",en=Pt.includes("_auto");Zs={id:Pt,isAuto:en,kind:"text",url:Xs}}else{let Pt=(ct=(Jt=X.getAttribute("contentType"))!=null?Jt:Zt==null?void 0:Zt.split("/")[0])!=null?ct:Js,en=(Xt=(xt=le.getAttribute("profiles"))==null?void 0:xt.split(","))!=null?Xt:[],_S=parseInt((Or=X.getAttribute("width"))!=null?Or:"",10),kl=parseInt((ul=X.getAttribute("height"))!=null?ul:"",10),Rl=parseInt((ll=X.getAttribute("bandwidth"))!=null?ll:"",10)/1e3,Ll=(cl=X.getAttribute("frameRate"))!=null?cl:"",NS=(dl=X.getAttribute("quality"))!=null?dl:void 0,FS=Ll?pg(Ll):void 0,qS=(pl=X.getAttribute("id"))!=null?pl:"id"+(S++).toString(10),US=Pt==="video"?`${kl}p`:Pt==="audio"?`${Rl}Kbps`:ha,HS=`${qS}@${US}`,jS=[...I,...RS,...en],tn,GS=X.querySelector("SegmentBase"),wt=(hl=X.querySelector("SegmentTemplate"))!=null?hl:CS;if(GS){let At=(ml=(fl=X.querySelector("SegmentBase Initialization"))==null?void 0:fl.getAttribute("range"))!=null?ml:"",[kt,an]=At.split("-").map(er=>parseInt(er,10)),dt={from:kt,to:an},_r=(bl=X.querySelector("SegmentBase"))==null?void 0:bl.getAttribute("indexRange"),[sn,fa]=_r?_r.split("-").map(er=>parseInt(er,10)):[],Nr=_r?{from:sn,to:fa}:void 0;tn={type:"byteRange",url:Xs,initRange:dt,indexRange:Nr}}else if(wt){let At={representationId:(gl=X.getAttribute("id"))!=null?gl:void 0,bandwidth:(Sl=X.getAttribute("bandwidth"))!=null?Sl:void 0},kt=parseInt((vl=wt.getAttribute("timescale"))!=null?vl:"",10),an=(yl=wt.getAttribute("initialization"))!=null?yl:"",dt=wt.getAttribute("media"),_r=(Il=parseInt((Tl=wt.getAttribute("startNumber"))!=null?Tl:"",10))!=null?Il:1,sn=Ht(an,At);if(!dt)throw new ReferenceError("No media attribute in SegmentTemplate");let fa=(El=wt.querySelectorAll("SegmentTimeline S"))!=null?El:[],Nr=[],er=0,nn="",on=0;if(fa.length){let ma=_r,Oe=0;for(let tr of fa){let He=parseInt((xl=tr.getAttribute("d"))!=null?xl:"",10),Rt=parseInt((Pl=tr.getAttribute("r"))!=null?Pl:"",10)||0,ba=parseInt((wl=tr.getAttribute("t"))!=null?wl:"",10);Oe=Number.isFinite(ba)?ba:Oe;let un=He/kt*1e3,ln=Oe/kt*1e3;for(let ga=0;ga<Rt+1;ga++){let WS=Ht(dt,q(R({},At),{segmentNumber:ma.toString(10),segmentTime:(Oe+ga*He).toString(10)})),$l=(ln!=null?ln:0)+ga*un,QS=$l+un;ma++,Nr.push({time:{from:$l,to:QS},url:WS})}Oe+=(Rt+1)*He,er+=(Rt+1)*un}on=Oe/kt*1e3,nn=Ht(dt,q(R({},At),{segmentNumber:ma.toString(10),segmentTime:Oe.toString(10)}))}else if(hg(p)){let Oe=parseInt((Al=wt.getAttribute("duration"))!=null?Al:"",10)/kt*1e3,tr=Math.ceil(p/Oe),He=0;for(let Rt=1;Rt<tr;Rt++){let ba=Ht(dt,q(R({},At),{segmentNumber:Rt.toString(10),segmentTime:He.toString(10)}));Nr.push({time:{from:He,to:He+Oe},url:ba}),He+=Oe}on=He,nn=Ht(dt,q(R({},At),{segmentNumber:tr.toString(10),segmentTime:He.toString(10)}))}let YS={time:{from:on,to:1/0},url:nn};tn={type:"template",baseUrl:Xs,segmentTemplateUrl:dt,initUrl:sn,totalSegmentsDurationMs:er,segments:Nr,nextSegmentBeyondManifest:YS,timescale:kt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pt||!Zt)continue;let rn={video:"video",audio:"audio",text:"text"}[Pt];if(!rn)continue;Vr||(Vr=rn),Zs={id:HS,kind:rn,segmentReference:tn,profiles:jS,duration:p,bitrate:Rl,mime:Zt,codecs:ha,width:_S,height:kl,fps:FS,quality:NS}}ee.language||(ee.language=OS),ee.label||(ee.label=BS),ee.mime||(ee.mime=Zt),ee.codecs||(ee.codecs=ha),ee.hdr||(ee.hdr=Vr==="video"&&Mu(ha)),ee.representations.push(Zs)}Vr&&i[Vr].push(ee)}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,streams:i}};var Gi=Ge(hi(),1);import{videoSizeToQuality as jk}from"@vkontakte/videoplayer-shared";var Sg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?gt(s):void 0)!=null?o:jk({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},vg=({id:a,bitrate:e})=>({id:a,bitrate:e}),Is=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Gi.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Gi.default)(t,-1)},yg=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Ou=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Gi.default)(r.split("."),0),isDefault:i}),Bu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Gi.default)(i.split("."),0)}),Es=a=>"url"in a,jt=a=>a.type==="template",Yi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Qi=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new Wi(0);this.onLastSegment$=new Wi(!1);this.fullyBuffered$=new Wi(!1);this.playingRepresentation$=new Wi(void 0);this.playingRepresentationInit$=new Wi(void 0);this.error$=new Yk;this.gaps=[];this.subscription=new Wk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new at;this.destroyAbortController=new at;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Rr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){let t=this.representations.get(e);ze(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Bb(this.sourceBuffer),this.subscription.add(Vu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Vu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Gt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,xu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=rt(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,l<c)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ze(r,"No init buffer for starting representation"),ze(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=Rr(this.destroyAbortController.signal,function(e,t=!1){return te(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);ze(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(qe(s)||qe(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),ze(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Tg(n)&&(this.isLive||(i.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Rr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!jt(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);ze(i);let s=this.segments.get(r);ze(s,"No segments for starting representation");let n=this.initData.get(r);if(ze(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new at,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(qe(e)||qe(this.downloadingRepresentationId)||qe(this.playingRepresentationId)||qe(this.sourceBuffer)||!qe(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(ze(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=rt(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&xu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=rt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let p=(0,Lr.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&rt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Lr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;Tg(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!jt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>q(R({},p),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Lr.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(c)>=Math.floor(p.time.from)&&Math.floor(c)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(d+1);this.segments.set(o.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ze(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!jt(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=Ht(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&I&&this.sourceBuffer&&!xi(this.sourceBuffer.buffered,r))&&g&&I});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return A(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return A(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Rr(o,function(){return te(this,null,function*(){let c=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=Ar(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Yi(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return A(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Rr(n,function(){return te(this,null,function*(){let u=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Vu(window,"online").pipe(Gk()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Yi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(jt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Lr.default)(e,0).byte.from,to:(0,Lr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!jt(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return A(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Ar(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,l=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:l;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,g=p?d.byte.to-r:e.byteLength,S=b<i,I=g<=i;if(d.status==="downloading"&&S&&I){d.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+b,h);this.sourceBufferTaskQueue.append(v,s).then(T=>T&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(c.loadedBytes=Math.min(h,i-b),c.loadedBytes>c.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),T=c.loadedBytes===h?v:Ar(o.mime).parseFeedableSegmentChunk(v);T!=null&&T.byteLength&&(d.status="partially_fed",c.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,s).then(y=>{if(s.aborted)n();else if(y)c.fedBytes+=T.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return A(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,f=d<i,b=p<=i;if(f){if(c.status==="downloading"&&b){c.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(g,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?g:Ar(u.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):n())}}}})}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Es(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Tu(()=>(0,Ig.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return A(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Rr(this.destroyAbortController.signal,function(){return te(this,null,function*(){let o=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ar(e.mime),i)).then(o=>A(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&jt(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Gt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return A(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return A(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return A(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||qe(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(u.time),i=n(i);let l=Es(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}pruneBufferOld(e,t,r=!1){return A(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||qe(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=l=>{var d;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=Es(l)?(d=l.size)!=null?d:0:l.byte.to-l.byte.from;i+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){i=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let c of l){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let c=this.sourceBuffer.buffered.start(l)*1e3,d=this.sourceBuffer.buffered.end(l)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){i=0,s=1/0,n=-1/0;let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+l&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Tu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Gt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(qe(this.sourceBuffer)||qe(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=1;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var zi=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Eg=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Ki,assertNever as xg,fromEvent as Pg,merge as Qk,now as Nu,Subscription as zk,ValueSubject as Fu}from"@vkontakte/videoplayer-shared";var xs=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new Fu(void 0);this.lastConnectionReused$=new Fu(void 0);this.lastRequestFirstBytes$=new Fu(void 0);this.abortAllController=new at;this.subscription=new zk;this.fetchManifest=Ki(this.abortAllController.signal,function(e){return te(this,null,function*(){let t=e;this.requestQuic&&(t=zi(t));let r=yield it(t,{signal:this.abortAllController.signal}).catch(Ji);return r?(this.onHeadersReceived(r.headers),r.text()):null})}.bind(this));this.fetch=Ki(this.abortAllController.signal,function(l){return te(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var O,U;let c=e,d=new Headers;if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(c,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),c=L.toString();break}default:xg(t)}this.requestQuic&&(c=zi(c));let p=this.abortAllController.signal,h;if(n){let L=new at;if(h=Qk(Pg(this.abortAllController.signal,"abort"),Pg(n,"abort")).subscribe(()=>{try{L.abort()}catch(w){Ji(w)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(w){Ji(w)}p=L.signal}let f=Nu(),b=yield it(c,{priority:s,headers:d,signal:p}).catch(Ji),g=Nu();if(!b)return h==null||h.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(g-f),!b.ok||!b.body)return h==null||h.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!i&&!o)return h==null||h.unsubscribe(),b.arrayBuffer();let[S,I]=b.body.tee(),v=S.getReader();o&&((U=this.throughputEstimator)==null||U.trackStream(I,u));let T=0,y=new Uint8Array(0),B=!1,D=L=>{h==null||h.unsubscribe(),B=!0,Ji(L)},$=Ki(p,function(H){return te(this,arguments,function*({done:L,value:w}){if(T===0&&this.lastRequestFirstBytes$.next(Nu()-f),p.aborted){h==null||h.unsubscribe();return}if(!L&&w){let W=new Uint8Array(y.length+w.length);W.set(y),W.set(w,y.length),y=W,T+=w.byteLength,i==null||i(new DataView(y.buffer),T),yield v==null?void 0:v.read().then($,D)}})}.bind(this));return yield v==null?void 0:v.read().then($,D),h==null||h.unsubscribe(),B?null:y.buffer})}.bind(this));this.fetchByteRangeRepresentation=Ki(this.abortAllController.signal,function(e,t,r){return te(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(S=e.indexRange)!=null?S:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let 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=Ki(this.abortAllController.signal,function(e,t){return te(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>q(R({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){let{type:t,reused:r}=Eg(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return A(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:xg(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Ji=a=>{if(!Yi(a))throw a};var Yt=(a,e,t)=>t*e+(1-t)*a,qu=(a,e)=>a.reduce((t,r)=>t+r,0)/e,wg=(a,e,t,r)=>{let i=0,s=t,n=qu(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as Kk,ValueSubject as Ag}from"@vkontakte/videoplayer-shared";var yt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Ag(e.initial),this.debounced$=new Ag(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ne(`raw_${t}`),this.smoothedSeries$=new ne(`smoothed_${t}`),this.reportedSeries$=new ne(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=je(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(Kk(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Ps=class extends yt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Yt(this.slow,e,this.params.emaAlphaSlow),this.fast=Yt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ws=class extends yt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=qu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Yt(this.emaSmoothed,e,this.params.emaAlpha);let r=wg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var As=class extends yt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Yt(this.smoothed,t,this.params.emaAlpha):t}};var Wt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Ps({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ws({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 As(R({initial:e,label:"liveEdgeDelay"},t))}};var Uu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var Cg=["timeupdate","progress","play","seeked","stalled","waiting"];var Ls=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Mg;this.representationSubscription=new Mg;this.state$=new M("none");this.currentVideoRepresentation$=new oe(void 0);this.currentVideoRepresentationInit$=new oe(void 0);this.currentAudioRepresentation$=new oe(void 0);this.currentVideoSegmentLength$=new oe(0);this.currentAudioSegmentLength$=new oe(0);this.error$=new $g;this.lastConnectionType$=new oe(void 0);this.lastConnectionReused$=new oe(void 0);this.lastRequestFirstBytes$=new oe(void 0);this.isLive$=new oe(!1);this.liveDuration$=new oe(0);this.liveAvailabilityStartTime$=new oe(void 0);this.bufferLength$=new oe(0);this.liveLoadBufferLength$=new oe(0);this.livePositionFromPlayer$=new oe(0);this.timeInWaiting=0;this.isActiveLowLatency$=new oe(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new $g;this.gapWatchdogActive=!1;this.destroyController=new at;this.initManifest=Hu(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var i;this.element=e,this.manifestUrlString=ae(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Tt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Hu(this.destroyController.signal,function(){return te(this,null,function*(){var s,n;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Tt.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t;try{t=gg(e!=null?e:"",this.manifestUrlString)}catch(o){let u=(s=$b(e))!=null?s:{id:"ManifestParsing",category:Tt.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(u)}if(!t)return null;let r=(o,u,l)=>{var c,d,p,h;return!!((d=(c=this.element)==null?void 0:c.canPlayType)!=null&&d.call(c,u)&&((h=(p=st())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${l}"`))||o==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((n=t.duration)!=null?n:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let o of["video","audio"]){let l=t.streams[o].filter(({mime:p,codecs:h})=>r(o,p,h)),c=new Set(l.map(({codecs:p})=>p)),d=Lb(c);if(d&&(i[o]=l.filter(({codecs:p})=>p.startsWith(d))),o==="video"){let p=this.tuning.preferHDR,h=i.video.some(b=>b.hdr),f=i.video.some(b=>!b.hdr);tR.isHDR&&p&&h?i.video=i.video.filter(b=>b.hdr):f&&(i.video=i.video.filter(b=>!b.hdr))}}return q(R({},t),{streams:i})})}.bind(this));this.initRepresentations=Hu(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var d;Qt(this.manifest),Qt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add($r(p,"error").pipe(Rs(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Tt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?pb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ps())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Qi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Lg(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Qi("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ju(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=eu(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Mr(...Cg.filter(p=>p!=="waiting").map(p=>$r(this.element,p))).pipe(Gu(p=>this.element?rt(this.element.buffered,this.element.currentTime*1e3):0),Rg(),Rs(p=>!!p),Zk(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Rg()).subscribe(h=>Uu(this.element,1))),this.representationSubscription.add(ks({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Rs(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(ks({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b,v=1;Math.abs(I)>g&&(v=1+Math.sign(I)*S),Uu(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let S=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(v=>{var T,y;return(y=(T=v.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?y:S}))-S}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(ks({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(eR(1e3)).subscribe(b=>A(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(Qt(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,S=eu(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,B=isFinite(h)?h:f,D=this.isActiveLowLatency$.getValue(),$=I<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLowLatency$.next(D&&$);let O="none";if(D?O="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&$?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(U=>U.proceedLowLatencyLive()),O="active_low_latency"):S!==0&&B<v?O="live_forward_buffering":B<v+y&&(O="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),O==="live_forward_buffering"||O==="live_with_target_offset"){let U=p-(v+T),L=this.normolizeLiveOffset(Math.trunc(S+U/g)),w=Math.abs(L-S),H;!h||w<=this.tuning.dashCmafLive.offsetCalculationError?H=S:L>0&&w>this.tuning.dashCmafLive.offsetCalculationError?H=L:H=0,this.manifestUrlString=ae(this.manifestUrlString,H,2)}O!=="none"&&O!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=Mr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Gu(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=Mr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Gu(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Mr(this.forceEnded$,ks({allBuffersFull:u,someBufferEnded:l}).pipe(Rs(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:Tt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Mr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let c=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{var h;return(h=p.duration)!=null?h:0})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&Lg(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")})}.bind(this));this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ju(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:Tt.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new xs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Wt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,R({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return A(this,null,function*(){var r,i,s,n;Qt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ae(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio))})}initBuffer(){Qt(this.element),this.state$.setState("running"),this.subscription.add(Mr(...Cg.map(e=>$r(this.element,e)),$r(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Tt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add($r(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add($r(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&xi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var r,i;if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset);else{let s=this.element.currentTime*1e3;(r=this.videoBufferManager)==null||r.maintain(s),(i=this.audioBufferManager)==null||i.maintain(s)}}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=ju(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:Tt.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return A(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u;Qt(this.element),Qt(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),xi(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3}stop(){var e,t,r;(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return A(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],i=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-i<=t&&n.to+i>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var $s=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ms=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/je(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=R({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*je(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Dg=`attribute vec2 a_vertex;
|
|
59
38
|
attribute vec2 a_texel;
|
|
60
39
|
|
|
61
40
|
varying vec2 v_texel;
|
|
@@ -66,7 +45,7 @@ void main(void) {
|
|
|
66
45
|
// save texel vector to pass to fragment shader
|
|
67
46
|
v_texel = a_texel;
|
|
68
47
|
}
|
|
69
|
-
`;var
|
|
48
|
+
`;var Og=`#ifdef GL_ES
|
|
70
49
|
precision highp float;
|
|
71
50
|
precision highp int;
|
|
72
51
|
#else
|
|
@@ -109,5 +88,5 @@ void main(void) {
|
|
|
109
88
|
// sample using new coordinates
|
|
110
89
|
gl_FragColor = texture2D(u_texture, tc);
|
|
111
90
|
}
|
|
112
|
-
`;var Os=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new Cs(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ds(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Ug,this.gl.VERTEX_SHADER),r=this.createShader(Hg,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Xt=class{constructor(e){this.subscription=new vR;this.videoState=new M("stopped");this.elementSize$=new yR(void 0);this.textTracksManager=new $e;this.droppedFramesManager=new cs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new bi;this.audioTrackSwitchHistory=new bi;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 dR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Os(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=he(e.container,e.tuning),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ms({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=be(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Qu.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(jg(l=>!!l.length),Wg()).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(jg(mR),Wg()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Yg(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ze(this.video,t.isLooped,i)),this.subscription.add(me(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(SR(this.video),this.elementSize$),s(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(pR(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Vu(h));let f=[];for(let b of h.representations){let g=wg(b);f.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(_u(p));let h=[];for(let f of p.representations){let b=Ag(f);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let f=kg(p,h);this.textTracksMap.set(f,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=l=>e.error$.next({id:"RepresentationSwitch",category:Qu.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(Bs(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$,fR(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let b=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,b).catch(n)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(zu()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(_u(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(zu()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Vu(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Yg(({to:l})=>l==="ready"),zu());this.subscription.add(Bs(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Bs(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Bs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,gR(["init"])).pipe(hR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var D,j,O,q,$,A,U,k,J,P,N,G,W,Z,Ae,Pt,dt,V,ee;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(D=e.videoTrack.getState())==null?void 0:D.id,n=[...this.videoTracksMap.keys()].find(({id:L})=>L===i),o=t.currentVideoTrack$.getValue(),u=((q=(O=e.videoStream.getState())!=null?O:n&&((j=this.videoTracksMap.get(n))==null?void 0:j.stream))!=null?q:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:L})=>L===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=st(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=($=e.audioStream.getState())!=null?$:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(A=[...this.audioStreamsMap.keys()].find(({id:L})=>L===(f==null?void 0:f.id)))!=null?A:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let L=ns(n,c,(U=this.audioStreamsMap.get(b))!=null?U:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(k=L==null?void 0:L.bitrate)!=null?k:-1/0)}else{let L=xs(n,c,(J=this.audioStreamsMap.get(b))!=null?J:[]);g=Math.max(g,(P=L==null?void 0:L.bitrate)!=null?P:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let L=ns(o,c,(N=this.audioStreamsMap.get(b))!=null?N:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(G=L==null?void 0:L.bitrate)!=null?G:-1/0)}else{let L=xs(o,c,(W=this.audioStreamsMap.get(b))!=null?W:[]);g=Math.max(g,(Z=L==null?void 0:L.bitrate)!=null?Z:-1/0)}}let S=yt(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:I}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(S=(Ae=c.filter(L=>!bR(L.quality)).sort((L,le)=>{var Be,Xe;return((Be=le.bitrate)!=null?Be:0)-((Xe=L.bitrate)!=null?Xe:0)}).filter(L=>Gg(L.quality,S.quality)&&Gg(L.quality,I))[0])!=null?Ae:S);let v=r?S!=null?S:n:n!=null?n:S,y;this.params.tuning.useSeparateAudioVideoABR?y=b&&nb(v,c,(Pt=this.audioStreamsMap.get(b))!=null?Pt:[],{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}):y=b&&xs(v,c,(dt=this.audioStreamsMap.get(b))!=null?dt:[]);let T=(V=this.videoTracksMap.get(v))==null?void 0:V.representation,B=y&&((ee=this.audioTracksMap.get(y))==null?void 0:ee.representation);if(T&&B)return[T,B];if(T&&!B&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ge(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:Qu.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),fe(this.video)}};var ta=class extends Xt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Qg,interval as TR,map as IR}from"@vkontakte/videoplayer-shared";var ra=class extends Xt{constructor(e){super(e),this.liveOffset=new it}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Qg({interval:TR(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(Qg({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(IR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var Kg=We(is(),1);import{assertNever as ia,assertNonNullable as zg,debounce as ER,ErrorCategory as Vs,filter as xR,isNonNullable as PR,isNullable as AR,map as _s,merge as wR,Observable as kR,observableFrom as RR,Subscription as LR,videoSizeToQuality as $R}from"@vkontakte/videoplayer-shared";var je={};var Dr=(a,e)=>new kR(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),aa=class{constructor(e){this.subscription=new LR;this.videoState=new M("initializing");this.textTracksManager=new $e;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:ia(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ia(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ia(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ia(e)}break;default:ia(t)}};this.video=he(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),fe(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Vs.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Kg.default)(import("hls.js").then(i=>{e||(je.Hls=i.default,je.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){zg(je.Hls,"hls.js not loaded"),this.hls=new je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){zg(je.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Vs.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=be(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(ze(this.video,e.isLooped,r)),this.subscription.add(me(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(Ce(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(_s(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Dr(this.hls,je.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Vs.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(Dr(this.hls,je.Events.MANIFEST_PARSED).pipe(_s(({levels:l})=>l.reduce((c,d)=>{var I,v;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(v=vt((I=d.attrs.QUALITY)!=null?I:""))!=null?v:$R({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(Dr(this.hls,je.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(Dr(this.hls,je.Events.LEVEL_LOADING).pipe(_s(({url:l})=>ie(l))),t.hostname$),s(Dr(this.hls,je.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(bt(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=Dr(this.hls,je.Events.LEVEL_SWITCHED).pipe(_s(({level:l})=>n(this.hls.levels[l])));o.pipe(xR(PR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(bt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(AR(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=wR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,RR(["init"])).pipe(ER(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return w(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield ge(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Vs.DOM,thrown:t})))||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0)}};var Jg="X-Playback-Duration",Ku=a=>w(void 0,null,function*(){var i;let e=yield nt(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Jg)?parseInt(e.headers.get(Jg),10):void 0});import{assertNever as VR,combine as _R,debounce as NR,ErrorCategory as Fs,filter as FR,filterChanged as qR,isNonNullable as Zg,isNullable as qs,map as eS,merge as UR,observableFrom as HR,Subscription as jR,ValueSubject as Zu,VideoQuality as GR}from"@vkontakte/videoplayer-shared";var Xu=We(go(),1);import{videoSizeToQuality as MR,getExponentialDelay as CR}from"@vkontakte/videoplayer-shared";var DR=a=>{let e=null;if(a.QUALITY&&(e=vt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=MR({width:t,height:r})}return e!=null?e:null},OR=(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,Xu.default)(l[1].split(",").map(I=>I.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=DR(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[I,v]=d.RESOLUTION.split("x").map(y=>parseInt(y,10));I&&v&&(g={width:I,height:v})}let S=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:S,bandwidth:f,size:g,fps:b})}if(c){let d=(0,Xu.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}},BR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Ju=0,Xg=(r,...i)=>w(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield nt(a)).text();Ju+=1;try{let{qualityManifests:o,textTracks:u}=OR(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(Ju<=t.manifestRetryMaxCount)return yield BR(CR(Ju-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Xg(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Ns=Xg;var sa=class{constructor(e){this.subscription=new jR;this.videoState=new M("stopped");this.textTracksManager=new $e;this.manifests$=new Zu([]);this.liveOffset=new it;this.manifestStartTime$=new Zu(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 VR(t)}};var t;this.params=e,this.video=he(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:GR.INVARIANT,url:this.params.source.url},Ns(se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Fs.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Fs.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.maxSeekBackTime$=new Zu((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:Fs.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=be(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(me(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(Ce(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(qR(),eS(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Zg(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ie(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(_R({startTime:this.manifestStartTime$.pipe(FR(Zg)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(eS(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=UR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,HR(["init"])).pipe(NR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),fe(this.video)}prepare(){var o,u;let e=this.selectManifest();if(qs(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=se(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Ku(n).then(l=>{var c;if(!qs(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(qs(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();Ku(b).then(g=>{qs(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){ge(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Fs.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as YR,debounce as WR,ErrorCategory as el,fromEvent as tl,isNonNullable as QR,isNullable as zR,map as tS,merge as rS,observableFrom as iS,Subscription as KR,ValueSubject as JR,VideoQuality as XR,clientChecker as ZR}from"@vkontakte/videoplayer-shared";var na=class{constructor(e){this.subscription=new KR;this.videoState=new M("stopped");this.textTracksManager=new $e;this.manifests$=new JR([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let 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 YR(t)}};this.params=e,this.video=he(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:XR.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ns(se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:el.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:el.WTF,message:"HlsProvider internal logic error",thrown:o})},i=be(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(tS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,r)),this.subscription.add(me(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&&QR(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(f=>f.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ie(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(tS(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)),!ZR.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(rS(tl(o,"addtrack"),tl(o,"removetrack"),tl(o,"change"),iS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=rS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,iS(["init"])).pipe(WR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),fe(this.video)}prepare(){var s,n;let e=this.selectManifest();if(zR(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(){ge(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:el.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as eL,assertNonNullable as aS,debounce as tL,ErrorCategory as sS,isHigher as rL,isHigherOrEqual as iL,isInvariantQuality as nS,isLowerOrEqual as aL,isNonNullable as sL,merge as nL,observableFrom as oL,Subscription as uL,map as lL}from"@vkontakte/videoplayer-shared";var oa=class{constructor(e){this.subscription=new uL;this.videoState=new M("stopped");this.trackUrls={};this.textTracksManager=new $e;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 eL(e)}};this.params=e,this.video=he(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:sS.WTF,message:"MpegProvider internal logic error",thrown:o})},i=be(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(lL(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,r)),this.subscription.add(me(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(Ce(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&&sL(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=nL(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,oL(["init"])).pipe(tL(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),fe(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;aS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];aS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ji(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ie(t))}playIfAllowed(){ge(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:sS.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=>!nS(d.track.quality)&&aL(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&&iL(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!nS(h.track.quality)&&rL(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=yt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as uS,debounce as hL,merge as lS,observableFrom as fL,Subscription as mL,map as cS,ValueSubject as bL,ErrorCategory as il,VideoQuality as gL}from"@vkontakte/videoplayer-shared";import{ErrorCategory as cL}from"@vkontakte/videoplayer-shared";var oS=["stun:videostun.mycdn.me:80"],dL=1e3,pL=3,rl=()=>null,Us=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=rl;this.externalStopCallback=rl;this.externalErrorCallback=rl;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return w(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return w(this,null,function*(){try{let e={iceServers:[{urls:oS}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return w(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return w(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:cL.WTF,message:e.message})}onPeerConnectionStream(e){return w(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return w(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),dL)}normalizeOptions(e={}){let t={stunServerList:oS,maxRetryNumber:pL,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ua=class{constructor(e){this.videoState=new M("stopped");this.maxSeekBackTime$=new bL(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 uS(e)}};this.subscription=new mL,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=he(e.container,e.tuning),this.liveStreamClient=new Us(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),fe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:il.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};lS(this.videoState.stateChangeStarted$.pipe(cS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(cS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=be(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(Ce(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(me(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 uS(n.to)}},r)).add(lS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,fL(["init"])).pipe(hL(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:gL.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:il.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ge(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:il.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var la=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as pa,assertNonNullable as Et,ErrorCategory as js,filter as xL,isNonNullable as bS,isNullable as PL,map as AL,merge as wL,once as kL,Subject as xe,Subscription as gS,ValueSubject as C}from"@vkontakte/videoplayer-shared";import{Observable as SL,map as dS,Subscription as vL,Subject as yL}from"@vkontakte/videoplayer-shared";var pS=a=>new SL(e=>{let t=new vL,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(dS(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(dS(({type:l})=>l!==void 0)),n=new yL,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 hS,Subscription as TL,combine as IL,filter as fS,once as mS}from"@vkontakte/videoplayer-shared";var ca=null,Hs=null;function al(){return ca||(ca=new(window.AudioContext||window.webkitAudioContext)),Hs||(Hs=new GainNode(ca,{gain:1}),Hs.connect(ca.destination)),{audioCtx:ca,gainNode:Hs}}import{clientChecker as EL}from"@vkontakte/videoplayer-shared";var Or=class Or{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new TL;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe(fS(n=>!!n.type),mS()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){EL.isSafari&&e!=="MPEG"||this.subscriptions.add(IL({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(fS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),mS()).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}=al(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Or.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Or.errorId,category:hS.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:Or.errorId,category:hS.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=al();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Or.errorId="VolumeMultiplierManager";var da=Or;var RL={chunkDuration:5e3,maxParallelRequests:5},ha=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 gS;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Ob([...Vb(this.params.tuning),...Bb(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>bS(e.sources[u])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(u=>!i.includes(u)),...t.filter(u=>i.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new la(s);let n=[...Iu(!0),...Iu(!1)];this.chromecastFormatsIterator=new la(n.filter(u=>bS(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new da(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(PL(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:js.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return pa(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Et(o),new ta(F(R({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),new ra(F(R({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Et(o),Pr||!this.params.tuning.useHlsJs?new na(F(R({},n),{source:o})):new aa(F(R({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),new sa(F(R({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Et(o),new oa(F(R({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new gb(F(R({},n),{source:o,config:F(R({},RL),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new ua({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 pa(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Et(o),new di({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 pa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return pa(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 pa(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 F(R({},e),{url:r(e.url)})}return(0,SS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new gS,t=!1,r=0;return e.add(wL(this.providerOutput.error$,pS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(AL(i=>({id:`ProviderHangup:${i}`,category:js.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(xL(({to:s})=>s==="playing"),kL()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=i.category===js.NETWORK,o=i.category===js.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}})),e}};import{fromEvent as Gs,once as LL,combine as $L,Subscription as vS,ValueSubject as sl,map as ML,filter as CL,isNonNullable as Ys,now as Pe,safeStorage as nl}from"@vkontakte/videoplayer-shared";var DL=5e3,yS="one_video_throughput",TS="one_video_rtt",lt=window.navigator.connection,IS=()=>{let a=lt==null?void 0:lt.downlink;if(Ys(a)&&a!==10)return a*1e3},ES=()=>{let a=lt==null?void 0:lt.rtt;if(Ys(a)&&a!==3e3)return a},xS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},ol=class a{constructor(e){this.subscription=new vS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(yS)||(e.useBrowserEstimation?IS():void 0)||DL,r=(s=(i=a.load(TS))!=null?i:e.useBrowserEstimation?ES():void 0)!=null?s:0;if(this.throughput$=new sl(t),this.rtt$=new sl(r),this.rttAdjustedThroughput$=new sl(xS(t,r,e.rttPenaltyRequestSize)),this.throughput=Kt.getSmoothedValue(t,-1,e),this.rtt=Kt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=IS();u&&this.throughput.next(u);let l=ES();Ys(l)&&this.rtt.next(l)};lt&&"onchange"in lt&&this.subscription.add(Gs(lt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{nl.set(yS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{nl.set(TS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add($L({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(ML(({throughput:n,rtt:o})=>xS(n,o,e.rttPenaltyRequestSize)),CL(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 vS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Gs(e,"progress").pipe(LL()).subscribe(s=>{t=s.loaded,r=Pe()}));break;case 1:case 0:i.add(Gs(e,"loadstart").subscribe(()=>{t=0,r=Pe()}));break}i.add(Gs(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=p=>w(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Pe()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Pe();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=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());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=nl.get(e);if(Ys(t))return(r=parseInt(t,10))!=null?r:void 0}},PS=ol;import{fillWithDefault as OL,VideoQuality as AS}from"@vkontakte/videoplayer-shared";var wS={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:AS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:AS.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},kS=a=>{var e;return F(R({},OL(a,wS)),{configName:[...(e=a.configName)!=null?e:[],...wS.configName]})};import{assertNonNullable as Ws,combine as Qs,ErrorCategory as zs,filter as fa,filterChanged as Oe,fromEvent as ll,isNonNullable as UL,isNullable as HL,Logger as jL,map as _,mapTo as MS,merge as xt,now as Ks,once as ct,Subject as Y,Subscription as CS,tap as DS,ValueSubject as x,isHigher as GL,isInvariantQuality as OS}from"@vkontakte/videoplayer-shared";import{merge as BL,map as VL,filter as RS,isNonNullable as _L}from"@vkontakte/videoplayer-shared";var ul=({seekState:a,position$:e})=>BL(a.stateChangeEnded$.pipe(VL(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),RS(_L)),e.pipe(RS(()=>a.getState().state==="none")));import{assertNonNullable as NL}from"@vkontakte/videoplayer-shared";var LS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return NL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as FL,once as qL}from"@vkontakte/videoplayer-shared";var $S=(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(FL(i=>i.length>0),qL()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Js=class{constructor(e={configName:[]}){this.subscription=new CS;this.logger=new jL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new x(!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 x("stopped"),position$:new x(0),duration$:new x(1/0),muted$:new x(!1),volume$:new x(1),availableVideoStreams$:new x([]),currentVideoStream$:new x(void 0),availableQualities$:new x([]),availableQualitiesFps$:new x({}),currentQuality$:new x(void 0),isAutoQualityEnabled$:new x(!0),autoQualityLimitingAvailable$:new x(!1),autoQualityLimits$:new x({}),availableAudioStreams$:new x([]),currentAudioStream$:new x(void 0),availableAudioTracks$:new x([]),isAudioAvailable$:new x(!0),currentPlaybackRate$:new x(1),currentBuffer$:new x({start:0,end:0}),isBuffering$:new x(!0),isStalled$:new x(!1),isEnded$:new x(!1),isLooped$:new x(!1),isLive$:new x(void 0),canChangePlaybackSpeed$:new x(void 0),atLiveEdge$:new x(void 0),atLiveDurationEdge$:new x(void 0),liveTime$:new x(void 0),liveBufferTime$:new x(void 0),currentFormat$:new x(void 0),availableTextTracks$:new x([]),currentTextTrack$:new x(void 0),throughputEstimation$:new x(void 0),rttEstimation$:new x(void 0),videoBitrate$:new x(void 0),hostname$:new x(void 0),httpConnectionType$:new x(void 0),httpConnectionReused$:new x(void 0),surface$:new x("none"),chromecastState$:new x("NOT_AVAILABLE"),chromecastDeviceName$:new x(void 0),intrinsicVideoSize$:new x(void 0),availableSources$:new x(void 0),is3DVideo$:new x(!1),currentVideoSegmentLength$:new x(0),currentAudioSegmentLength$:new x(0)};this.events={inited$:new Y,ready$:new Y,started$:new Y,playing$:new Y,paused$:new Y,stopped$:new Y,willStart$:new Y,willResume$:new Y,willPause$:new Y,willStop$:new Y,willDestruct$:new Y,watchCoverageRecord$:new Y,watchCoverageLive$:new Y,managedError$:new Y,fatalError$:new Y,ended$:new Y,looped$:new Y,seeked$:new Y,willSeek$:new Y,firstBytes$:new Y,loadedMetadata$:new Y,firstFrame$:new Y,canplay$:new Y,log$:new Y};this.experimental={element$:new x(void 0),tuningConfigName$:new x([]),enableDebugTelemetry$:new x(!1),dumpTelemetry:Jm};if(this.initLogs(),this.tuning=kS(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ia({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new PS(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,i)=>{let s=Reflect.get(t,r,i);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let u=n.map(d=>JSON.stringify(d,(p,h)=>{let f=typeof h;return["number","string","boolean"].includes(f)?h:h===null?null:`<${f}>`})),l=`Player.${String(r)}`,c=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:zs.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,i;return this.config=e,this.domContainer=LS(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new ha({sources:e.sources,meta:(r=e.meta)!=null?r:{},failoverHosts:(i=e.failoverHosts)!=null?i:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ti()?ll(document,"visibilitychange").pipe(ct()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue();return e>=r&&!i&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Ws(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(fa(r=>r.length>0),ct()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Ws(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>R({type:"external"},t))),this}selectTextTrack(e){var t;return $S(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(HL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return UL(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(xt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(fa(({from:e})=>e==="stopped"),ct()).subscribe(()=>{this.initedAt=Ks(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState(F(R({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:zs.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),Oe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(_(n=>n.map(({quality:o})=>o).sort((o,u)=>OS(o)?1:OS(u)?-1:GL(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Oe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Oe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Oe()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(_(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Qs({hasLiveOffsetByPaused:xt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(n=>n.to),Oe(),_(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Qs({atLiveEdge:Qs({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:ul({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(_(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),Oe(),DS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(_(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Qs({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(_(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Oe(),DS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),Oe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),Oe()).subscribe(this.info.volume$)).add(ul({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(xt(e.providerOutput.endedEvent$.pipe(MS(!0)),e.providerOutput.seekedEvent$.pipe(MS(!1))).pipe(Oe()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(_(n=>({id:n?`No${n}`:"NoProviders",category:zs.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(ct(),_(n=>n!=null?n:Ks()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ct(),_(()=>Ks()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ct(),_(()=>Ks()-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 x(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new x(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(fa(({to:n})=>n==="playing"),ct()).subscribe(()=>r.next(!1)));let i=0,s=xt(e.providerOutput.isBuffering$,t,r).pipe(_(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),Oe());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(xt(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(xt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(_(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new CS;this.subscription.add(t),this.subscription.add(e.current$.pipe(Oe((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(fa(r=>r.length>0),ct()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t,r=(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=yt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(xt(this.desiredState.videoTrack.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(_(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Ws(this.providerContainer),Ws(e),Km(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>zm(r)),this.providerContainer.current$.subscribe(({type:r})=>mi("provider",r)),e.duration$.subscribe(r=>mi("duration",r)),e.availableVideoTracks$.pipe(fa(r=>!!r.length),ct()).subscribe(r=>mi("tracks",r)),this.events.fatalError$.subscribe(new oe("fatalError")),this.events.managedError$.subscribe(new oe("managedError")),e.position$.subscribe(new oe("position")),e.currentVideoTrack$.pipe(_(r=>r==null?void 0:r.quality)).subscribe(new oe("quality")),this.info.currentBuffer$.subscribe(new oe("buffer")),e.isBuffering$.subscribe(new oe("isBuffering"))].forEach(r=>this.subscription.add(r)),mi("codecs",Db())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>w(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:zs.DOM,message:String(i)})})});this.subscription.add(xt(ll(document,"visibilitychange"),ll(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as jG,Observable as GG,Subject as YG,ValueSubject as WG,VideoQuality as QG}from"@vkontakte/videoplayer-shared";var zG=`@vkontakte/videoplayer-core@${Vl}`;export{ya as ChromecastState,hn as HttpConnectionType,GG as Observable,de as PlaybackState,Js as Player,zG as SDK_VERSION,YG as Subject,jG as Subscription,fn as Surface,Vl as VERSION,WG as ValueSubject,ft as VideoFormat,QG as VideoQuality};
|
|
91
|
+
`;var Cs=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new $s(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ms(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Dg,this.gl.VERTEX_SHADER),r=this.createShader(Og,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var zt=class{constructor(e){this.subscription=new fR;this.videoState=new M("stopped");this.elementSize$=new mR(void 0);this.textTracksManager=new Le;this.droppedFramesManager=new us;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new as;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&E(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return nR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Cs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ls({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=me(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Yu.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Bg(l=>!!l.length),Ng()).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(Bg(cR),Ng()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(_g(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(We(this.video,t.isLooped,i)),this.subscription.add(fe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Re(this.video,t.playbackRate,r.playbackRateState$,i)),s(hR(this.video),this.elementSize$),s(Me(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(oR(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Ou(h));let f=[];for(let b of h.representations){let g=vg(b);f.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(Bu(p));let h=[];for(let f of p.representations){let b=Sg(f);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let f=yg(p,h);this.textTracksMap.set(f,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=l=>e.error$.next({id:"RepresentationSwitch",category:Yu.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(Ds(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,lR(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let b=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,b).catch(n)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Wu()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Bu(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Wu()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Ou(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(_g(({to:l})=>l==="ready"),Wu());this.subscription.add(Ds(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Ds(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Ds(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,pR(["init"])).pipe(uR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var D,$,O,U,L,w,H,W,k,x,N,G,Q,Z;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(D=e.videoTrack.getState())==null?void 0:D.id,n=[...this.videoTracksMap.keys()].find(({id:F})=>F===i),o=t.currentVideoTrack$.getValue(),u=((U=(O=e.videoStream.getState())!=null?O:n&&(($=this.videoTracksMap.get(n))==null?void 0:$.stream))!=null?U:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:F})=>F===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=rt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(L=e.audioStream.getState())!=null?L:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(w=[...this.audioStreamsMap.keys()].find(({id:F})=>F===(f==null?void 0:f.id)))!=null?w:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let F=Is(n,c,(H=this.audioStreamsMap.get(b))!=null?H:[]);g=Math.max(g,(W=F==null?void 0:F.bitrate)!=null?W:-1/0)}if(o){let F=Is(o,c,(k=this.audioStreamsMap.get(b))!=null?k:[]);g=Math.max(g,(x=F==null?void 0:F.bitrate)!=null?x:-1/0)}}let S=vt(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:I}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(S=(N=c.filter(F=>!dR(F.quality)).sort((F,Kt)=>{var ut,V;return((ut=Kt.bitrate)!=null?ut:0)-((V=F.bitrate)!=null?V:0)}).filter(F=>Vg(F.quality,S.quality)&&Vg(F.quality,I))[0])!=null?N:S);let v=r?S!=null?S:n:n!=null?n:S,T=b&&Is(v,c,(G=this.audioStreamsMap.get(b))!=null?G:[]),y=(Q=this.videoTracksMap.get(v))==null?void 0:Q.representation,B=T&&((Z=this.audioTracksMap.get(T))==null?void 0:Z.representation);if(y&&B)return[y,B];if(y&&!B&&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:Yu.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),he(this.video)}};var Zi=class extends zt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Fg,interval as bR,map as gR}from"@vkontakte/videoplayer-shared";var ea=class extends zt{constructor(e){super(e),this.liveOffset=new et}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Fg({interval:bR(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:i})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(i-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(Fg({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(gR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var Ug=Ge(ts(),1);import{assertNever as ta,assertNonNullable as qg,debounce as SR,ErrorCategory as Os,filter as vR,isNonNullable as yR,isNullable as TR,map as Bs,merge as IR,Observable as ER,observableFrom as xR,Subscription as PR,videoSizeToQuality as wR}from"@vkontakte/videoplayer-shared";var Ue={};var Cr=(a,e)=>new ER(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),ra=class{constructor(e){this.subscription=new PR;this.videoState=new M("initializing");this.textTracksManager=new Le;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:ta(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ta(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ta(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ta(e)}break;default:ta(t)}};this.video=pe(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),he(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Os.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Ug.default)(import("hls.js").then(i=>{e||(Ue.Hls=i.default,Ue.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){qg(Ue.Hls,"hls.js not loaded"),this.hls=new Ue.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){qg(Ue.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Os.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=me(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(We(this.video,e.isLooped,r)),this.subscription.add(fe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Re(this.video,e.playbackRate,i.playbackRateState$,r)),s(Me(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Bs(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Cr(this.hls,Ue.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Os.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Cr(this.hls,Ue.Events.MANIFEST_PARSED).pipe(Bs(({levels:l})=>l.reduce((c,d)=>{var I,v;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(v=gt((I=d.attrs.QUALITY)!=null?I:""))!=null?v:wR({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(Cr(this.hls,Ue.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Cr(this.hls,Ue.Events.LEVEL_LOADING).pipe(Bs(({url:l})=>re(l))),t.hostname$),s(Cr(this.hls,Ue.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(ft(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=Cr(this.hls,Ue.Events.LEVEL_SWITCHED).pipe(Bs(({level:l})=>n(this.hls.levels[l])));o.pipe(vR(yR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(ft(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(TR(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=IR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xR(["init"])).pipe(SR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return A(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield be(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Os.DOM,thrown:t})))||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0)}};var Hg="X-Playback-Duration",Qu=a=>A(void 0,null,function*(){var i;let e=yield it(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Hg)?parseInt(e.headers.get(Hg),10):void 0});import{assertNever as MR,combine as CR,debounce as DR,ErrorCategory as _s,filter as OR,filterChanged as BR,isNonNullable as Gg,isNullable as Ns,map as Yg,merge as VR,observableFrom as _R,Subscription as NR,ValueSubject as Ju,VideoQuality as FR}from"@vkontakte/videoplayer-shared";var Ku=Ge(mo(),1);import{videoSizeToQuality as AR,getExponentialDelay as kR}from"@vkontakte/videoplayer-shared";var RR=a=>{let e=null;if(a.QUALITY&&(e=gt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=AR({width:t,height:r})}return e!=null?e:null},LR=(a,e)=>{var s,n;let t=a.split(`
|
|
92
|
+
`),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,Ku.default)(l[1].split(",").map(I=>I.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=RR(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[I,v]=d.RESOLUTION.split("x").map(T=>parseInt(T,10));I&&v&&(g={width:I,height:v})}let S=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:S,bandwidth:f,size:g,fps:b})}if(c){let d=(0,Ku.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},$R=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),zu=0,jg=(r,...i)=>A(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield it(a)).text();zu+=1;try{let{qualityManifests:o,textTracks:u}=LR(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(zu<=t.manifestRetryMaxCount)return yield $R(kR(zu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),jg(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Vs=jg;var ia=class{constructor(e){this.subscription=new NR;this.videoState=new M("stopped");this.textTracksManager=new Le;this.manifests$=new Ju([]);this.liveOffset=new et;this.manifestStartTime$=new Ju(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return MR(t)}};var t;this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:FR.INVARIANT,url:this.params.source.url},Vs(ae(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:_s.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_s.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.maxSeekBackTime$=new Ju((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:_s.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=me(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,i.playbackRateState$,r)),s(Me(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(BR(),Yg(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&&Gg(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(re(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(CR({startTime:this.manifestStartTime$.pipe(OR(Gg)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Yg(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=VR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,_R(["init"])).pipe(DR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),he(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Ns(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ae(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Qu(n).then(l=>{var c;if(!Ns(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Ns(d)||!isFinite(d))try{it(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();Qu(b).then(g=>{Ns(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:_s.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as qR,debounce as UR,ErrorCategory as Xu,fromEvent as Zu,isNonNullable as HR,isNullable as jR,map as Wg,merge as Qg,observableFrom as zg,Subscription as GR,ValueSubject as YR,VideoQuality as WR,clientChecker as QR}from"@vkontakte/videoplayer-shared";var aa=class{constructor(e){this.subscription=new GR;this.videoState=new M("stopped");this.textTracksManager=new Le;this.manifests$=new YR([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return qR(t)}};this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:WR.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Vs(ae(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Xu.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:Xu.WTF,message:"HlsProvider internal logic error",thrown:o})},i=me(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Wg(o=>o.to)),this.params.output.playbackState$),this.subscription.add(We(this.video,t.isLooped,r)),this.subscription.add(fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&HR(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(f=>f.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(re(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let 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(Wg(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!QR.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Qg(Zu(o,"addtrack"),Zu(o,"removetrack"),Zu(o,"change"),zg(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Qg(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,zg(["init"])).pipe(UR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),he(this.video)}prepare(){var s,n;let e=this.selectManifest();if(jR(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Xu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as zR,assertNonNullable as Kg,debounce as KR,ErrorCategory as Jg,isHigher as JR,isHigherOrEqual as XR,isInvariantQuality as Xg,isLowerOrEqual as ZR,isNonNullable as eL,merge as tL,observableFrom as rL,Subscription as iL,map as aL}from"@vkontakte/videoplayer-shared";var sa=class{constructor(e){this.subscription=new iL;this.videoState=new M("stopped");this.trackUrls={};this.textTracksManager=new Le;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return zR(e)}};this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:Jg.WTF,message:"MpegProvider internal logic error",thrown:o})},i=me(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(aL(o=>o.to)),this.params.output.playbackState$),this.subscription.add(We(this.video,t.isLooped,r)),this.subscription.add(fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,i.playbackRateState$,r)),s(Me(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&eL(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=tL(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,rL(["init"])).pipe(KR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),he(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Kg(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Kg(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=zi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(re(t))}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Jg.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=>!Xg(d.track.quality)&&ZR(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&XR(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!Xg(h.track.quality)&&JR(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=vt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as eS,debounce as uL,merge as tS,observableFrom as lL,Subscription as cL,map as rS,ValueSubject as dL,ErrorCategory as tl,VideoQuality as pL}from"@vkontakte/videoplayer-shared";import{ErrorCategory as sL}from"@vkontakte/videoplayer-shared";var Zg=["stun:videostun.mycdn.me:80"],nL=1e3,oL=3,el=()=>null,Fs=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=el;this.externalStopCallback=el;this.externalErrorCallback=el;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return A(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return A(this,null,function*(){try{let e={iceServers:[{urls:Zg}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return A(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return A(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:sL.WTF,message:e.message})}onPeerConnectionStream(e){return A(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return A(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),nL)}normalizeOptions(e={}){let t={stunServerList:Zg,maxRetryNumber:oL,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var na=class{constructor(e){this.videoState=new M("stopped");this.maxSeekBackTime$=new dL(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return eS(e)}};this.subscription=new cL,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=pe(e.container,e.tuning),this.liveStreamClient=new Fs(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),he(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:tl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};tS(this.videoState.stateChangeStarted$.pipe(rS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(rS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=me(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Me(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(fe(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return eS(n.to)}},r)).add(tS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,lL(["init"])).pipe(uL(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:pL.INVARIANT}),this.video.srcObject=e,E(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:tl.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:tl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var oa=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as ca,assertNonNullable as It,ErrorCategory as Us,filter as vL,isNonNullable as uS,isNullable as yL,map as TL,merge as IL,once as EL,Subject as Ee,Subscription as lS,ValueSubject as C}from"@vkontakte/videoplayer-shared";import{Observable as hL,map as iS,Subscription as fL,Subject as mL}from"@vkontakte/videoplayer-shared";var aS=a=>new hL(e=>{let t=new fL,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(iS(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(iS(({type:l})=>l!==void 0)),n=new mL,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as sS,Subscription as bL,combine as gL,filter as nS,once as oS}from"@vkontakte/videoplayer-shared";var ua=null,qs=null;function rl(){return ua||(ua=new(window.AudioContext||window.webkitAudioContext)),qs||(qs=new GainNode(ua,{gain:1}),qs.connect(ua.destination)),{audioCtx:ua,gainNode:qs}}import{clientChecker as SL}from"@vkontakte/videoplayer-shared";var Dr=class Dr{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new bL;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe(nS(n=>!!n.type),oS()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){SL.isSafari&&e!=="MPEG"||this.subscriptions.add(gL({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(nS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),oS()).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}=rl(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Dr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Dr.errorId,category:sS.VIDEO_PIPELINE,message:(n=o==null?void 0:o.message)!=null?n:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(n=>{var o;this.volumeMultiplierError$.next({id:Dr.errorId,category:sS.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=rl();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Dr.errorId="VolumeMultiplierManager";var la=Dr;var xL={chunkDuration:5e3,maxParallelRequests:5},da=class{constructor(e){this.current$=new C({type:void 0});this.providerError$=new Ee;this.noAvailableProvidersError$=new Ee;this.volumeMultiplierError$=new Ee;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 Ee,warning$:new Ee,willSeekEvent$:new Ee,seekedEvent$:new Ee,loopedEvent$:new Ee,endedEvent$:new Ee,firstBytesEvent$:new Ee,loadedMetadataEvent$:new Ee,firstFrameEvent$:new Ee,canplay$:new Ee,isLive$:new 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 lS;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Ab([...Rb(this.params.tuning),...kb(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>uS(e.sources[u])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(u=>!i.includes(u)),...t.filter(u=>i.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new oa(s);let n=[...yu(!0),...yu(!1)];this.chromecastFormatsIterator=new oa(n.filter(u=>uS(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new la(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(yL(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Us.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return ca(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return It(o),new Zi(q(R({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return It(o),new ea(q(R({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return It(o),xr||!this.params.tuning.useHlsJs?new aa(q(R({},n),{source:o})):new ra(q(R({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return It(o),new ia(q(R({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return It(o),new sa(q(R({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return It(o),new lb(q(R({},n),{source:o,config:q(R({},xL),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return It(o),new na({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return ca(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return It(o),new ci({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return ca(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ca(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return ca(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return q(R({},e),{url:r(e.url)})}return(0,cS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new lS,t=!1,r=0;return e.add(IL(this.providerOutput.error$,aS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(TL(i=>({id:`ProviderHangup:${i}`,category:Us.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(vL(({to:s})=>s==="playing"),EL()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=i.category===Us.NETWORK,o=i.category===Us.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}})),e}};import{fromEvent as Hs,once as PL,combine as wL,Subscription as dS,ValueSubject as il,map as AL,filter as kL,isNonNullable as js,now as xe,safeStorage as al}from"@vkontakte/videoplayer-shared";var RL=5e3,pS="one_video_throughput",hS="one_video_rtt",nt=window.navigator.connection,fS=()=>{let a=nt==null?void 0:nt.downlink;if(js(a)&&a!==10)return a*1e3},mS=()=>{let a=nt==null?void 0:nt.rtt;if(js(a)&&a!==3e3)return a},bS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},sl=class a{constructor(e){this.subscription=new dS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(pS)||(e.useBrowserEstimation?fS():void 0)||RL,r=(s=(i=a.load(hS))!=null?i:e.useBrowserEstimation?mS():void 0)!=null?s:0;if(this.throughput$=new il(t),this.rtt$=new il(r),this.rttAdjustedThroughput$=new il(bS(t,r,e.rttPenaltyRequestSize)),this.throughput=Wt.getSmoothedValue(t,-1,e),this.rtt=Wt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=fS();u&&this.throughput.next(u);let l=mS();js(l)&&this.rtt.next(l)};nt&&"onchange"in nt&&this.subscription.add(Hs(nt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{al.set(pS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{al.set(hS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(wL({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(AL(({throughput:n,rtt:o})=>bS(n,o,e.rttPenaltyRequestSize)),kL(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=xe(),i=new dS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Hs(e,"progress").pipe(PL()).subscribe(s=>{t=s.loaded,r=xe()}));break;case 1:case 0:i.add(Hs(e,"loadstart").subscribe(()=>{t=0,r=xe()}));break}i.add(Hs(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=xe(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=xe(),n=0,o=xe(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>A(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,xe()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=xe();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=xe()}else n+=d.byteLength;o=xe()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&xe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,xe()-o,this.concurrentDownloads.size),n=0,o=xe());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=al.get(e);if(js(t))return(r=parseInt(t,10))!=null?r:void 0}},gS=sl;import{fillWithDefault as LL,VideoQuality as SS}from"@vkontakte/videoplayer-shared";var vS={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:SS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:SS.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},yS=a=>{var e;return q(R({},LL(a,vS)),{configName:[...(e=a.configName)!=null?e:[],...vS.configName]})};import{assertNonNullable as Gs,combine as Ys,ErrorCategory as Ws,filter as pa,filterChanged as De,fromEvent as ol,isNonNullable as VL,isNullable as _L,Logger as NL,map as _,mapTo as xS,merge as Et,now as Qs,once as ot,Subject as Y,Subscription as PS,tap as wS,ValueSubject as P,isHigher as FL,isInvariantQuality as AS}from"@vkontakte/videoplayer-shared";import{merge as $L,map as ML,filter as TS,isNonNullable as CL}from"@vkontakte/videoplayer-shared";var nl=({seekState:a,position$:e})=>$L(a.stateChangeEnded$.pipe(ML(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),TS(CL)),e.pipe(TS(()=>a.getState().state==="none")));import{assertNonNullable as DL}from"@vkontakte/videoplayer-shared";var IS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return DL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as OL,once as BL}from"@vkontakte/videoplayer-shared";var ES=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(OL(i=>i.length>0),BL()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var zs=class{constructor(e={configName:[]}){this.subscription=new PS;this.logger=new NL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new M("stopped"),seekState:new M({state:"none"}),volume:new M({volume:1,muted:!1}),videoTrack:new M(void 0),videoStream:new M(void 0),audioStream:new M(void 0),autoVideoTrackSwitching:new M(!0),autoVideoTrackLimits:new M({}),isLooped:new M(!1),playbackRate:new M(1),externalTextTracks:new M([]),internalTextTracks:new M([]),currentTextTrack:new M(void 0),textTrackCuesSettings:new M({}),cameraOrientation:new M({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new Y,ready$:new Y,started$:new Y,playing$:new Y,paused$:new Y,stopped$:new Y,willStart$:new Y,willResume$:new Y,willPause$:new Y,willStop$:new Y,willDestruct$:new Y,watchCoverageRecord$:new Y,watchCoverageLive$:new Y,managedError$:new Y,fatalError$:new Y,ended$:new Y,looped$:new Y,seeked$:new Y,willSeek$:new Y,firstBytes$:new Y,loadedMetadata$:new Y,firstFrame$:new Y,canplay$:new Y,log$:new Y};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:zm};if(this.initLogs(),this.tuning=yS(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ya({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new gS(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,i)=>{let s=Reflect.get(t,r,i);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let u=n.map(d=>JSON.stringify(d,(p,h)=>{let f=typeof h;return["number","string","boolean"].includes(f)?h:h===null?null:`<${f}>`})),l=`Player.${String(r)}`,c=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:Ws.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,i;return this.config=e,this.domContainer=IS(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new da({sources:e.sources,meta:(r=e.meta)!=null?r:{},failoverHosts:(i=e.failoverHosts)!=null?i:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!vi()?ol(document,"visibilitychange").pipe(ot()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue();return e>=r&&!i&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Gs(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(pa(r=>r.length>0),ot()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Gs(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>R({type:"external"},t))),this}selectTextTrack(e){var t;return ES(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(_L(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return VL(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Et(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(pa(({from:e})=>e==="stopped"),ot()).subscribe(()=>{this.initedAt=Qs(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState(q(R({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Ws.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),De()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(_(n=>n.map(({quality:o})=>o).sort((o,u)=>AS(o)?1:AS(u)?-1:FL(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(De()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(De()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(De()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(_(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Ys({hasLiveOffsetByPaused:Et(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(n=>n.to),De(),_(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Ys({atLiveEdge:Ys({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:nl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(_(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),De(),wS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(_(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ys({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(_(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),De(),wS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),De()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),De()).subscribe(this.info.volume$)).add(nl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Et(e.providerOutput.endedEvent$.pipe(xS(!0)),e.providerOutput.seekedEvent$.pipe(xS(!1))).pipe(De()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(_(n=>({id:n?`No${n}`:"NoProviders",category:Ws.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(ot(),_(n=>n!=null?n:Qs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ot(),_(()=>Qs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ot(),_(()=>Qs()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(pa(({to:n})=>n==="playing"),ot()).subscribe(()=>r.next(!1)));let i=0,s=Et(e.providerOutput.isBuffering$,t,r).pipe(_(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),De());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Et(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Et(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(_(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new PS;this.subscription.add(t),this.subscription.add(e.current$.pipe(De((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(pa(r=>r.length>0),ot()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t,r=(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=vt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Et(this.desiredState.videoTrack.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(_(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Gs(this.providerContainer),Gs(e),Qm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Wm(r)),this.providerContainer.current$.subscribe(({type:r})=>fi("provider",r)),e.duration$.subscribe(r=>fi("duration",r)),e.availableVideoTracks$.pipe(pa(r=>!!r.length),ot()).subscribe(r=>fi("tracks",r)),this.events.fatalError$.subscribe(new ne("fatalError")),this.events.managedError$.subscribe(new ne("managedError")),e.position$.subscribe(new ne("position")),e.currentVideoTrack$.pipe(_(r=>r==null?void 0:r.quality)).subscribe(new ne("quality")),this.info.currentBuffer$.subscribe(new ne("buffer")),e.isBuffering$.subscribe(new ne("isBuffering"))].forEach(r=>this.subscription.add(r)),fi("codecs",wb())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>A(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Ws.DOM,message:String(i)})})});this.subscription.add(Et(ol(document,"visibilitychange"),ol(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as NG,Observable as FG,Subject as qG,ValueSubject as UG,VideoQuality as HG}from"@vkontakte/videoplayer-shared";var jG=`@vkontakte/videoplayer-core@${Ol}`;export{Sa as ChromecastState,dn as HttpConnectionType,FG as Observable,ce as PlaybackState,zs as Player,jG as SDK_VERSION,qG as Subject,NG as Subscription,pn as Surface,Ol as VERSION,UG as ValueSubject,pt as VideoFormat,HG as VideoQuality};
|