@vkontakte/videoplayer-core 2.0.115-dev.c6f77ae4.0 → 2.0.116-dev.48c29cc5.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 +18 -18
- package/es2015.esm.js +18 -18
- package/es2018.cjs.js +19 -19
- package/es2018.esm.js +19 -19
- package/esnext.cjs.js +19 -19
- package/esnext.esm.js +19 -19
- package/evergreen.esm.js +19 -19
- package/package.json +2 -2
- package/types/player/Player.d.ts +1 -1
- package/types/player/types.d.ts +1 -1
- package/types/providers/DashProvider/lib/buffer.d.ts +3 -0
- package/types/providers/DashProvider/lib/types.d.ts +1 -0
- package/types/utils/tuningConfig.d.ts +3 -0
package/es2018.cjs.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.116-dev.48c29cc5.0
|
|
3
|
+
* Tue, 29 Oct 2024 05:59:16 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-116/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var cg=Object.create;var Oa=Object.defineProperty;var dg=Object.getOwnPropertyDescriptor;var pg=Object.getOwnPropertyNames;var hg=Object.getPrototypeOf,fg=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),mg=(a,e)=>{for(var t in e)Oa(a,t,{get:e[t],enumerable:!0})},hl=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of pg(e))!fg.call(a,r)&&r!==t&&Oa(a,r,{get:()=>e[r],enumerable:!(i=dg(e,r))||i.enumerable});return a};var ze=(a,e,t)=>(t=a!=null?cg(hg(a)):{},hl(e||!a||!a.__esModule?Oa(t,"default",{value:a,enumerable:!0}):t,a)),bg=a=>hl(Oa({},"__esModule",{value:!0}),a);var Le=b(($A,ml)=>{"use strict";ml.exports=function(a){try{return!!a()}catch(e){return!0}}});var rr=b((LA,bl)=>{"use strict";var Sg=Le();bl.exports=!Sg(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Ie=b((MA,vl)=>{"use strict";var gl=rr(),Sl=Function.prototype,on=Sl.call,vg=gl&&Sl.bind.bind(on,on);vl.exports=gl?vg:function(a){return function(){return on.apply(a,arguments)}}});var gi=b((CA,Tl)=>{"use strict";var yl=Ie(),yg=yl({}.toString),Tg=yl("".slice);Tl.exports=function(a){return Tg(yg(a),8,-1)}});var El=b((DA,Il)=>{"use strict";var Ig=Ie(),Eg=Le(),xg=gi(),un=Object,Pg=Ig("".split);Il.exports=Eg(function(){return!un("z").propertyIsEnumerable(0)})?function(a){return xg(a)==="String"?Pg(a,""):un(a)}:un});var Si=b((BA,xl)=>{"use strict";xl.exports=function(a){return a==null}});var ar=b((OA,Pl)=>{"use strict";var Ag=Si(),wg=TypeError;Pl.exports=function(a){if(Ag(a))throw new wg("Can't call method on "+a);return a}});var vi=b((VA,Al)=>{"use strict";var kg=El(),Rg=ar();Al.exports=function(a){return kg(Rg(a))}});var ln=b((_A,wl)=>{"use strict";wl.exports=function(){}});var Yt=b((NA,kl)=>{"use strict";kl.exports={}});var oe=b((cn,Rl)=>{"use strict";var sr=function(a){return a&&a.Math===Math&&a};Rl.exports=sr(typeof globalThis=="object"&&globalThis)||sr(typeof window=="object"&&window)||sr(typeof self=="object"&&self)||sr(typeof global=="object"&&global)||sr(typeof cn=="object"&&cn)||function(){return this}()||Function("return this")()});var ne=b((FA,$l)=>{"use strict";var dn=typeof document=="object"&&document.all;$l.exports=typeof dn=="undefined"&&dn!==void 0?function(a){return typeof a=="function"||a===dn}:function(a){return typeof a=="function"}});var Cl=b((qA,Ml)=>{"use strict";var $g=oe(),Lg=ne(),Ll=$g.WeakMap;Ml.exports=Lg(Ll)&&/native code/.test(String(Ll))});var _e=b((UA,Dl)=>{"use strict";var Mg=ne();Dl.exports=function(a){return typeof a=="object"?a!==null:Mg(a)}});var Ne=b((HA,Bl)=>{"use strict";var Cg=Le();Bl.exports=!Cg(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Fa=b((jA,Vl)=>{"use strict";var Dg=oe(),Ol=_e(),pn=Dg.document,Bg=Ol(pn)&&Ol(pn.createElement);Vl.exports=function(a){return Bg?pn.createElement(a):{}}});var hn=b((GA,_l)=>{"use strict";var Og=Ne(),Vg=Le(),_g=Fa();_l.exports=!Og&&!Vg(function(){return Object.defineProperty(_g("div"),"a",{get:function(){return 7}}).a!==7})});var fn=b((WA,Nl)=>{"use strict";var Ng=Ne(),Fg=Le();Nl.exports=Ng&&Fg(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var st=b((YA,Fl)=>{"use strict";var qg=_e(),Ug=String,Hg=TypeError;Fl.exports=function(a){if(qg(a))return a;throw new Hg(Ug(a)+" is not an object")}});var Me=b((QA,ql)=>{"use strict";var jg=rr(),qa=Function.prototype.call;ql.exports=jg?qa.bind(qa):function(){return qa.apply(qa,arguments)}});var Ua=b((zA,Ul)=>{"use strict";Ul.exports={}});var mt=b((KA,jl)=>{"use strict";var mn=Ua(),bn=oe(),Gg=ne(),Hl=function(a){return Gg(a)?a:void 0};jl.exports=function(a,e){return arguments.length<2?Hl(mn[a])||Hl(bn[a]):mn[a]&&mn[a][e]||bn[a]&&bn[a][e]}});var nr=b((JA,Gl)=>{"use strict";var Wg=Ie();Gl.exports=Wg({}.isPrototypeOf)});var yi=b((XA,Ql)=>{"use strict";var Yg=oe(),Wl=Yg.navigator,Yl=Wl&&Wl.userAgent;Ql.exports=Yl?String(Yl):""});var Sn=b((ZA,ec)=>{"use strict";var Zl=oe(),gn=yi(),zl=Zl.process,Kl=Zl.Deno,Jl=zl&&zl.versions||Kl&&Kl.version,Xl=Jl&&Jl.v8,Ke,Ha;Xl&&(Ke=Xl.split("."),Ha=Ke[0]>0&&Ke[0]<4?1:+(Ke[0]+Ke[1]));!Ha&&gn&&(Ke=gn.match(/Edge\/(\d+)/),(!Ke||Ke[1]>=74)&&(Ke=gn.match(/Chrome\/(\d+)/),Ke&&(Ha=+Ke[1])));ec.exports=Ha});var vn=b((ew,ic)=>{"use strict";var tc=Sn(),Qg=Le(),zg=oe(),Kg=zg.String;ic.exports=!!Object.getOwnPropertySymbols&&!Qg(function(){var a=Symbol("symbol detection");return!Kg(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&tc&&tc<41})});var yn=b((tw,rc)=>{"use strict";var Jg=vn();rc.exports=Jg&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Tn=b((iw,ac)=>{"use strict";var Xg=mt(),Zg=ne(),eS=nr(),tS=yn(),iS=Object;ac.exports=tS?function(a){return typeof a=="symbol"}:function(a){var e=Xg("Symbol");return Zg(e)&&eS(e.prototype,iS(a))}});var or=b((rw,sc)=>{"use strict";var rS=String;sc.exports=function(a){try{return rS(a)}catch(e){return"Object"}}});var bt=b((aw,nc)=>{"use strict";var aS=ne(),sS=or(),nS=TypeError;nc.exports=function(a){if(aS(a))return a;throw new nS(sS(a)+" is not a function")}});var ur=b((sw,oc)=>{"use strict";var oS=bt(),uS=Si();oc.exports=function(a,e){var t=a[e];return uS(t)?void 0:oS(t)}});var lc=b((nw,uc)=>{"use strict";var In=Me(),En=ne(),xn=_e(),lS=TypeError;uc.exports=function(a,e){var t,i;if(e==="string"&&En(t=a.toString)&&!xn(i=In(t,a))||En(t=a.valueOf)&&!xn(i=In(t,a))||e!=="string"&&En(t=a.toString)&&!xn(i=In(t,a)))return i;throw new lS("Can't convert object to primitive value")}});var Je=b((ow,cc)=>{"use strict";cc.exports=!0});var hc=b((uw,pc)=>{"use strict";var dc=oe(),cS=Object.defineProperty;pc.exports=function(a,e){try{cS(dc,a,{value:e,configurable:!0,writable:!0})}catch(t){dc[a]=e}return e}});var lr=b((lw,bc)=>{"use strict";var dS=Je(),pS=oe(),hS=hc(),fc="__core-js_shared__",mc=bc.exports=pS[fc]||hS(fc,{});(mc.versions||(mc.versions=[])).push({version:"3.38.0",mode:dS?"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 Pn=b((cw,Sc)=>{"use strict";var gc=lr();Sc.exports=function(a,e){return gc[a]||(gc[a]=e||{})}});var cr=b((dw,vc)=>{"use strict";var fS=ar(),mS=Object;vc.exports=function(a){return mS(fS(a))}});var Xe=b((pw,yc)=>{"use strict";var bS=Ie(),gS=cr(),SS=bS({}.hasOwnProperty);yc.exports=Object.hasOwn||function(e,t){return SS(gS(e),t)}});var An=b((hw,Tc)=>{"use strict";var vS=Ie(),yS=0,TS=Math.random(),IS=vS(1 .toString);Tc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+IS(++yS+TS,36)}});var Se=b((fw,Ec)=>{"use strict";var ES=oe(),xS=Pn(),Ic=Xe(),PS=An(),AS=vn(),wS=yn(),Ti=ES.Symbol,wn=xS("wks"),kS=wS?Ti.for||Ti:Ti&&Ti.withoutSetter||PS;Ec.exports=function(a){return Ic(wn,a)||(wn[a]=AS&&Ic(Ti,a)?Ti[a]:kS("Symbol."+a)),wn[a]}});var wc=b((mw,Ac)=>{"use strict";var RS=Me(),xc=_e(),Pc=Tn(),$S=ur(),LS=lc(),MS=Se(),CS=TypeError,DS=MS("toPrimitive");Ac.exports=function(a,e){if(!xc(a)||Pc(a))return a;var t=$S(a,DS),i;if(t){if(e===void 0&&(e="default"),i=RS(t,a,e),!xc(i)||Pc(i))return i;throw new CS("Can't convert object to primitive value")}return e===void 0&&(e="number"),LS(a,e)}});var kn=b((bw,kc)=>{"use strict";var BS=wc(),OS=Tn();kc.exports=function(a){var e=BS(a,"string");return OS(e)?e:e+""}});var Qt=b($c=>{"use strict";var VS=Ne(),_S=hn(),NS=fn(),ja=st(),Rc=kn(),FS=TypeError,Rn=Object.defineProperty,qS=Object.getOwnPropertyDescriptor,$n="enumerable",Ln="configurable",Mn="writable";$c.f=VS?NS?function(e,t,i){if(ja(e),t=Rc(t),ja(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Mn in i&&!i[Mn]){var r=qS(e,t);r&&r[Mn]&&(e[t]=i.value,i={configurable:Ln in i?i[Ln]:r[Ln],enumerable:$n in i?i[$n]:r[$n],writable:!1})}return Rn(e,t,i)}:Rn:function(e,t,i){if(ja(e),t=Rc(t),ja(i),_S)try{return Rn(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new FS("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var dr=b((Sw,Lc)=>{"use strict";Lc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Ii=b((vw,Mc)=>{"use strict";var US=Ne(),HS=Qt(),jS=dr();Mc.exports=US?function(a,e,t){return HS.f(a,e,jS(1,t))}:function(a,e,t){return a[e]=t,a}});var Ga=b((yw,Dc)=>{"use strict";var GS=Pn(),WS=An(),Cc=GS("keys");Dc.exports=function(a){return Cc[a]||(Cc[a]=WS(a))}});var Wa=b((Tw,Bc)=>{"use strict";Bc.exports={}});var On=b((Iw,_c)=>{"use strict";var YS=Cl(),Vc=oe(),QS=_e(),zS=Ii(),Cn=Xe(),Dn=lr(),KS=Ga(),JS=Wa(),Oc="Object already initialized",Bn=Vc.TypeError,XS=Vc.WeakMap,Ya,pr,Qa,ZS=function(a){return Qa(a)?pr(a):Ya(a,{})},ev=function(a){return function(e){var t;if(!QS(e)||(t=pr(e)).type!==a)throw new Bn("Incompatible receiver, "+a+" required");return t}};YS||Dn.state?(Ze=Dn.state||(Dn.state=new XS),Ze.get=Ze.get,Ze.has=Ze.has,Ze.set=Ze.set,Ya=function(a,e){if(Ze.has(a))throw new Bn(Oc);return e.facade=a,Ze.set(a,e),e},pr=function(a){return Ze.get(a)||{}},Qa=function(a){return Ze.has(a)}):(zt=KS("state"),JS[zt]=!0,Ya=function(a,e){if(Cn(a,zt))throw new Bn(Oc);return e.facade=a,zS(a,zt,e),e},pr=function(a){return Cn(a,zt)?a[zt]:{}},Qa=function(a){return Cn(a,zt)});var Ze,zt;_c.exports={set:Ya,get:pr,has:Qa,enforce:ZS,getterFor:ev}});var Vn=b((Ew,Uc)=>{"use strict";var tv=rr(),qc=Function.prototype,Nc=qc.apply,Fc=qc.call;Uc.exports=typeof Reflect=="object"&&Reflect.apply||(tv?Fc.bind(Nc):function(){return Fc.apply(Nc,arguments)})});var _n=b((xw,Hc)=>{"use strict";var iv=gi(),rv=Ie();Hc.exports=function(a){if(iv(a)==="Function")return rv(a)}});var Yc=b(Wc=>{"use strict";var jc={}.propertyIsEnumerable,Gc=Object.getOwnPropertyDescriptor,av=Gc&&!jc.call({1:2},1);Wc.f=av?function(e){var t=Gc(this,e);return!!t&&t.enumerable}:jc});var Kc=b(zc=>{"use strict";var sv=Ne(),nv=Me(),ov=Yc(),uv=dr(),lv=vi(),cv=kn(),dv=Xe(),pv=hn(),Qc=Object.getOwnPropertyDescriptor;zc.f=sv?Qc:function(e,t){if(e=lv(e),t=cv(t),pv)try{return Qc(e,t)}catch(i){}if(dv(e,t))return uv(!nv(ov.f,e,t),e[t])}});var Nn=b((ww,Jc)=>{"use strict";var hv=Le(),fv=ne(),mv=/#|\.prototype\./,hr=function(a,e){var t=gv[bv(a)];return t===vv?!0:t===Sv?!1:fv(e)?hv(e):!!e},bv=hr.normalize=function(a){return String(a).replace(mv,".").toLowerCase()},gv=hr.data={},Sv=hr.NATIVE="N",vv=hr.POLYFILL="P";Jc.exports=hr});var fr=b((kw,Zc)=>{"use strict";var Xc=_n(),yv=bt(),Tv=rr(),Iv=Xc(Xc.bind);Zc.exports=function(a,e){return yv(a),e===void 0?a:Tv?Iv(a,e):function(){return a.apply(e,arguments)}}});var Fe=b((Rw,td)=>{"use strict";var mr=oe(),Ev=Vn(),xv=_n(),Pv=ne(),Av=Kc().f,wv=Nn(),Ei=Ua(),kv=fr(),xi=Ii(),ed=Xe();lr();var Rv=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return Ev(a,this,arguments)};return e.prototype=a.prototype,e};td.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?mr:r?mr[t]:mr[t]&&mr[t].prototype,o=i?Ei:Ei[t]||xi(Ei,t,{})[t],u=o.prototype,c,l,d,p,h,m,g,S,x;for(p in e)c=wv(i?p:t+(r?".":"#")+p,a.forced),l=!c&&n&&ed(n,p),m=o[p],l&&(a.dontCallGetSet?(x=Av(n,p),g=x&&x.value):g=n[p]),h=l&&g?g:e[p],!(!c&&!s&&typeof m==typeof h)&&(a.bind&&l?S=kv(h,mr):a.wrap&&l?S=Rv(h):s&&Pv(h)?S=xv(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&xi(S,"sham",!0),xi(o,p,S),s&&(d=t+"Prototype",ed(Ei,d)||xi(Ei,d,{}),xi(Ei[d],p,h),a.real&&u&&(c||!u[p])&&xi(u,p,h)))}});var ad=b(($w,rd)=>{"use strict";var Fn=Ne(),$v=Xe(),id=Function.prototype,Lv=Fn&&Object.getOwnPropertyDescriptor,qn=$v(id,"name"),Mv=qn&&function(){}.name==="something",Cv=qn&&(!Fn||Fn&&Lv(id,"name").configurable);rd.exports={EXISTS:qn,PROPER:Mv,CONFIGURABLE:Cv}});var nd=b((Lw,sd)=>{"use strict";var Dv=Math.ceil,Bv=Math.floor;sd.exports=Math.trunc||function(e){var t=+e;return(t>0?Bv:Dv)(t)}});var za=b((Mw,od)=>{"use strict";var Ov=nd();od.exports=function(a){var e=+a;return e!==e||e===0?0:Ov(e)}});var ld=b((Cw,ud)=>{"use strict";var Vv=za(),_v=Math.max,Nv=Math.min;ud.exports=function(a,e){var t=Vv(a);return t<0?_v(t+e,0):Nv(t,e)}});var dd=b((Dw,cd)=>{"use strict";var Fv=za(),qv=Math.min;cd.exports=function(a){var e=Fv(a);return e>0?qv(e,9007199254740991):0}});var Ka=b((Bw,pd)=>{"use strict";var Uv=dd();pd.exports=function(a){return Uv(a.length)}});var md=b((Ow,fd)=>{"use strict";var Hv=vi(),jv=ld(),Gv=Ka(),hd=function(a){return function(e,t,i){var r=Hv(e),s=Gv(r);if(s===0)return!a&&-1;var n=jv(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};fd.exports={includes:hd(!0),indexOf:hd(!1)}});var Sd=b((Vw,gd)=>{"use strict";var Wv=Ie(),Un=Xe(),Yv=vi(),Qv=md().indexOf,zv=Wa(),bd=Wv([].push);gd.exports=function(a,e){var t=Yv(a),i=0,r=[],s;for(s in t)!Un(zv,s)&&Un(t,s)&&bd(r,s);for(;e.length>i;)Un(t,s=e[i++])&&(~Qv(r,s)||bd(r,s));return r}});var Hn=b((_w,vd)=>{"use strict";vd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Td=b((Nw,yd)=>{"use strict";var Kv=Sd(),Jv=Hn();yd.exports=Object.keys||function(e){return Kv(e,Jv)}});var Ed=b(Id=>{"use strict";var Xv=Ne(),Zv=fn(),ey=Qt(),ty=st(),iy=vi(),ry=Td();Id.f=Xv&&!Zv?Object.defineProperties:function(e,t){ty(e);for(var i=iy(t),r=ry(t),s=r.length,n=0,o;s>n;)ey.f(e,o=r[n++],i[o]);return e}});var jn=b((qw,xd)=>{"use strict";var ay=mt();xd.exports=ay("document","documentElement")});var Qn=b((Uw,Ld)=>{"use strict";var sy=st(),ny=Ed(),Pd=Hn(),oy=Wa(),uy=jn(),ly=Fa(),cy=Ga(),Ad=">",wd="<",Wn="prototype",Yn="script",Rd=cy("IE_PROTO"),Gn=function(){},$d=function(a){return wd+Yn+Ad+a+wd+"/"+Yn+Ad},kd=function(a){a.write($d("")),a.close();var e=a.parentWindow.Object;return a=null,e},dy=function(){var a=ly("iframe"),e="java"+Yn+":",t;return a.style.display="none",uy.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write($d("document.F=Object")),t.close(),t.F},Ja,Xa=function(){try{Ja=new ActiveXObject("htmlfile")}catch(e){}Xa=typeof document!="undefined"?document.domain&&Ja?kd(Ja):dy():kd(Ja);for(var a=Pd.length;a--;)delete Xa[Wn][Pd[a]];return Xa()};oy[Rd]=!0;Ld.exports=Object.create||function(e,t){var i;return e!==null?(Gn[Wn]=sy(e),i=new Gn,Gn[Wn]=null,i[Rd]=e):i=Xa(),t===void 0?i:ny.f(i,t)}});var Cd=b((Hw,Md)=>{"use strict";var py=Le();Md.exports=!py(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Kn=b((jw,Bd)=>{"use strict";var hy=Xe(),fy=ne(),my=cr(),by=Ga(),gy=Cd(),Dd=by("IE_PROTO"),zn=Object,Sy=zn.prototype;Bd.exports=gy?zn.getPrototypeOf:function(a){var e=my(a);if(hy(e,Dd))return e[Dd];var t=e.constructor;return fy(t)&&e instanceof t?t.prototype:e instanceof zn?Sy:null}});var Pi=b((Gw,Od)=>{"use strict";var vy=Ii();Od.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:vy(a,e,t),a}});var eo=b((Ww,Nd)=>{"use strict";var yy=Le(),Ty=ne(),Iy=_e(),Ey=Qn(),Vd=Kn(),xy=Pi(),Py=Se(),Ay=Je(),Zn=Py("iterator"),_d=!1,gt,Jn,Xn;[].keys&&(Xn=[].keys(),"next"in Xn?(Jn=Vd(Vd(Xn)),Jn!==Object.prototype&&(gt=Jn)):_d=!0);var wy=!Iy(gt)||yy(function(){var a={};return gt[Zn].call(a)!==a});wy?gt={}:Ay&&(gt=Ey(gt));Ty(gt[Zn])||xy(gt,Zn,function(){return this});Nd.exports={IteratorPrototype:gt,BUGGY_SAFARI_ITERATORS:_d}});var Za=b((Yw,qd)=>{"use strict";var ky=Se(),Ry=ky("toStringTag"),Fd={};Fd[Ry]="z";qd.exports=String(Fd)==="[object z]"});var br=b((Qw,Ud)=>{"use strict";var $y=Za(),Ly=ne(),es=gi(),My=Se(),Cy=My("toStringTag"),Dy=Object,By=es(function(){return arguments}())==="Arguments",Oy=function(a,e){try{return a[e]}catch(t){}};Ud.exports=$y?es:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=Oy(e=Dy(a),Cy))=="string"?t:By?es(e):(i=es(e))==="Object"&&Ly(e.callee)?"Arguments":i}});var jd=b((zw,Hd)=>{"use strict";var Vy=Za(),_y=br();Hd.exports=Vy?{}.toString:function(){return"[object "+_y(this)+"]"}});var gr=b((Kw,Wd)=>{"use strict";var Ny=Za(),Fy=Qt().f,qy=Ii(),Uy=Xe(),Hy=jd(),jy=Se(),Gd=jy("toStringTag");Wd.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(Uy(r,Gd)||Fy(r,Gd,{configurable:!0,value:e}),i&&!Ny&&qy(r,"toString",Hy))}});var Qd=b((Jw,Yd)=>{"use strict";var Gy=eo().IteratorPrototype,Wy=Qn(),Yy=dr(),Qy=gr(),zy=Yt(),Ky=function(){return this};Yd.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=Wy(Gy,{next:Yy(+!i,t)}),Qy(a,r,!1,!0),zy[r]=Ky,a}});var Kd=b((Xw,zd)=>{"use strict";var Jy=Ie(),Xy=bt();zd.exports=function(a,e,t){try{return Jy(Xy(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Xd=b((Zw,Jd)=>{"use strict";var Zy=_e();Jd.exports=function(a){return Zy(a)||a===null}});var ep=b((ek,Zd)=>{"use strict";var eT=Xd(),tT=String,iT=TypeError;Zd.exports=function(a){if(eT(a))return a;throw new iT("Can't set "+tT(a)+" as a prototype")}});var to=b((tk,tp)=>{"use strict";var rT=Kd(),aT=_e(),sT=ar(),nT=ep();tp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=rT(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return sT(r),nT(s),aT(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var pp=b((ik,dp)=>{"use strict";var oT=Fe(),uT=Me(),ts=Je(),lp=ad(),lT=ne(),cT=Qd(),ip=Kn(),rp=to(),dT=gr(),pT=Ii(),io=Pi(),hT=Se(),ap=Yt(),cp=eo(),fT=lp.PROPER,mT=lp.CONFIGURABLE,sp=cp.IteratorPrototype,is=cp.BUGGY_SAFARI_ITERATORS,Sr=hT("iterator"),np="keys",vr="values",op="entries",up=function(){return this};dp.exports=function(a,e,t,i,r,s,n){cT(t,e,i);var o=function(x){if(x===r&&p)return p;if(!is&&x&&x in l)return l[x];switch(x){case np:return function(){return new t(this,x)};case vr:return function(){return new t(this,x)};case op:return function(){return new t(this,x)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[Sr]||l["@@iterator"]||r&&l[r],p=!is&&d||o(r),h=e==="Array"&&l.entries||d,m,g,S;if(h&&(m=ip(h.call(new a)),m!==Object.prototype&&m.next&&(!ts&&ip(m)!==sp&&(rp?rp(m,sp):lT(m[Sr])||io(m,Sr,up)),dT(m,u,!0,!0),ts&&(ap[u]=up))),fT&&r===vr&&d&&d.name!==vr&&(!ts&&mT?pT(l,"name",vr):(c=!0,p=function(){return uT(d,this)})),r)if(g={values:o(vr),keys:s?p:o(np),entries:o(op)},n)for(S in g)(is||c||!(S in l))&&io(l,S,g[S]);else oT({target:e,proto:!0,forced:is||c},g);return(!ts||n)&&l[Sr]!==p&&io(l,Sr,p,{name:r}),ap[e]=p,g}});var fp=b((rk,hp)=>{"use strict";hp.exports=function(a,e){return{value:a,done:e}}});var ao=b((ak,vp)=>{"use strict";var bT=vi(),ro=ln(),mp=Yt(),gp=On(),gT=Qt().f,ST=pp(),rs=fp(),vT=Je(),yT=Ne(),Sp="Array Iterator",TT=gp.set,IT=gp.getterFor(Sp);vp.exports=ST(Array,"Array",function(a,e){TT(this,{type:Sp,target:bT(a),index:0,kind:e})},function(){var a=IT(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,rs(void 0,!0);switch(a.kind){case"keys":return rs(t,!1);case"values":return rs(e[t],!1)}return rs([t,e[t]],!1)},"values");var bp=mp.Arguments=mp.Array;ro("keys");ro("values");ro("entries");if(!vT&&yT&&bp.name!=="values")try{gT(bp,"name",{value:"values"})}catch(a){}});var Tp=b((sk,yp)=>{"use strict";var ET=Se(),xT=Yt(),PT=ET("iterator"),AT=Array.prototype;yp.exports=function(a){return a!==void 0&&(xT.Array===a||AT[PT]===a)}});var so=b((nk,Ep)=>{"use strict";var wT=br(),Ip=ur(),kT=Si(),RT=Yt(),$T=Se(),LT=$T("iterator");Ep.exports=function(a){if(!kT(a))return Ip(a,LT)||Ip(a,"@@iterator")||RT[wT(a)]}});var Pp=b((ok,xp)=>{"use strict";var MT=Me(),CT=bt(),DT=st(),BT=or(),OT=so(),VT=TypeError;xp.exports=function(a,e){var t=arguments.length<2?OT(a):e;if(CT(t))return DT(MT(t,a));throw new VT(BT(a)+" is not iterable")}});var kp=b((uk,wp)=>{"use strict";var _T=Me(),Ap=st(),NT=ur();wp.exports=function(a,e,t){var i,r;Ap(a);try{if(i=NT(a,"return"),!i){if(e==="throw")throw t;return t}i=_T(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Ap(i),t}});var ss=b((lk,Mp)=>{"use strict";var FT=fr(),qT=Me(),UT=st(),HT=or(),jT=Tp(),GT=Ka(),Rp=nr(),WT=Pp(),YT=so(),$p=kp(),QT=TypeError,as=function(a,e){this.stopped=a,this.result=e},Lp=as.prototype;Mp.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=FT(e,i),c,l,d,p,h,m,g,S=function(A){return c&&$p(c,"normal",A),new as(!0,A)},x=function(A){return r?(UT(A),o?u(A[0],A[1],S):u(A[0],A[1])):o?u(A,S):u(A)};if(s)c=a.iterator;else if(n)c=a;else{if(l=YT(a),!l)throw new QT(HT(a)+" is not iterable");if(jT(l)){for(d=0,p=GT(a);p>d;d++)if(h=x(a[d]),h&&Rp(Lp,h))return h;return new as(!1)}c=WT(a,l)}for(m=s?a.next:c.next;!(g=qT(m,c)).done;){try{h=x(g.value)}catch(A){$p(c,"throw",A)}if(typeof h=="object"&&h&&Rp(Lp,h))return h}return new as(!1)}});var Dp=b((ck,Cp)=>{"use strict";var zT=Ne(),KT=Qt(),JT=dr();Cp.exports=function(a,e,t){zT?KT.f(a,e,JT(0,t)):a[e]=t}});var Bp=b(()=>{"use strict";var XT=Fe(),ZT=ss(),eI=Dp();XT({target:"Object",stat:!0},{fromEntries:function(e){var t={};return ZT(e,function(i,r){eI(t,i,r)},{AS_ENTRIES:!0}),t}})});var Vp=b((hk,Op)=>{"use strict";ao();Bp();var tI=Ua();Op.exports=tI.Object.fromEntries});var Np=b((fk,_p)=>{"use strict";_p.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 qp=b(()=>{"use strict";ao();var iI=Np(),rI=oe(),aI=gr(),Fp=Yt();for(ns in iI)aI(rI[ns],ns),Fp[ns]=Fp.Array;var ns});var Hp=b((gk,Up)=>{"use strict";var sI=Vp();qp();Up.exports=sI});var no=b((Sk,jp)=>{"use strict";var nI=Hp();jp.exports=nI});var Gp=b(()=>{"use strict"});var oo=b((Tk,Wp)=>{"use strict";var yr=oe(),oI=yi(),uI=gi(),os=function(a){return oI.slice(0,a.length)===a};Wp.exports=function(){return os("Bun/")?"BUN":os("Cloudflare-Workers")?"CLOUDFLARE":os("Deno/")?"DENO":os("Node.js/")?"NODE":yr.Bun&&typeof Bun.version=="string"?"BUN":yr.Deno&&typeof Deno.version=="object"?"DENO":uI(yr.process)==="process"?"NODE":yr.window&&yr.document?"BROWSER":"REST"}()});var us=b((Ik,Yp)=>{"use strict";var lI=oo();Yp.exports=lI==="NODE"});var zp=b((Ek,Qp)=>{"use strict";var cI=Qt();Qp.exports=function(a,e,t){return cI.f(a,e,t)}});var Xp=b((xk,Jp)=>{"use strict";var dI=mt(),pI=zp(),hI=Se(),fI=Ne(),Kp=hI("species");Jp.exports=function(a){var e=dI(a);fI&&e&&!e[Kp]&&pI(e,Kp,{configurable:!0,get:function(){return this}})}});var eh=b((Pk,Zp)=>{"use strict";var mI=nr(),bI=TypeError;Zp.exports=function(a,e){if(mI(e,a))return a;throw new bI("Incorrect invocation")}});var lo=b((Ak,th)=>{"use strict";var gI=Ie(),SI=ne(),uo=lr(),vI=gI(Function.toString);SI(uo.inspectSource)||(uo.inspectSource=function(a){return vI(a)});th.exports=uo.inspectSource});var oh=b((wk,nh)=>{"use strict";var yI=Ie(),TI=Le(),ih=ne(),II=br(),EI=mt(),xI=lo(),rh=function(){},ah=EI("Reflect","construct"),co=/^\s*(?:class|function)\b/,PI=yI(co.exec),AI=!co.test(rh),Tr=function(e){if(!ih(e))return!1;try{return ah(rh,[],e),!0}catch(t){return!1}},sh=function(e){if(!ih(e))return!1;switch(II(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return AI||!!PI(co,xI(e))}catch(t){return!0}};sh.sham=!0;nh.exports=!ah||TI(function(){var a;return Tr(Tr.call)||!Tr(Object)||!Tr(function(){a=!0})||a})?sh:Tr});var lh=b((kk,uh)=>{"use strict";var wI=oh(),kI=or(),RI=TypeError;uh.exports=function(a){if(wI(a))return a;throw new RI(kI(a)+" is not a constructor")}});var po=b((Rk,dh)=>{"use strict";var ch=st(),$I=lh(),LI=Si(),MI=Se(),CI=MI("species");dh.exports=function(a,e){var t=ch(a).constructor,i;return t===void 0||LI(i=ch(t)[CI])?e:$I(i)}});var hh=b(($k,ph)=>{"use strict";var DI=Ie();ph.exports=DI([].slice)});var mh=b((Lk,fh)=>{"use strict";var BI=TypeError;fh.exports=function(a,e){if(a<e)throw new BI("Not enough arguments");return a}});var ho=b((Mk,bh)=>{"use strict";var OI=yi();bh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(OI)});var Io=b((Ck,Ph)=>{"use strict";var Ce=oe(),VI=Vn(),_I=fr(),gh=ne(),NI=Xe(),xh=Le(),Sh=jn(),FI=hh(),vh=Fa(),qI=mh(),UI=ho(),HI=us(),vo=Ce.setImmediate,yo=Ce.clearImmediate,jI=Ce.process,fo=Ce.Dispatch,GI=Ce.Function,yh=Ce.MessageChannel,WI=Ce.String,mo=0,Ir={},Th="onreadystatechange",Er,Kt,bo,go;xh(function(){Er=Ce.location});var To=function(a){if(NI(Ir,a)){var e=Ir[a];delete Ir[a],e()}},So=function(a){return function(){To(a)}},Ih=function(a){To(a.data)},Eh=function(a){Ce.postMessage(WI(a),Er.protocol+"//"+Er.host)};(!vo||!yo)&&(vo=function(e){qI(arguments.length,1);var t=gh(e)?e:GI(e),i=FI(arguments,1);return Ir[++mo]=function(){VI(t,void 0,i)},Kt(mo),mo},yo=function(e){delete Ir[e]},HI?Kt=function(a){jI.nextTick(So(a))}:fo&&fo.now?Kt=function(a){fo.now(So(a))}:yh&&!UI?(bo=new yh,go=bo.port2,bo.port1.onmessage=Ih,Kt=_I(go.postMessage,go)):Ce.addEventListener&&gh(Ce.postMessage)&&!Ce.importScripts&&Er&&Er.protocol!=="file:"&&!xh(Eh)?(Kt=Eh,Ce.addEventListener("message",Ih,!1)):Th in vh("script")?Kt=function(a){Sh.appendChild(vh("script"))[Th]=function(){Sh.removeChild(this),To(a)}}:Kt=function(a){setTimeout(So(a),0)});Ph.exports={set:vo,clear:yo}});var kh=b((Dk,wh)=>{"use strict";var Ah=oe(),YI=Ne(),QI=Object.getOwnPropertyDescriptor;wh.exports=function(a){if(!YI)return Ah[a];var e=QI(Ah,a);return e&&e.value}});var Eo=b((Bk,$h)=>{"use strict";var Rh=function(){this.head=null,this.tail=null};Rh.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}}};$h.exports=Rh});var Mh=b((Ok,Lh)=>{"use strict";var zI=yi();Lh.exports=/ipad|iphone|ipod/i.test(zI)&&typeof Pebble!="undefined"});var Dh=b((Vk,Ch)=>{"use strict";var KI=yi();Ch.exports=/web0s(?!.*chrome)/i.test(KI)});var qh=b((_k,Fh)=>{"use strict";var wi=oe(),JI=kh(),Bh=fr(),xo=Io().set,XI=Eo(),ZI=ho(),eE=Mh(),tE=Dh(),Po=us(),Oh=wi.MutationObserver||wi.WebKitMutationObserver,Vh=wi.document,_h=wi.process,ls=wi.Promise,ko=JI("queueMicrotask"),Ai,Ao,wo,cs,Nh;ko||(xr=new XI,Pr=function(){var a,e;for(Po&&(a=_h.domain)&&a.exit();e=xr.get();)try{e()}catch(t){throw xr.head&&Ai(),t}a&&a.enter()},!ZI&&!Po&&!tE&&Oh&&Vh?(Ao=!0,wo=Vh.createTextNode(""),new Oh(Pr).observe(wo,{characterData:!0}),Ai=function(){wo.data=Ao=!Ao}):!eE&&ls&&ls.resolve?(cs=ls.resolve(void 0),cs.constructor=ls,Nh=Bh(cs.then,cs),Ai=function(){Nh(Pr)}):Po?Ai=function(){_h.nextTick(Pr)}:(xo=Bh(xo,wi),Ai=function(){xo(Pr)}),ko=function(a){xr.head||Ai(),xr.add(a)});var xr,Pr;Fh.exports=ko});var Hh=b((Nk,Uh)=>{"use strict";Uh.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var ds=b((Fk,jh)=>{"use strict";jh.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Jt=b((qk,Gh)=>{"use strict";var iE=oe();Gh.exports=iE.Promise});var ki=b((Uk,zh)=>{"use strict";var rE=oe(),Ar=Jt(),aE=ne(),sE=Nn(),nE=lo(),oE=Se(),Wh=oo(),uE=Je(),Ro=Sn(),Yh=Ar&&Ar.prototype,lE=oE("species"),$o=!1,Qh=aE(rE.PromiseRejectionEvent),cE=sE("Promise",function(){var a=nE(Ar),e=a!==String(Ar);if(!e&&Ro===66||uE&&!(Yh.catch&&Yh.finally))return!0;if(!Ro||Ro<51||!/native code/.test(a)){var t=new Ar(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[lE]=i,$o=t.then(function(){})instanceof i,!$o)return!0}return!e&&(Wh==="BROWSER"||Wh==="DENO")&&!Qh});zh.exports={CONSTRUCTOR:cE,REJECTION_EVENT:Qh,SUBCLASSING:$o}});var Ri=b((Hk,Jh)=>{"use strict";var Kh=bt(),dE=TypeError,pE=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new dE("Bad Promise constructor");e=i,t=r}),this.resolve=Kh(e),this.reject=Kh(t)};Jh.exports.f=function(a){return new pE(a)}});var gf=b(()=>{"use strict";var hE=Fe(),fE=Je(),ms=us(),Ot=oe(),Ci=Me(),Xh=Pi(),Zh=to(),mE=gr(),bE=Xp(),gE=bt(),fs=ne(),SE=_e(),vE=eh(),yE=po(),sf=Io().set,Bo=qh(),TE=Hh(),IE=ds(),EE=Eo(),nf=On(),bs=Jt(),Oo=ki(),of=Ri(),gs="Promise",uf=Oo.CONSTRUCTOR,xE=Oo.REJECTION_EVENT,PE=Oo.SUBCLASSING,Lo=nf.getterFor(gs),AE=nf.set,$i=bs&&bs.prototype,Xt=bs,ps=$i,lf=Ot.TypeError,Mo=Ot.document,Vo=Ot.process,Co=of.f,wE=Co,kE=!!(Mo&&Mo.createEvent&&Ot.dispatchEvent),cf="unhandledrejection",RE="rejectionhandled",ef=0,df=1,$E=2,_o=1,pf=2,hs,tf,LE,rf,hf=function(a){var e;return SE(a)&&fs(e=a.then)?e:!1},ff=function(a,e){var t=e.value,i=e.state===df,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{r?(i||(e.rejection===pf&&CE(e),e.rejection=_o),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===a.promise?n(new lf("Promise-chain cycle")):(c=hf(u))?Ci(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},mf=function(a,e){a.notified||(a.notified=!0,Bo(function(){for(var t=a.reactions,i;i=t.get();)ff(i,a);a.notified=!1,e&&!a.rejection&&ME(a)}))},bf=function(a,e,t){var i,r;kE?(i=Mo.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Ot.dispatchEvent(i)):i={promise:e,reason:t},!xE&&(r=Ot["on"+a])?r(i):a===cf&&TE("Unhandled promise rejection",t)},ME=function(a){Ci(sf,Ot,function(){var e=a.facade,t=a.value,i=af(a),r;if(i&&(r=IE(function(){ms?Vo.emit("unhandledRejection",t,e):bf(cf,e,t)}),a.rejection=ms||af(a)?pf:_o,r.error))throw r.value})},af=function(a){return a.rejection!==_o&&!a.parent},CE=function(a){Ci(sf,Ot,function(){var e=a.facade;ms?Vo.emit("rejectionHandled",e):bf(RE,e,a.value)})},Li=function(a,e,t){return function(i){a(e,i,t)}},Mi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=$E,mf(a,!0))},Do=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new lf("Promise can't be resolved itself");var i=hf(e);i?Bo(function(){var r={done:!1};try{Ci(i,e,Li(Do,r,a),Li(Mi,r,a))}catch(s){Mi(r,s,a)}}):(a.value=e,a.state=df,mf(a,!1))}catch(r){Mi({done:!1},r,a)}}};if(uf&&(Xt=function(e){vE(this,ps),gE(e),Ci(hs,this);var t=Lo(this);try{e(Li(Do,t),Li(Mi,t))}catch(i){Mi(t,i)}},ps=Xt.prototype,hs=function(e){AE(this,{type:gs,done:!1,notified:!1,parent:!1,reactions:new EE,rejection:!1,state:ef,value:void 0})},hs.prototype=Xh(ps,"then",function(e,t){var i=Lo(this),r=Co(yE(this,Xt));return i.parent=!0,r.ok=fs(e)?e:!0,r.fail=fs(t)&&t,r.domain=ms?Vo.domain:void 0,i.state===ef?i.reactions.add(r):Bo(function(){ff(r,i)}),r.promise}),tf=function(){var a=new hs,e=Lo(a);this.promise=a,this.resolve=Li(Do,e),this.reject=Li(Mi,e)},of.f=Co=function(a){return a===Xt||a===LE?new tf(a):wE(a)},!fE&&fs(bs)&&$i!==Object.prototype)){rf=$i.then,PE||Xh($i,"then",function(e,t){var i=this;return new Xt(function(r,s){Ci(rf,i,r,s)}).then(e,t)},{unsafe:!0});try{delete $i.constructor}catch(a){}Zh&&Zh($i,ps)}hE({global:!0,constructor:!0,wrap:!0,forced:uf},{Promise:Xt});mE(Xt,gs,!1,!0);bE(gs)});var If=b((Wk,Tf)=>{"use strict";var DE=Se(),vf=DE("iterator"),yf=!1;try{Sf=0,No={next:function(){return{done:!!Sf++}},return:function(){yf=!0}},No[vf]=function(){return this},Array.from(No,function(){throw 2})}catch(a){}var Sf,No;Tf.exports=function(a,e){try{if(!e&&!yf)return!1}catch(r){return!1}var t=!1;try{var i={};i[vf]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Fo=b((Yk,Ef)=>{"use strict";var BE=Jt(),OE=If(),VE=ki().CONSTRUCTOR;Ef.exports=VE||!OE(function(a){BE.all(a).then(void 0,function(){})})});var xf=b(()=>{"use strict";var _E=Fe(),NE=Me(),FE=bt(),qE=Ri(),UE=ds(),HE=ss(),jE=Fo();_E({target:"Promise",stat:!0,forced:jE},{all:function(e){var t=this,i=qE.f(t),r=i.resolve,s=i.reject,n=UE(function(){var o=FE(t.resolve),u=[],c=0,l=1;HE(e,function(d){var p=c++,h=!1;l++,NE(o,t,d).then(function(m){h||(h=!0,u[p]=m,--l||r(u))},s)}),--l||r(u)});return n.error&&s(n.value),i.promise}})});var Af=b(()=>{"use strict";var GE=Fe(),WE=Je(),YE=ki().CONSTRUCTOR,Uo=Jt(),QE=mt(),zE=ne(),KE=Pi(),Pf=Uo&&Uo.prototype;GE({target:"Promise",proto:!0,forced:YE,real:!0},{catch:function(a){return this.then(void 0,a)}});!WE&&zE(Uo)&&(qo=QE("Promise").prototype.catch,Pf.catch!==qo&&KE(Pf,"catch",qo,{unsafe:!0}));var qo});var wf=b(()=>{"use strict";var JE=Fe(),XE=Me(),ZE=bt(),ex=Ri(),tx=ds(),ix=ss(),rx=Fo();JE({target:"Promise",stat:!0,forced:rx},{race:function(e){var t=this,i=ex.f(t),r=i.reject,s=tx(function(){var n=ZE(t.resolve);ix(e,function(o){XE(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var kf=b(()=>{"use strict";var ax=Fe(),sx=Ri(),nx=ki().CONSTRUCTOR;ax({target:"Promise",stat:!0,forced:nx},{reject:function(e){var t=sx.f(this),i=t.reject;return i(e),t.promise}})});var Ho=b((iR,Rf)=>{"use strict";var ox=st(),ux=_e(),lx=Ri();Rf.exports=function(a,e){if(ox(a),ux(e)&&e.constructor===a)return e;var t=lx.f(a),i=t.resolve;return i(e),t.promise}});var Mf=b(()=>{"use strict";var cx=Fe(),dx=mt(),$f=Je(),px=Jt(),Lf=ki().CONSTRUCTOR,hx=Ho(),fx=dx("Promise"),mx=$f&&!Lf;cx({target:"Promise",stat:!0,forced:$f||Lf},{resolve:function(e){return hx(mx&&this===fx?px:this,e)}})});var Cf=b(()=>{"use strict";gf();xf();Af();wf();kf();Mf()});var Vf=b(()=>{"use strict";var bx=Fe(),gx=Je(),Ss=Jt(),Sx=Le(),Bf=mt(),Of=ne(),vx=po(),Df=Ho(),yx=Pi(),Go=Ss&&Ss.prototype,Tx=!!Ss&&Sx(function(){Go.finally.call({then:function(){}},function(){})});bx({target:"Promise",proto:!0,real:!0,forced:Tx},{finally:function(a){var e=vx(this,Bf("Promise")),t=Of(a);return this.then(t?function(i){return Df(e,a()).then(function(){return i})}:a,t?function(i){return Df(e,a()).then(function(){throw i})}:a)}});!gx&&Of(Ss)&&(jo=Bf("Promise").prototype.finally,Go.finally!==jo&&yx(Go,"finally",jo,{unsafe:!0}));var jo});var vs=b((lR,_f)=>{"use strict";var Ix=mt();_f.exports=Ix});var Ff=b((cR,Nf)=>{"use strict";Gp();Cf();Vf();var Ex=vs();Nf.exports=Ex("Promise","finally")});var Uf=b((dR,qf)=>{"use strict";var xx=Ff();qf.exports=xx});var ys=b((pR,Hf)=>{"use strict";var Px=Uf();Hf.exports=Px});var Zf=b(()=>{"use strict";var Cx=Fe(),Dx=cr(),Bx=Ka(),Ox=za(),Vx=ln();Cx({target:"Array",proto:!0},{at:function(e){var t=Dx(this),i=Bx(t),r=Ox(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});Vx("at")});var tm=b((c$,em)=>{"use strict";Zf();var _x=vs();em.exports=_x("Array","at")});var rm=b((d$,im)=>{"use strict";var Nx=tm();im.exports=Nx});var kr=b((p$,am)=>{"use strict";var Fx=rm();am.exports=Fx});var Km=b(()=>{"use strict"});var Jm=b(()=>{"use strict"});var Zm=b((eD,Xm)=>{"use strict";var yP=_e(),TP=gi(),IP=Se(),EP=IP("match");Xm.exports=function(a){var e;return yP(a)&&((e=a[EP])!==void 0?!!e:TP(a)==="RegExp")}});var tb=b((tD,eb)=>{"use strict";var xP=br(),PP=String;eb.exports=function(a){if(xP(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return PP(a)}});var rb=b((iD,ib)=>{"use strict";var AP=st();ib.exports=function(){var a=AP(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 nb=b((rD,sb)=>{"use strict";var wP=Me(),kP=Xe(),RP=nr(),$P=rb(),ab=RegExp.prototype;sb.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in ab)&&!kP(a,"flags")&&RP(ab,a)?wP($P,a):e}});var ub=b((aD,ob)=>{"use strict";var fu=Ie(),LP=cr(),MP=Math.floor,pu=fu("".charAt),CP=fu("".replace),hu=fu("".slice),DP=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,BP=/\$([$&'`]|\d{1,2})/g;ob.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=BP;return r!==void 0&&(r=LP(r),u=DP),CP(s,u,function(c,l){var d;switch(pu(l,0)){case"$":return"$";case"&":return a;case"`":return hu(e,0,t);case"'":return hu(e,n);case"<":d=r[hu(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=MP(p/10);return h===0?c:h<=o?i[h-1]===void 0?pu(l,1):i[h-1]+pu(l,1):c}d=i[p-1]}return d===void 0?"":d})}});var db=b(()=>{"use strict";var OP=Fe(),VP=Me(),bu=Ie(),lb=ar(),_P=ne(),NP=Si(),FP=Zm(),Hi=tb(),qP=ur(),UP=nb(),HP=ub(),jP=Se(),GP=Je(),WP=jP("replace"),YP=TypeError,mu=bu("".indexOf),QP=bu("".replace),cb=bu("".slice),zP=Math.max;OP({target:"String",proto:!0},{replaceAll:function(e,t){var i=lb(this),r,s,n,o,u,c,l,d,p,h,m=0,g="";if(!NP(e)){if(r=FP(e),r&&(s=Hi(lb(UP(e))),!~mu(s,"g")))throw new YP("`.replaceAll` does not allow non-global regexes");if(n=qP(e,WP),n)return VP(n,e,i,t);if(GP&&r)return QP(Hi(i),e,t)}for(o=Hi(i),u=Hi(e),c=_P(t),c||(t=Hi(t)),l=u.length,d=zP(1,l),p=mu(o,u);p!==-1;)h=c?Hi(t(u,p,o)):HP(u,o,p,[],void 0,t),g+=cb(o,m,p)+h,m=p+l,p=p+d>o.length?-1:mu(o,u,p+d);return m<o.length&&(g+=cb(o,m)),g}})});var hb=b((oD,pb)=>{"use strict";Km();Jm();db();var KP=vs();pb.exports=KP("String","replaceAll")});var mb=b((uD,fb)=>{"use strict";var JP=hb();fb.exports=JP});var gb=b((lD,bb)=>{"use strict";var XP=mb();bb.exports=XP});var bA={};mg(bA,{ChromecastState:()=>ir,HttpConnectionType:()=>Va,Observable:()=>dt.Observable,PlaybackState:()=>ge,Player:()=>Ea,SDK_VERSION:()=>mA,Subject:()=>dt.Subject,Subscription:()=>dt.Subscription,Surface:()=>_a,VERSION:()=>nn,ValueSubject:()=>dt.ValueSubject,VideoFormat:()=>ft,VideoQuality:()=>dt.VideoQuality});module.exports=bg(bA);var nn="2.0.115-dev.c6f77ae4.0";var ge=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ge||{}),ft=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(ft||{});var ir=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(ir||{}),Va=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Va||{});var _a=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(_a||{});var _=require("@vkontakte/videoplayer-shared");var fl=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Na=class{constructor(e){this.connection$=new _.ValueSubject(void 0);this.castState$=new _.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new _.Subject;this.realCastState$=new _.ValueSubject("NOT_AVAILABLE");this.subscription=new _.Subscription;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 i=(0,_.isNonNullable)((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},r||fl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:_.ErrorCategory.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 i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,_.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,_.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,_.isNullable)(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),i=cast.framework.CastContext.getInstance();this.subscription.add((0,_.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,_.assertNever)(r.sessionState)}})).add((0,_.merge)((0,_.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,_.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,_.map)(r=>r.castState)),(0,_.observableFrom)([i.getCastState()])).pipe((0,_.filterChanged)(),(0,_.map)(gg),(0,_.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=(0,_.isNonNullable)(this.connection$.getValue());if(s&&!n){let c=i.getCurrentSession();(0,_.assertNonNullable)(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,_.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,_.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:_.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},gg=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(0,_.assertNever)(a)}};var Fb=ze(no(),1);var Yf=ze(ys(),1);var Wo=require("@vkontakte/videoplayer-shared");var fe=(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 i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Wo.assertNever)(t)}return a},Yo=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Wo.assertNever)(e)}};var k=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var nt=require("@vkontakte/videoplayer-shared"),H=class{constructor(e){this.transitionStarted$=new nt.Subject;this.transitionEnded$=new nt.Subject;this.transitionUpdated$=new nt.Subject;this.forceChanged$=new nt.Subject;this.stateChangeStarted$=(0,nt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,nt.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,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:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,nt.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var jf=require("@vkontakte/videoplayer-shared"),Gf=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(0,jf.assertNever)(a)}};var $=require("@vkontakte/videoplayer-shared");var Ax=5,wx=5,kx=500,Wf=7e3,wr=class{constructor(e){this.subscription=new $.Subscription;this.loadMediaTimeoutSubscription=new $.Subscription;this.videoState=new H("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,$.assertNever)(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:(0,$.assertNever)(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:(0,$.assertNever)(e)}break}default:(0,$.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Gf(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 $.Subscription;this.subscription.add(e),this.subscription.add((0,$.merge)(this.videoState.stateChangeStarted$.pipe((0,$.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,$.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new $.Subject;e.add(r.pipe((0,$.debounce)(kx)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,$.fromEvent)(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)>Ax)&&r.next(o),s=o})),e.add((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.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<wx&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(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:(0,$.assertNever)(n)}}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,$.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,$.observableFrom)(["init"])).pipe((0,$.debounce)(0));t(i,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"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?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),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(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"),k(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"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var c;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let l=t[e];(0,$.assertNonNullable)(l);let d=(0,$.getHighestQuality)(Object.keys(l));(0,$.assertNonNullable)(d);let p=l[d];(0,$.assertNonNullable)(p),i=p,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];(0,$.assertNonNullable)(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];(0,$.assertNonNullable)(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,$.assertNonNullable)(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,$.assertNonNullable)(l),i=fe(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:$.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,$.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((c=this.params.meta.videoId)!=null?c:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,$.isNonNullable)(o)&&(n.metadata.title=o),(0,$.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add((0,$.timeout)(Wf).subscribe(()=>s(`timeout(${Wf})`)))});(0,Yf.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:$.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Jo=require("@vkontakte/videoplayer-shared");var Qf=require("@vkontakte/videoplayer-shared"),zf=a=>{try{a.pause(),a.playbackRate=0,(0,Qf.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Ts=require("@vkontakte/videoplayer-shared"),Qo=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)}},zo=window.WeakMap?new WeakMap:new Qo,Ko=window.WeakMap?new WeakMap:new Map,Rx=(a,e=20)=>{let t=0;return(0,Ts.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ee=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),i=!!t;t?(0,Jo.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),zo.set(t,i);let r=new Ts.Subscription;return r.add(Rx(t,e)),Ko.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},xe=a=>{let e=Ko.get(a);e==null||e.unsubscribe(),Ko.delete(a);let t=zo.get(a);zo.delete(a),t?(0,Jo.clearVideoElement)(a):zf(a)};var L=require("@vkontakte/videoplayer-shared");var Vt=require("@vkontakte/videoplayer-shared"),Is=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Vt.isNullable)(r),c=new Vt.Subscription;return r&&c.add(r.subscribe(l=>{let d=a.getState();i(l,d)&&a.setState(l)},s)),i(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(l=>{t(l.to),u&&a.setState(l.to)},s)),c},ot=(a,e,t)=>Is(e,()=>a.loop,i=>{(0,Vt.isNonNullable)(i)&&(a.loop=i)},{onError:t}),Pe=(a,e,t,i)=>Is(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,Vt.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),qe=(a,e,t,i)=>Is(e,()=>a.playbackRate,r=>{(0,Vt.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),_t=Is;var $x=a=>["__",a.language,a.label].join("|"),Lx=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Xo=class a{constructor(){this.available$=new L.Subject;this.current$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.subscription=new L.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:L.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(_t(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,L.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(_t(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,L.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(_t(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:r})),this.subscription.add(_t(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,L.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"addtrack"),(0,L.fromEvent)(e,"removetrack"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,L.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"change"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,L.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,L.filterChanged)()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var c,l,d,p,h;let u=(l=(c=o.target)==null?void 0:c.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,L.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,L.isNonNullable)(t.align)&&(r.align=t.align),(0,L.isNonNullable)(t.position)&&(r.position=t.position),(0,L.isNonNullable)(t.size)&&(r.size=t.size),(0,L.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,c,l;let{language:t,label:i}=e,r=e.id?e.id:$x(e),s=this.externalTracks.has(r),n=(s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)||r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(l=this.internalTracks.get(r))==null?void 0:l.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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!Lx(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){(0,L.assertNonNullable)(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){(0,L.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.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)}},Ue=Xo;var vt=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 Kf=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},Zo=a=>{let e=Kf(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Jf=a=>{let e=Kf(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var M=require("@vkontakte/videoplayer-shared");var Mx=3,Xf=(a,e,t=Mx)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Ae=a=>{let e=T=>(0,M.fromEvent)(a,T).pipe((0,M.mapTo)(void 0)),i=(0,M.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>(0,M.fromEvent)(a,T))).pipe((0,M.map)(T=>T.type==="ended"?a.readyState<2:a.readyState<3),(0,M.filterChanged)()),r=(0,M.merge)((0,M.fromEvent)(a,"progress"),(0,M.fromEvent)(a,"timeupdate")).pipe((0,M.map)(()=>Xf(a.buffered,a.currentTime))),s=M.clientChecker.isSafari?(0,M.combine)({play:e("play").pipe((0,M.once)()),playing:e("playing")}).pipe((0,M.mapTo)(void 0)):e("playing"),n=(0,M.fromEvent)(a,"volumechange").pipe((0,M.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,M.fromEvent)(a,"ratechange").pipe((0,M.map)(()=>a.playbackRate)),u=(0,M.fromEvent)(a,"error").pipe((0,M.filter)(()=>!!(a.error||a.played.length)),(0,M.map)(()=>{var P;let T=a.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:M.ErrorCategory.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(P=a.error)!=null?P:void 0}})),c=(0,M.fromEvent)(a,"timeupdate").pipe((0,M.map)(()=>a.currentTime)),l=new M.Subject,d=.3,p;c.subscribe(T=>{a.loop&&(0,M.isNonNullable)(p)&&(0,M.isNonNullable)(T)&&p>=a.duration-d&&T<=d&&l.next(p),p=T});let h=e("pause").pipe((0,M.filter)(()=>!a.error&&p!==a.duration)),m=(0,M.fromEvent)(a,"enterpictureinpicture"),g=(0,M.fromEvent)(a,"leavepictureinpicture"),S=new M.ValueSubject(Jf(a));m.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let x=new M.ValueSubject(Zo(a));return(0,M.fromEvent)(a,"fullscreenchange").pipe((0,M.map)(()=>Zo(a))).subscribe(x),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,M.fromEvent)(a,"durationchange").pipe((0,M.map)(()=>a.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:x}};var yt=require("@vkontakte/videoplayer-shared"),Nt=a=>{switch(a){case"mobile":return yt.VideoQuality.Q_144P;case"lowest":return yt.VideoQuality.Q_240P;case"low":return yt.VideoQuality.Q_360P;case"sd":case"medium":return yt.VideoQuality.Q_480P;case"hd":case"high":return yt.VideoQuality.Q_720P;case"fullhd":case"full":return yt.VideoQuality.Q_1080P;case"quadhd":case"quad":return yt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return yt.VideoQuality.Q_2160P}};var Zt=ze(kr(),1),C=require("@vkontakte/videoplayer-shared");var eu=!1,Tt={},sm=a=>{eu=a},nm=()=>{Tt={}},om=a=>{a(Tt)},Rr=(a,e)=>{var t;eu&&(Tt.meta=(t=Tt.meta)!=null?t:{},Tt.meta[a]=e)},ve=class{constructor(e){this.name=e}next(e){var i,r;if(!eu)return;Tt.series=(i=Tt.series)!=null?i:{};let t=(r=Tt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Tt.series[this.name]=t}};var qx=new ve("best_bitrate"),lm=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var tu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),$r=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,C.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},cm='Assertion "ABR Tracks is empty array" failed',Es=(a,e,t,i)=>{var u;let r=[...e].sort(tu(1)),s=[...t].sort(tu(1)),n=s.filter(c=>(0,C.isNonNullable)(c.bitrate)&&(0,C.isNonNullable)(a.bitrate)?a.bitrate/c.bitrate>i:!0),o=(u=(0,Zt.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Zt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Zt.default)(n,-1):(0,Zt.default)(s,0)},um=a=>"quality"in a,dm=(a,e,t,i)=>{var n;let r=(0,C.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,C.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,C.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=um(o)?"video":"audio",c=um(o)?o.quality:o.bitrate;return e({message:`
|
|
7
|
-
[last ${u} selected] ${
|
|
8
|
-
`}),o}return i==null||i.recordSwitch(t),t},
|
|
6
|
+
"use strict";var lg=Object.create;var Va=Object.defineProperty;var cg=Object.getOwnPropertyDescriptor;var dg=Object.getOwnPropertyNames;var pg=Object.getPrototypeOf,hg=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),fg=(a,e)=>{for(var t in e)Va(a,t,{get:e[t],enumerable:!0})},pl=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of dg(e))!hg.call(a,r)&&r!==t&&Va(a,r,{get:()=>e[r],enumerable:!(i=cg(e,r))||i.enumerable});return a};var Ne=(a,e,t)=>(t=a!=null?lg(pg(a)):{},pl(e||!a||!a.__esModule?Va(t,"default",{value:a,enumerable:!0}):t,a)),mg=a=>pl(Va({},"__esModule",{value:!0}),a);var Le=b((RA,fl)=>{"use strict";fl.exports=function(a){try{return!!a()}catch(e){return!0}}});var ar=b(($A,ml)=>{"use strict";var gg=Le();ml.exports=!gg(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Ie=b((LA,Sl)=>{"use strict";var bl=ar(),gl=Function.prototype,un=gl.call,Sg=bl&&gl.bind.bind(un,un);Sl.exports=bl?Sg:function(a){return function(){return un.apply(a,arguments)}}});var Si=b((MA,yl)=>{"use strict";var vl=Ie(),vg=vl({}.toString),yg=vl("".slice);yl.exports=function(a){return yg(vg(a),8,-1)}});var Il=b((CA,Tl)=>{"use strict";var Tg=Ie(),Ig=Le(),Eg=Si(),ln=Object,xg=Tg("".split);Tl.exports=Ig(function(){return!ln("z").propertyIsEnumerable(0)})?function(a){return Eg(a)==="String"?xg(a,""):ln(a)}:ln});var vi=b((DA,El)=>{"use strict";El.exports=function(a){return a==null}});var sr=b((BA,xl)=>{"use strict";var Pg=vi(),Ag=TypeError;xl.exports=function(a){if(Pg(a))throw new Ag("Can't call method on "+a);return a}});var yi=b((OA,Pl)=>{"use strict";var wg=Il(),kg=sr();Pl.exports=function(a){return wg(kg(a))}});var cn=b((VA,Al)=>{"use strict";Al.exports=function(){}});var Qt=b((_A,wl)=>{"use strict";wl.exports={}});var oe=b((dn,kl)=>{"use strict";var nr=function(a){return a&&a.Math===Math&&a};kl.exports=nr(typeof globalThis=="object"&&globalThis)||nr(typeof window=="object"&&window)||nr(typeof self=="object"&&self)||nr(typeof global=="object"&&global)||nr(typeof dn=="object"&&dn)||function(){return this}()||Function("return this")()});var ne=b((NA,Rl)=>{"use strict";var pn=typeof document=="object"&&document.all;Rl.exports=typeof pn=="undefined"&&pn!==void 0?function(a){return typeof a=="function"||a===pn}:function(a){return typeof a=="function"}});var Ml=b((FA,Ll)=>{"use strict";var Rg=oe(),$g=ne(),$l=Rg.WeakMap;Ll.exports=$g($l)&&/native code/.test(String($l))});var Fe=b((UA,Cl)=>{"use strict";var Lg=ne();Cl.exports=function(a){return typeof a=="object"?a!==null:Lg(a)}});var Ue=b((qA,Dl)=>{"use strict";var Mg=Le();Dl.exports=!Mg(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ua=b((HA,Ol)=>{"use strict";var Cg=oe(),Bl=Fe(),hn=Cg.document,Dg=Bl(hn)&&Bl(hn.createElement);Ol.exports=function(a){return Dg?hn.createElement(a):{}}});var fn=b((jA,Vl)=>{"use strict";var Bg=Ue(),Og=Le(),Vg=Ua();Vl.exports=!Bg&&!Og(function(){return Object.defineProperty(Vg("div"),"a",{get:function(){return 7}}).a!==7})});var mn=b((GA,_l)=>{"use strict";var _g=Ue(),Ng=Le();_l.exports=_g&&Ng(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var st=b((WA,Nl)=>{"use strict";var Fg=Fe(),Ug=String,qg=TypeError;Nl.exports=function(a){if(Fg(a))return a;throw new qg(Ug(a)+" is not an object")}});var Me=b((YA,Fl)=>{"use strict";var Hg=ar(),qa=Function.prototype.call;Fl.exports=Hg?qa.bind(qa):function(){return qa.apply(qa,arguments)}});var Ha=b((QA,Ul)=>{"use strict";Ul.exports={}});var mt=b((zA,Hl)=>{"use strict";var bn=Ha(),gn=oe(),jg=ne(),ql=function(a){return jg(a)?a:void 0};Hl.exports=function(a,e){return arguments.length<2?ql(bn[a])||ql(gn[a]):bn[a]&&bn[a][e]||gn[a]&&gn[a][e]}});var or=b((KA,jl)=>{"use strict";var Gg=Ie();jl.exports=Gg({}.isPrototypeOf)});var Ti=b((JA,Yl)=>{"use strict";var Wg=oe(),Gl=Wg.navigator,Wl=Gl&&Gl.userAgent;Yl.exports=Wl?String(Wl):""});var vn=b((XA,Zl)=>{"use strict";var Xl=oe(),Sn=Ti(),Ql=Xl.process,zl=Xl.Deno,Kl=Ql&&Ql.versions||zl&&zl.version,Jl=Kl&&Kl.v8,Ke,ja;Jl&&(Ke=Jl.split("."),ja=Ke[0]>0&&Ke[0]<4?1:+(Ke[0]+Ke[1]));!ja&&Sn&&(Ke=Sn.match(/Edge\/(\d+)/),(!Ke||Ke[1]>=74)&&(Ke=Sn.match(/Chrome\/(\d+)/),Ke&&(ja=+Ke[1])));Zl.exports=ja});var yn=b((ZA,tc)=>{"use strict";var ec=vn(),Yg=Le(),Qg=oe(),zg=Qg.String;tc.exports=!!Object.getOwnPropertySymbols&&!Yg(function(){var a=Symbol("symbol detection");return!zg(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&ec&&ec<41})});var Tn=b((ew,ic)=>{"use strict";var Kg=yn();ic.exports=Kg&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var In=b((tw,rc)=>{"use strict";var Jg=mt(),Xg=ne(),Zg=or(),eS=Tn(),tS=Object;rc.exports=eS?function(a){return typeof a=="symbol"}:function(a){var e=Jg("Symbol");return Xg(e)&&Zg(e.prototype,tS(a))}});var ur=b((iw,ac)=>{"use strict";var iS=String;ac.exports=function(a){try{return iS(a)}catch(e){return"Object"}}});var bt=b((rw,sc)=>{"use strict";var rS=ne(),aS=ur(),sS=TypeError;sc.exports=function(a){if(rS(a))return a;throw new sS(aS(a)+" is not a function")}});var lr=b((aw,nc)=>{"use strict";var nS=bt(),oS=vi();nc.exports=function(a,e){var t=a[e];return oS(t)?void 0:nS(t)}});var uc=b((sw,oc)=>{"use strict";var En=Me(),xn=ne(),Pn=Fe(),uS=TypeError;oc.exports=function(a,e){var t,i;if(e==="string"&&xn(t=a.toString)&&!Pn(i=En(t,a))||xn(t=a.valueOf)&&!Pn(i=En(t,a))||e!=="string"&&xn(t=a.toString)&&!Pn(i=En(t,a)))return i;throw new uS("Can't convert object to primitive value")}});var Je=b((nw,lc)=>{"use strict";lc.exports=!0});var pc=b((ow,dc)=>{"use strict";var cc=oe(),lS=Object.defineProperty;dc.exports=function(a,e){try{lS(cc,a,{value:e,configurable:!0,writable:!0})}catch(t){cc[a]=e}return e}});var cr=b((uw,mc)=>{"use strict";var cS=Je(),dS=oe(),pS=pc(),hc="__core-js_shared__",fc=mc.exports=dS[hc]||pS(hc,{});(fc.versions||(fc.versions=[])).push({version:"3.38.0",mode:cS?"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 An=b((lw,gc)=>{"use strict";var bc=cr();gc.exports=function(a,e){return bc[a]||(bc[a]=e||{})}});var dr=b((cw,Sc)=>{"use strict";var hS=sr(),fS=Object;Sc.exports=function(a){return fS(hS(a))}});var Xe=b((dw,vc)=>{"use strict";var mS=Ie(),bS=dr(),gS=mS({}.hasOwnProperty);vc.exports=Object.hasOwn||function(e,t){return gS(bS(e),t)}});var wn=b((pw,yc)=>{"use strict";var SS=Ie(),vS=0,yS=Math.random(),TS=SS(1 .toString);yc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+TS(++vS+yS,36)}});var Se=b((hw,Ic)=>{"use strict";var IS=oe(),ES=An(),Tc=Xe(),xS=wn(),PS=yn(),AS=Tn(),Ii=IS.Symbol,kn=ES("wks"),wS=AS?Ii.for||Ii:Ii&&Ii.withoutSetter||xS;Ic.exports=function(a){return Tc(kn,a)||(kn[a]=PS&&Tc(Ii,a)?Ii[a]:wS("Symbol."+a)),kn[a]}});var Ac=b((fw,Pc)=>{"use strict";var kS=Me(),Ec=Fe(),xc=In(),RS=lr(),$S=uc(),LS=Se(),MS=TypeError,CS=LS("toPrimitive");Pc.exports=function(a,e){if(!Ec(a)||xc(a))return a;var t=RS(a,CS),i;if(t){if(e===void 0&&(e="default"),i=kS(t,a,e),!Ec(i)||xc(i))return i;throw new MS("Can't convert object to primitive value")}return e===void 0&&(e="number"),$S(a,e)}});var Rn=b((mw,wc)=>{"use strict";var DS=Ac(),BS=In();wc.exports=function(a){var e=DS(a,"string");return BS(e)?e:e+""}});var zt=b(Rc=>{"use strict";var OS=Ue(),VS=fn(),_S=mn(),Ga=st(),kc=Rn(),NS=TypeError,$n=Object.defineProperty,FS=Object.getOwnPropertyDescriptor,Ln="enumerable",Mn="configurable",Cn="writable";Rc.f=OS?_S?function(e,t,i){if(Ga(e),t=kc(t),Ga(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Cn in i&&!i[Cn]){var r=FS(e,t);r&&r[Cn]&&(e[t]=i.value,i={configurable:Mn in i?i[Mn]:r[Mn],enumerable:Ln in i?i[Ln]:r[Ln],writable:!1})}return $n(e,t,i)}:$n:function(e,t,i){if(Ga(e),t=kc(t),Ga(i),VS)try{return $n(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new NS("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var pr=b((gw,$c)=>{"use strict";$c.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Ei=b((Sw,Lc)=>{"use strict";var US=Ue(),qS=zt(),HS=pr();Lc.exports=US?function(a,e,t){return qS.f(a,e,HS(1,t))}:function(a,e,t){return a[e]=t,a}});var Wa=b((vw,Cc)=>{"use strict";var jS=An(),GS=wn(),Mc=jS("keys");Cc.exports=function(a){return Mc[a]||(Mc[a]=GS(a))}});var Ya=b((yw,Dc)=>{"use strict";Dc.exports={}});var Vn=b((Tw,Vc)=>{"use strict";var WS=Ml(),Oc=oe(),YS=Fe(),QS=Ei(),Dn=Xe(),Bn=cr(),zS=Wa(),KS=Ya(),Bc="Object already initialized",On=Oc.TypeError,JS=Oc.WeakMap,Qa,hr,za,XS=function(a){return za(a)?hr(a):Qa(a,{})},ZS=function(a){return function(e){var t;if(!YS(e)||(t=hr(e)).type!==a)throw new On("Incompatible receiver, "+a+" required");return t}};WS||Bn.state?(Ze=Bn.state||(Bn.state=new JS),Ze.get=Ze.get,Ze.has=Ze.has,Ze.set=Ze.set,Qa=function(a,e){if(Ze.has(a))throw new On(Bc);return e.facade=a,Ze.set(a,e),e},hr=function(a){return Ze.get(a)||{}},za=function(a){return Ze.has(a)}):(Kt=zS("state"),KS[Kt]=!0,Qa=function(a,e){if(Dn(a,Kt))throw new On(Bc);return e.facade=a,QS(a,Kt,e),e},hr=function(a){return Dn(a,Kt)?a[Kt]:{}},za=function(a){return Dn(a,Kt)});var Ze,Kt;Vc.exports={set:Qa,get:hr,has:za,enforce:XS,getterFor:ZS}});var _n=b((Iw,Uc)=>{"use strict";var ev=ar(),Fc=Function.prototype,_c=Fc.apply,Nc=Fc.call;Uc.exports=typeof Reflect=="object"&&Reflect.apply||(ev?Nc.bind(_c):function(){return Nc.apply(_c,arguments)})});var Nn=b((Ew,qc)=>{"use strict";var tv=Si(),iv=Ie();qc.exports=function(a){if(tv(a)==="Function")return iv(a)}});var Wc=b(Gc=>{"use strict";var Hc={}.propertyIsEnumerable,jc=Object.getOwnPropertyDescriptor,rv=jc&&!Hc.call({1:2},1);Gc.f=rv?function(e){var t=jc(this,e);return!!t&&t.enumerable}:Hc});var zc=b(Qc=>{"use strict";var av=Ue(),sv=Me(),nv=Wc(),ov=pr(),uv=yi(),lv=Rn(),cv=Xe(),dv=fn(),Yc=Object.getOwnPropertyDescriptor;Qc.f=av?Yc:function(e,t){if(e=uv(e),t=lv(t),dv)try{return Yc(e,t)}catch(i){}if(cv(e,t))return ov(!sv(nv.f,e,t),e[t])}});var Fn=b((Aw,Kc)=>{"use strict";var pv=Le(),hv=ne(),fv=/#|\.prototype\./,fr=function(a,e){var t=bv[mv(a)];return t===Sv?!0:t===gv?!1:hv(e)?pv(e):!!e},mv=fr.normalize=function(a){return String(a).replace(fv,".").toLowerCase()},bv=fr.data={},gv=fr.NATIVE="N",Sv=fr.POLYFILL="P";Kc.exports=fr});var mr=b((ww,Xc)=>{"use strict";var Jc=Nn(),vv=bt(),yv=ar(),Tv=Jc(Jc.bind);Xc.exports=function(a,e){return vv(a),e===void 0?a:yv?Tv(a,e):function(){return a.apply(e,arguments)}}});var qe=b((kw,ed)=>{"use strict";var br=oe(),Iv=_n(),Ev=Nn(),xv=ne(),Pv=zc().f,Av=Fn(),xi=Ha(),wv=mr(),Pi=Ei(),Zc=Xe();cr();var kv=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return Iv(a,this,arguments)};return e.prototype=a.prototype,e};ed.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?br:r?br[t]:br[t]&&br[t].prototype,o=i?xi:xi[t]||Pi(xi,t,{})[t],u=o.prototype,l,c,d,h,p,m,g,S,x;for(h in e)l=Av(i?h:t+(r?".":"#")+h,a.forced),c=!l&&n&&Zc(n,h),m=o[h],c&&(a.dontCallGetSet?(x=Pv(n,h),g=x&&x.value):g=n[h]),p=c&&g?g:e[h],!(!l&&!s&&typeof m==typeof p)&&(a.bind&&c?S=wv(p,br):a.wrap&&c?S=kv(p):s&&xv(p)?S=Ev(p):S=p,(a.sham||p&&p.sham||m&&m.sham)&&Pi(S,"sham",!0),Pi(o,h,S),s&&(d=t+"Prototype",Zc(xi,d)||Pi(xi,d,{}),Pi(xi[d],h,p),a.real&&u&&(l||!u[h])&&Pi(u,h,p)))}});var rd=b((Rw,id)=>{"use strict";var Un=Ue(),Rv=Xe(),td=Function.prototype,$v=Un&&Object.getOwnPropertyDescriptor,qn=Rv(td,"name"),Lv=qn&&function(){}.name==="something",Mv=qn&&(!Un||Un&&$v(td,"name").configurable);id.exports={EXISTS:qn,PROPER:Lv,CONFIGURABLE:Mv}});var sd=b(($w,ad)=>{"use strict";var Cv=Math.ceil,Dv=Math.floor;ad.exports=Math.trunc||function(e){var t=+e;return(t>0?Dv:Cv)(t)}});var Ka=b((Lw,nd)=>{"use strict";var Bv=sd();nd.exports=function(a){var e=+a;return e!==e||e===0?0:Bv(e)}});var ud=b((Mw,od)=>{"use strict";var Ov=Ka(),Vv=Math.max,_v=Math.min;od.exports=function(a,e){var t=Ov(a);return t<0?Vv(t+e,0):_v(t,e)}});var cd=b((Cw,ld)=>{"use strict";var Nv=Ka(),Fv=Math.min;ld.exports=function(a){var e=Nv(a);return e>0?Fv(e,9007199254740991):0}});var Ja=b((Dw,dd)=>{"use strict";var Uv=cd();dd.exports=function(a){return Uv(a.length)}});var fd=b((Bw,hd)=>{"use strict";var qv=yi(),Hv=ud(),jv=Ja(),pd=function(a){return function(e,t,i){var r=qv(e),s=jv(r);if(s===0)return!a&&-1;var n=Hv(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};hd.exports={includes:pd(!0),indexOf:pd(!1)}});var gd=b((Ow,bd)=>{"use strict";var Gv=Ie(),Hn=Xe(),Wv=yi(),Yv=fd().indexOf,Qv=Ya(),md=Gv([].push);bd.exports=function(a,e){var t=Wv(a),i=0,r=[],s;for(s in t)!Hn(Qv,s)&&Hn(t,s)&&md(r,s);for(;e.length>i;)Hn(t,s=e[i++])&&(~Yv(r,s)||md(r,s));return r}});var jn=b((Vw,Sd)=>{"use strict";Sd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var yd=b((_w,vd)=>{"use strict";var zv=gd(),Kv=jn();vd.exports=Object.keys||function(e){return zv(e,Kv)}});var Id=b(Td=>{"use strict";var Jv=Ue(),Xv=mn(),Zv=zt(),ey=st(),ty=yi(),iy=yd();Td.f=Jv&&!Xv?Object.defineProperties:function(e,t){ey(e);for(var i=ty(t),r=iy(t),s=r.length,n=0,o;s>n;)Zv.f(e,o=r[n++],i[o]);return e}});var Gn=b((Fw,Ed)=>{"use strict";var ry=mt();Ed.exports=ry("document","documentElement")});var zn=b((Uw,$d)=>{"use strict";var ay=st(),sy=Id(),xd=jn(),ny=Ya(),oy=Gn(),uy=Ua(),ly=Wa(),Pd=">",Ad="<",Yn="prototype",Qn="script",kd=ly("IE_PROTO"),Wn=function(){},Rd=function(a){return Ad+Qn+Pd+a+Ad+"/"+Qn+Pd},wd=function(a){a.write(Rd("")),a.close();var e=a.parentWindow.Object;return a=null,e},cy=function(){var a=uy("iframe"),e="java"+Qn+":",t;return a.style.display="none",oy.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Rd("document.F=Object")),t.close(),t.F},Xa,Za=function(){try{Xa=new ActiveXObject("htmlfile")}catch(e){}Za=typeof document!="undefined"?document.domain&&Xa?wd(Xa):cy():wd(Xa);for(var a=xd.length;a--;)delete Za[Yn][xd[a]];return Za()};ny[kd]=!0;$d.exports=Object.create||function(e,t){var i;return e!==null?(Wn[Yn]=ay(e),i=new Wn,Wn[Yn]=null,i[kd]=e):i=Za(),t===void 0?i:sy.f(i,t)}});var Md=b((qw,Ld)=>{"use strict";var dy=Le();Ld.exports=!dy(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Jn=b((Hw,Dd)=>{"use strict";var py=Xe(),hy=ne(),fy=dr(),my=Wa(),by=Md(),Cd=my("IE_PROTO"),Kn=Object,gy=Kn.prototype;Dd.exports=by?Kn.getPrototypeOf:function(a){var e=fy(a);if(py(e,Cd))return e[Cd];var t=e.constructor;return hy(t)&&e instanceof t?t.prototype:e instanceof Kn?gy:null}});var Ai=b((jw,Bd)=>{"use strict";var Sy=Ei();Bd.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:Sy(a,e,t),a}});var to=b((Gw,_d)=>{"use strict";var vy=Le(),yy=ne(),Ty=Fe(),Iy=zn(),Od=Jn(),Ey=Ai(),xy=Se(),Py=Je(),eo=xy("iterator"),Vd=!1,gt,Xn,Zn;[].keys&&(Zn=[].keys(),"next"in Zn?(Xn=Od(Od(Zn)),Xn!==Object.prototype&&(gt=Xn)):Vd=!0);var Ay=!Ty(gt)||vy(function(){var a={};return gt[eo].call(a)!==a});Ay?gt={}:Py&&(gt=Iy(gt));yy(gt[eo])||Ey(gt,eo,function(){return this});_d.exports={IteratorPrototype:gt,BUGGY_SAFARI_ITERATORS:Vd}});var es=b((Ww,Fd)=>{"use strict";var wy=Se(),ky=wy("toStringTag"),Nd={};Nd[ky]="z";Fd.exports=String(Nd)==="[object z]"});var gr=b((Yw,Ud)=>{"use strict";var Ry=es(),$y=ne(),ts=Si(),Ly=Se(),My=Ly("toStringTag"),Cy=Object,Dy=ts(function(){return arguments}())==="Arguments",By=function(a,e){try{return a[e]}catch(t){}};Ud.exports=Ry?ts:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=By(e=Cy(a),My))=="string"?t:Dy?ts(e):(i=ts(e))==="Object"&&$y(e.callee)?"Arguments":i}});var Hd=b((Qw,qd)=>{"use strict";var Oy=es(),Vy=gr();qd.exports=Oy?{}.toString:function(){return"[object "+Vy(this)+"]"}});var Sr=b((zw,Gd)=>{"use strict";var _y=es(),Ny=zt().f,Fy=Ei(),Uy=Xe(),qy=Hd(),Hy=Se(),jd=Hy("toStringTag");Gd.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(Uy(r,jd)||Ny(r,jd,{configurable:!0,value:e}),i&&!_y&&Fy(r,"toString",qy))}});var Yd=b((Kw,Wd)=>{"use strict";var jy=to().IteratorPrototype,Gy=zn(),Wy=pr(),Yy=Sr(),Qy=Qt(),zy=function(){return this};Wd.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=Gy(jy,{next:Wy(+!i,t)}),Yy(a,r,!1,!0),Qy[r]=zy,a}});var zd=b((Jw,Qd)=>{"use strict";var Ky=Ie(),Jy=bt();Qd.exports=function(a,e,t){try{return Ky(Jy(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Jd=b((Xw,Kd)=>{"use strict";var Xy=Fe();Kd.exports=function(a){return Xy(a)||a===null}});var Zd=b((Zw,Xd)=>{"use strict";var Zy=Jd(),eT=String,tT=TypeError;Xd.exports=function(a){if(Zy(a))return a;throw new tT("Can't set "+eT(a)+" as a prototype")}});var io=b((ek,ep)=>{"use strict";var iT=zd(),rT=Fe(),aT=sr(),sT=Zd();ep.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=iT(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return aT(r),sT(s),rT(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var dp=b((tk,cp)=>{"use strict";var nT=qe(),oT=Me(),is=Je(),up=rd(),uT=ne(),lT=Yd(),tp=Jn(),ip=io(),cT=Sr(),dT=Ei(),ro=Ai(),pT=Se(),rp=Qt(),lp=to(),hT=up.PROPER,fT=up.CONFIGURABLE,ap=lp.IteratorPrototype,rs=lp.BUGGY_SAFARI_ITERATORS,vr=pT("iterator"),sp="keys",yr="values",np="entries",op=function(){return this};cp.exports=function(a,e,t,i,r,s,n){lT(t,e,i);var o=function(x){if(x===r&&h)return h;if(!rs&&x&&x in c)return c[x];switch(x){case sp:return function(){return new t(this,x)};case yr:return function(){return new t(this,x)};case np:return function(){return new t(this,x)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[vr]||c["@@iterator"]||r&&c[r],h=!rs&&d||o(r),p=e==="Array"&&c.entries||d,m,g,S;if(p&&(m=tp(p.call(new a)),m!==Object.prototype&&m.next&&(!is&&tp(m)!==ap&&(ip?ip(m,ap):uT(m[vr])||ro(m,vr,op)),cT(m,u,!0,!0),is&&(rp[u]=op))),hT&&r===yr&&d&&d.name!==yr&&(!is&&fT?dT(c,"name",yr):(l=!0,h=function(){return oT(d,this)})),r)if(g={values:o(yr),keys:s?h:o(sp),entries:o(np)},n)for(S in g)(rs||l||!(S in c))&&ro(c,S,g[S]);else nT({target:e,proto:!0,forced:rs||l},g);return(!is||n)&&c[vr]!==h&&ro(c,vr,h,{name:r}),rp[e]=h,g}});var hp=b((ik,pp)=>{"use strict";pp.exports=function(a,e){return{value:a,done:e}}});var so=b((rk,Sp)=>{"use strict";var mT=yi(),ao=cn(),fp=Qt(),bp=Vn(),bT=zt().f,gT=dp(),as=hp(),ST=Je(),vT=Ue(),gp="Array Iterator",yT=bp.set,TT=bp.getterFor(gp);Sp.exports=gT(Array,"Array",function(a,e){yT(this,{type:gp,target:mT(a),index:0,kind:e})},function(){var a=TT(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,as(void 0,!0);switch(a.kind){case"keys":return as(t,!1);case"values":return as(e[t],!1)}return as([t,e[t]],!1)},"values");var mp=fp.Arguments=fp.Array;ao("keys");ao("values");ao("entries");if(!ST&&vT&&mp.name!=="values")try{bT(mp,"name",{value:"values"})}catch(a){}});var yp=b((ak,vp)=>{"use strict";var IT=Se(),ET=Qt(),xT=IT("iterator"),PT=Array.prototype;vp.exports=function(a){return a!==void 0&&(ET.Array===a||PT[xT]===a)}});var no=b((sk,Ip)=>{"use strict";var AT=gr(),Tp=lr(),wT=vi(),kT=Qt(),RT=Se(),$T=RT("iterator");Ip.exports=function(a){if(!wT(a))return Tp(a,$T)||Tp(a,"@@iterator")||kT[AT(a)]}});var xp=b((nk,Ep)=>{"use strict";var LT=Me(),MT=bt(),CT=st(),DT=ur(),BT=no(),OT=TypeError;Ep.exports=function(a,e){var t=arguments.length<2?BT(a):e;if(MT(t))return CT(LT(t,a));throw new OT(DT(a)+" is not iterable")}});var wp=b((ok,Ap)=>{"use strict";var VT=Me(),Pp=st(),_T=lr();Ap.exports=function(a,e,t){var i,r;Pp(a);try{if(i=_T(a,"return"),!i){if(e==="throw")throw t;return t}i=VT(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Pp(i),t}});var ns=b((uk,Lp)=>{"use strict";var NT=mr(),FT=Me(),UT=st(),qT=ur(),HT=yp(),jT=Ja(),kp=or(),GT=xp(),WT=no(),Rp=wp(),YT=TypeError,ss=function(a,e){this.stopped=a,this.result=e},$p=ss.prototype;Lp.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=NT(e,i),l,c,d,h,p,m,g,S=function(A){return l&&Rp(l,"normal",A),new ss(!0,A)},x=function(A){return r?(UT(A),o?u(A[0],A[1],S):u(A[0],A[1])):o?u(A,S):u(A)};if(s)l=a.iterator;else if(n)l=a;else{if(c=WT(a),!c)throw new YT(qT(a)+" is not iterable");if(HT(c)){for(d=0,h=jT(a);h>d;d++)if(p=x(a[d]),p&&kp($p,p))return p;return new ss(!1)}l=GT(a,c)}for(m=s?a.next:l.next;!(g=FT(m,l)).done;){try{p=x(g.value)}catch(A){Rp(l,"throw",A)}if(typeof p=="object"&&p&&kp($p,p))return p}return new ss(!1)}});var Cp=b((lk,Mp)=>{"use strict";var QT=Ue(),zT=zt(),KT=pr();Mp.exports=function(a,e,t){QT?zT.f(a,e,KT(0,t)):a[e]=t}});var Dp=b(()=>{"use strict";var JT=qe(),XT=ns(),ZT=Cp();JT({target:"Object",stat:!0},{fromEntries:function(e){var t={};return XT(e,function(i,r){ZT(t,i,r)},{AS_ENTRIES:!0}),t}})});var Op=b((pk,Bp)=>{"use strict";so();Dp();var eI=Ha();Bp.exports=eI.Object.fromEntries});var _p=b((hk,Vp)=>{"use strict";Vp.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 Fp=b(()=>{"use strict";so();var tI=_p(),iI=oe(),rI=Sr(),Np=Qt();for(os in tI)rI(iI[os],os),Np[os]=Np.Array;var os});var qp=b((bk,Up)=>{"use strict";var aI=Op();Fp();Up.exports=aI});var oo=b((gk,Hp)=>{"use strict";var sI=qp();Hp.exports=sI});var jp=b(()=>{"use strict"});var uo=b((yk,Gp)=>{"use strict";var Tr=oe(),nI=Ti(),oI=Si(),us=function(a){return nI.slice(0,a.length)===a};Gp.exports=function(){return us("Bun/")?"BUN":us("Cloudflare-Workers")?"CLOUDFLARE":us("Deno/")?"DENO":us("Node.js/")?"NODE":Tr.Bun&&typeof Bun.version=="string"?"BUN":Tr.Deno&&typeof Deno.version=="object"?"DENO":oI(Tr.process)==="process"?"NODE":Tr.window&&Tr.document?"BROWSER":"REST"}()});var ls=b((Tk,Wp)=>{"use strict";var uI=uo();Wp.exports=uI==="NODE"});var Qp=b((Ik,Yp)=>{"use strict";var lI=zt();Yp.exports=function(a,e,t){return lI.f(a,e,t)}});var Jp=b((Ek,Kp)=>{"use strict";var cI=mt(),dI=Qp(),pI=Se(),hI=Ue(),zp=pI("species");Kp.exports=function(a){var e=cI(a);hI&&e&&!e[zp]&&dI(e,zp,{configurable:!0,get:function(){return this}})}});var Zp=b((xk,Xp)=>{"use strict";var fI=or(),mI=TypeError;Xp.exports=function(a,e){if(fI(e,a))return a;throw new mI("Incorrect invocation")}});var co=b((Pk,eh)=>{"use strict";var bI=Ie(),gI=ne(),lo=cr(),SI=bI(Function.toString);gI(lo.inspectSource)||(lo.inspectSource=function(a){return SI(a)});eh.exports=lo.inspectSource});var nh=b((Ak,sh)=>{"use strict";var vI=Ie(),yI=Le(),th=ne(),TI=gr(),II=mt(),EI=co(),ih=function(){},rh=II("Reflect","construct"),po=/^\s*(?:class|function)\b/,xI=vI(po.exec),PI=!po.test(ih),Ir=function(e){if(!th(e))return!1;try{return rh(ih,[],e),!0}catch(t){return!1}},ah=function(e){if(!th(e))return!1;switch(TI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return PI||!!xI(po,EI(e))}catch(t){return!0}};ah.sham=!0;sh.exports=!rh||yI(function(){var a;return Ir(Ir.call)||!Ir(Object)||!Ir(function(){a=!0})||a})?ah:Ir});var uh=b((wk,oh)=>{"use strict";var AI=nh(),wI=ur(),kI=TypeError;oh.exports=function(a){if(AI(a))return a;throw new kI(wI(a)+" is not a constructor")}});var ho=b((kk,ch)=>{"use strict";var lh=st(),RI=uh(),$I=vi(),LI=Se(),MI=LI("species");ch.exports=function(a,e){var t=lh(a).constructor,i;return t===void 0||$I(i=lh(t)[MI])?e:RI(i)}});var ph=b((Rk,dh)=>{"use strict";var CI=Ie();dh.exports=CI([].slice)});var fh=b(($k,hh)=>{"use strict";var DI=TypeError;hh.exports=function(a,e){if(a<e)throw new DI("Not enough arguments");return a}});var fo=b((Lk,mh)=>{"use strict";var BI=Ti();mh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(BI)});var Eo=b((Mk,xh)=>{"use strict";var Ce=oe(),OI=_n(),VI=mr(),bh=ne(),_I=Xe(),Eh=Le(),gh=Gn(),NI=ph(),Sh=Ua(),FI=fh(),UI=fo(),qI=ls(),yo=Ce.setImmediate,To=Ce.clearImmediate,HI=Ce.process,mo=Ce.Dispatch,jI=Ce.Function,vh=Ce.MessageChannel,GI=Ce.String,bo=0,Er={},yh="onreadystatechange",xr,Jt,go,So;Eh(function(){xr=Ce.location});var Io=function(a){if(_I(Er,a)){var e=Er[a];delete Er[a],e()}},vo=function(a){return function(){Io(a)}},Th=function(a){Io(a.data)},Ih=function(a){Ce.postMessage(GI(a),xr.protocol+"//"+xr.host)};(!yo||!To)&&(yo=function(e){FI(arguments.length,1);var t=bh(e)?e:jI(e),i=NI(arguments,1);return Er[++bo]=function(){OI(t,void 0,i)},Jt(bo),bo},To=function(e){delete Er[e]},qI?Jt=function(a){HI.nextTick(vo(a))}:mo&&mo.now?Jt=function(a){mo.now(vo(a))}:vh&&!UI?(go=new vh,So=go.port2,go.port1.onmessage=Th,Jt=VI(So.postMessage,So)):Ce.addEventListener&&bh(Ce.postMessage)&&!Ce.importScripts&&xr&&xr.protocol!=="file:"&&!Eh(Ih)?(Jt=Ih,Ce.addEventListener("message",Th,!1)):yh in Sh("script")?Jt=function(a){gh.appendChild(Sh("script"))[yh]=function(){gh.removeChild(this),Io(a)}}:Jt=function(a){setTimeout(vo(a),0)});xh.exports={set:yo,clear:To}});var wh=b((Ck,Ah)=>{"use strict";var Ph=oe(),WI=Ue(),YI=Object.getOwnPropertyDescriptor;Ah.exports=function(a){if(!WI)return Ph[a];var e=YI(Ph,a);return e&&e.value}});var xo=b((Dk,Rh)=>{"use strict";var kh=function(){this.head=null,this.tail=null};kh.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}}};Rh.exports=kh});var Lh=b((Bk,$h)=>{"use strict";var QI=Ti();$h.exports=/ipad|iphone|ipod/i.test(QI)&&typeof Pebble!="undefined"});var Ch=b((Ok,Mh)=>{"use strict";var zI=Ti();Mh.exports=/web0s(?!.*chrome)/i.test(zI)});var Fh=b((Vk,Nh)=>{"use strict";var ki=oe(),KI=wh(),Dh=mr(),Po=Eo().set,JI=xo(),XI=fo(),ZI=Lh(),eE=Ch(),Ao=ls(),Bh=ki.MutationObserver||ki.WebKitMutationObserver,Oh=ki.document,Vh=ki.process,cs=ki.Promise,Ro=KI("queueMicrotask"),wi,wo,ko,ds,_h;Ro||(Pr=new JI,Ar=function(){var a,e;for(Ao&&(a=Vh.domain)&&a.exit();e=Pr.get();)try{e()}catch(t){throw Pr.head&&wi(),t}a&&a.enter()},!XI&&!Ao&&!eE&&Bh&&Oh?(wo=!0,ko=Oh.createTextNode(""),new Bh(Ar).observe(ko,{characterData:!0}),wi=function(){ko.data=wo=!wo}):!ZI&&cs&&cs.resolve?(ds=cs.resolve(void 0),ds.constructor=cs,_h=Dh(ds.then,ds),wi=function(){_h(Ar)}):Ao?wi=function(){Vh.nextTick(Ar)}:(Po=Dh(Po,ki),wi=function(){Po(Ar)}),Ro=function(a){Pr.head||wi(),Pr.add(a)});var Pr,Ar;Nh.exports=Ro});var qh=b((_k,Uh)=>{"use strict";Uh.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var ps=b((Nk,Hh)=>{"use strict";Hh.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Xt=b((Fk,jh)=>{"use strict";var tE=oe();jh.exports=tE.Promise});var Ri=b((Uk,Qh)=>{"use strict";var iE=oe(),wr=Xt(),rE=ne(),aE=Fn(),sE=co(),nE=Se(),Gh=uo(),oE=Je(),$o=vn(),Wh=wr&&wr.prototype,uE=nE("species"),Lo=!1,Yh=rE(iE.PromiseRejectionEvent),lE=aE("Promise",function(){var a=sE(wr),e=a!==String(wr);if(!e&&$o===66||oE&&!(Wh.catch&&Wh.finally))return!0;if(!$o||$o<51||!/native code/.test(a)){var t=new wr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[uE]=i,Lo=t.then(function(){})instanceof i,!Lo)return!0}return!e&&(Gh==="BROWSER"||Gh==="DENO")&&!Yh});Qh.exports={CONSTRUCTOR:lE,REJECTION_EVENT:Yh,SUBCLASSING:Lo}});var $i=b((qk,Kh)=>{"use strict";var zh=bt(),cE=TypeError,dE=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new cE("Bad Promise constructor");e=i,t=r}),this.resolve=zh(e),this.reject=zh(t)};Kh.exports.f=function(a){return new dE(a)}});var bf=b(()=>{"use strict";var pE=qe(),hE=Je(),bs=ls(),Vt=oe(),Di=Me(),Jh=Ai(),Xh=io(),fE=Sr(),mE=Jp(),bE=bt(),ms=ne(),gE=Fe(),SE=Zp(),vE=ho(),af=Eo().set,Oo=Fh(),yE=qh(),TE=ps(),IE=xo(),sf=Vn(),gs=Xt(),Vo=Ri(),nf=$i(),Ss="Promise",of=Vo.CONSTRUCTOR,EE=Vo.REJECTION_EVENT,xE=Vo.SUBCLASSING,Mo=sf.getterFor(Ss),PE=sf.set,Li=gs&&gs.prototype,Zt=gs,hs=Li,uf=Vt.TypeError,Co=Vt.document,_o=Vt.process,Do=nf.f,AE=Do,wE=!!(Co&&Co.createEvent&&Vt.dispatchEvent),lf="unhandledrejection",kE="rejectionhandled",Zh=0,cf=1,RE=2,No=1,df=2,fs,ef,$E,tf,pf=function(a){var e;return gE(a)&&ms(e=a.then)?e:!1},hf=function(a,e){var t=e.value,i=e.state===cf,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===df&&ME(e),e.rejection=No),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new uf("Promise-chain cycle")):(l=pf(u))?Di(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},ff=function(a,e){a.notified||(a.notified=!0,Oo(function(){for(var t=a.reactions,i;i=t.get();)hf(i,a);a.notified=!1,e&&!a.rejection&&LE(a)}))},mf=function(a,e,t){var i,r;wE?(i=Co.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Vt.dispatchEvent(i)):i={promise:e,reason:t},!EE&&(r=Vt["on"+a])?r(i):a===lf&&yE("Unhandled promise rejection",t)},LE=function(a){Di(af,Vt,function(){var e=a.facade,t=a.value,i=rf(a),r;if(i&&(r=TE(function(){bs?_o.emit("unhandledRejection",t,e):mf(lf,e,t)}),a.rejection=bs||rf(a)?df:No,r.error))throw r.value})},rf=function(a){return a.rejection!==No&&!a.parent},ME=function(a){Di(af,Vt,function(){var e=a.facade;bs?_o.emit("rejectionHandled",e):mf(kE,e,a.value)})},Mi=function(a,e,t){return function(i){a(e,i,t)}},Ci=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=RE,ff(a,!0))},Bo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new uf("Promise can't be resolved itself");var i=pf(e);i?Oo(function(){var r={done:!1};try{Di(i,e,Mi(Bo,r,a),Mi(Ci,r,a))}catch(s){Ci(r,s,a)}}):(a.value=e,a.state=cf,ff(a,!1))}catch(r){Ci({done:!1},r,a)}}};if(of&&(Zt=function(e){SE(this,hs),bE(e),Di(fs,this);var t=Mo(this);try{e(Mi(Bo,t),Mi(Ci,t))}catch(i){Ci(t,i)}},hs=Zt.prototype,fs=function(e){PE(this,{type:Ss,done:!1,notified:!1,parent:!1,reactions:new IE,rejection:!1,state:Zh,value:void 0})},fs.prototype=Jh(hs,"then",function(e,t){var i=Mo(this),r=Do(vE(this,Zt));return i.parent=!0,r.ok=ms(e)?e:!0,r.fail=ms(t)&&t,r.domain=bs?_o.domain:void 0,i.state===Zh?i.reactions.add(r):Oo(function(){hf(r,i)}),r.promise}),ef=function(){var a=new fs,e=Mo(a);this.promise=a,this.resolve=Mi(Bo,e),this.reject=Mi(Ci,e)},nf.f=Do=function(a){return a===Zt||a===$E?new ef(a):AE(a)},!hE&&ms(gs)&&Li!==Object.prototype)){tf=Li.then,xE||Jh(Li,"then",function(e,t){var i=this;return new Zt(function(r,s){Di(tf,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Li.constructor}catch(a){}Xh&&Xh(Li,hs)}pE({global:!0,constructor:!0,wrap:!0,forced:of},{Promise:Zt});fE(Zt,Ss,!1,!0);mE(Ss)});var Tf=b((Gk,yf)=>{"use strict";var CE=Se(),Sf=CE("iterator"),vf=!1;try{gf=0,Fo={next:function(){return{done:!!gf++}},return:function(){vf=!0}},Fo[Sf]=function(){return this},Array.from(Fo,function(){throw 2})}catch(a){}var gf,Fo;yf.exports=function(a,e){try{if(!e&&!vf)return!1}catch(r){return!1}var t=!1;try{var i={};i[Sf]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Uo=b((Wk,If)=>{"use strict";var DE=Xt(),BE=Tf(),OE=Ri().CONSTRUCTOR;If.exports=OE||!BE(function(a){DE.all(a).then(void 0,function(){})})});var Ef=b(()=>{"use strict";var VE=qe(),_E=Me(),NE=bt(),FE=$i(),UE=ps(),qE=ns(),HE=Uo();VE({target:"Promise",stat:!0,forced:HE},{all:function(e){var t=this,i=FE.f(t),r=i.resolve,s=i.reject,n=UE(function(){var o=NE(t.resolve),u=[],l=0,c=1;qE(e,function(d){var h=l++,p=!1;c++,_E(o,t,d).then(function(m){p||(p=!0,u[h]=m,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var Pf=b(()=>{"use strict";var jE=qe(),GE=Je(),WE=Ri().CONSTRUCTOR,Ho=Xt(),YE=mt(),QE=ne(),zE=Ai(),xf=Ho&&Ho.prototype;jE({target:"Promise",proto:!0,forced:WE,real:!0},{catch:function(a){return this.then(void 0,a)}});!GE&&QE(Ho)&&(qo=YE("Promise").prototype.catch,xf.catch!==qo&&zE(xf,"catch",qo,{unsafe:!0}));var qo});var Af=b(()=>{"use strict";var KE=qe(),JE=Me(),XE=bt(),ZE=$i(),ex=ps(),tx=ns(),ix=Uo();KE({target:"Promise",stat:!0,forced:ix},{race:function(e){var t=this,i=ZE.f(t),r=i.reject,s=ex(function(){var n=XE(t.resolve);tx(e,function(o){JE(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var wf=b(()=>{"use strict";var rx=qe(),ax=$i(),sx=Ri().CONSTRUCTOR;rx({target:"Promise",stat:!0,forced:sx},{reject:function(e){var t=ax.f(this),i=t.reject;return i(e),t.promise}})});var jo=b((tR,kf)=>{"use strict";var nx=st(),ox=Fe(),ux=$i();kf.exports=function(a,e){if(nx(a),ox(e)&&e.constructor===a)return e;var t=ux.f(a),i=t.resolve;return i(e),t.promise}});var Lf=b(()=>{"use strict";var lx=qe(),cx=mt(),Rf=Je(),dx=Xt(),$f=Ri().CONSTRUCTOR,px=jo(),hx=cx("Promise"),fx=Rf&&!$f;lx({target:"Promise",stat:!0,forced:Rf||$f},{resolve:function(e){return px(fx&&this===hx?dx:this,e)}})});var Mf=b(()=>{"use strict";bf();Ef();Pf();Af();wf();Lf()});var Of=b(()=>{"use strict";var mx=qe(),bx=Je(),vs=Xt(),gx=Le(),Df=mt(),Bf=ne(),Sx=ho(),Cf=jo(),vx=Ai(),Wo=vs&&vs.prototype,yx=!!vs&&gx(function(){Wo.finally.call({then:function(){}},function(){})});mx({target:"Promise",proto:!0,real:!0,forced:yx},{finally:function(a){var e=Sx(this,Df("Promise")),t=Bf(a);return this.then(t?function(i){return Cf(e,a()).then(function(){return i})}:a,t?function(i){return Cf(e,a()).then(function(){throw i})}:a)}});!bx&&Bf(vs)&&(Go=Df("Promise").prototype.finally,Wo.finally!==Go&&vx(Wo,"finally",Go,{unsafe:!0}));var Go});var ys=b((uR,Vf)=>{"use strict";var Tx=mt();Vf.exports=Tx});var Nf=b((lR,_f)=>{"use strict";jp();Mf();Of();var Ix=ys();_f.exports=Ix("Promise","finally")});var Uf=b((cR,Ff)=>{"use strict";var Ex=Nf();Ff.exports=Ex});var Ts=b((dR,qf)=>{"use strict";var xx=Uf();qf.exports=xx});var Xf=b(()=>{"use strict";var Mx=qe(),Cx=dr(),Dx=Ja(),Bx=Ka(),Ox=cn();Mx({target:"Array",proto:!0},{at:function(e){var t=Cx(this),i=Dx(t),r=Bx(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});Ox("at")});var em=b((l$,Zf)=>{"use strict";Xf();var Vx=ys();Zf.exports=Vx("Array","at")});var im=b((c$,tm)=>{"use strict";var _x=em();tm.exports=_x});var Bi=b((d$,rm)=>{"use strict";var Nx=im();rm.exports=Nx});var zm=b(()=>{"use strict"});var Km=b(()=>{"use strict"});var Xm=b((ZC,Jm)=>{"use strict";var vP=Fe(),yP=Si(),TP=Se(),IP=TP("match");Jm.exports=function(a){var e;return vP(a)&&((e=a[IP])!==void 0?!!e:yP(a)==="RegExp")}});var eb=b((eD,Zm)=>{"use strict";var EP=gr(),xP=String;Zm.exports=function(a){if(EP(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return xP(a)}});var ib=b((tD,tb)=>{"use strict";var PP=st();tb.exports=function(){var a=PP(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 sb=b((iD,ab)=>{"use strict";var AP=Me(),wP=Xe(),kP=or(),RP=ib(),rb=RegExp.prototype;ab.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in rb)&&!wP(a,"flags")&&kP(rb,a)?AP(RP,a):e}});var ob=b((rD,nb)=>{"use strict";var mu=Ie(),$P=dr(),LP=Math.floor,hu=mu("".charAt),MP=mu("".replace),fu=mu("".slice),CP=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,DP=/\$([$&'`]|\d{1,2})/g;nb.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=DP;return r!==void 0&&(r=$P(r),u=CP),MP(s,u,function(l,c){var d;switch(hu(c,0)){case"$":return"$";case"&":return a;case"`":return fu(e,0,t);case"'":return fu(e,n);case"<":d=r[fu(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=LP(h/10);return p===0?l:p<=o?i[p-1]===void 0?hu(c,1):i[p-1]+hu(c,1):l}d=i[h-1]}return d===void 0?"":d})}});var cb=b(()=>{"use strict";var BP=qe(),OP=Me(),gu=Ie(),ub=sr(),VP=ne(),_P=vi(),NP=Xm(),Gi=eb(),FP=lr(),UP=sb(),qP=ob(),HP=Se(),jP=Je(),GP=HP("replace"),WP=TypeError,bu=gu("".indexOf),YP=gu("".replace),lb=gu("".slice),QP=Math.max;BP({target:"String",proto:!0},{replaceAll:function(e,t){var i=ub(this),r,s,n,o,u,l,c,d,h,p,m=0,g="";if(!_P(e)){if(r=NP(e),r&&(s=Gi(ub(UP(e))),!~bu(s,"g")))throw new WP("`.replaceAll` does not allow non-global regexes");if(n=FP(e,GP),n)return OP(n,e,i,t);if(jP&&r)return YP(Gi(i),e,t)}for(o=Gi(i),u=Gi(e),l=VP(t),l||(t=Gi(t)),c=u.length,d=QP(1,c),h=bu(o,u);h!==-1;)p=l?Gi(t(u,h,o)):qP(u,o,h,[],void 0,t),g+=lb(o,m,h)+p,m=h+c,h=h+d>o.length?-1:bu(o,u,h+d);return m<o.length&&(g+=lb(o,m)),g}})});var pb=b((nD,db)=>{"use strict";zm();Km();cb();var zP=ys();db.exports=zP("String","replaceAll")});var fb=b((oD,hb)=>{"use strict";var KP=pb();hb.exports=KP});var bb=b((uD,mb)=>{"use strict";var JP=fb();mb.exports=JP});var mA={};fg(mA,{ChromecastState:()=>rr,HttpConnectionType:()=>_a,Observable:()=>dt.Observable,PlaybackState:()=>ge,Player:()=>Ea,SDK_VERSION:()=>fA,Subject:()=>dt.Subject,Subscription:()=>dt.Subscription,Surface:()=>Na,VERSION:()=>on,ValueSubject:()=>dt.ValueSubject,VideoFormat:()=>ft,VideoQuality:()=>dt.VideoQuality});module.exports=mg(mA);var on="2.0.116-dev.48c29cc5.0";var ge=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ge||{}),ft=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(ft||{});var rr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(rr||{}),_a=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(_a||{});var Na=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Na||{});var F=require("@vkontakte/videoplayer-shared");var hl=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Fa=class{constructor(e){this.connection$=new F.ValueSubject(void 0);this.castState$=new F.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new F.Subject;this.realCastState$=new F.ValueSubject("NOT_AVAILABLE");this.subscription=new F.Subscription;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 i=(0,F.isNonNullable)((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},r||hl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:F.ErrorCategory.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 i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,F.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,F.isNullable)(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),i=cast.framework.CastContext.getInstance();this.subscription.add((0,F.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,F.assertNever)(r.sessionState)}})).add((0,F.merge)((0,F.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,F.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,F.map)(r=>r.castState)),(0,F.observableFrom)([i.getCastState()])).pipe((0,F.filterChanged)(),(0,F.map)(bg),(0,F.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=(0,F.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();(0,F.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,F.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,F.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:F.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},bg=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(0,F.assertNever)(a)}};var Fb=Ne(oo(),1);var Wf=Ne(Ts(),1);var Yo=require("@vkontakte/videoplayer-shared");var me=(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 i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Yo.assertNever)(t)}return a},Qo=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Yo.assertNever)(e)}};var k=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var nt=require("@vkontakte/videoplayer-shared"),j=class{constructor(e){this.transitionStarted$=new nt.Subject;this.transitionEnded$=new nt.Subject;this.transitionUpdated$=new nt.Subject;this.forceChanged$=new nt.Subject;this.stateChangeStarted$=(0,nt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,nt.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,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:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,nt.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Hf=require("@vkontakte/videoplayer-shared"),jf=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(0,Hf.assertNever)(a)}};var $=require("@vkontakte/videoplayer-shared");var Px=5,Ax=5,wx=500,Gf=7e3,kr=class{constructor(e){this.subscription=new $.Subscription;this.loadMediaTimeoutSubscription=new $.Subscription;this.videoState=new j("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,$.assertNever)(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:(0,$.assertNever)(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:(0,$.assertNever)(e)}break}default:(0,$.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(jf(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 $.Subscription;this.subscription.add(e),this.subscription.add((0,$.merge)(this.videoState.stateChangeStarted$.pipe((0,$.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,$.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new $.Subject;e.add(r.pipe((0,$.debounce)(wx)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,$.fromEvent)(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)>Px)&&r.next(o),s=o})),e.add((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.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<Ax&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(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:(0,$.assertNever)(n)}}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,$.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,$.observableFrom)(["init"])).pipe((0,$.debounce)(0));t(i,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"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?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),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(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"),k(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"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];(0,$.assertNonNullable)(c);let d=(0,$.getHighestQuality)(Object.keys(c));(0,$.assertNonNullable)(d);let h=c[d];(0,$.assertNonNullable)(h),i=h,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,$.assertNonNullable)(c),i=c.url,r="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];(0,$.assertNonNullable)(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,$.assertNonNullable)(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,$.assertNonNullable)(c),i=me(c.url),r="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:$.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,$.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,$.isNonNullable)(o)&&(n.metadata.title=o),(0,$.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add((0,$.timeout)(Gf).subscribe(()=>s(`timeout(${Gf})`)))});(0,Wf.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:$.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Xo=require("@vkontakte/videoplayer-shared");var Yf=require("@vkontakte/videoplayer-shared"),Qf=a=>{try{a.pause(),a.playbackRate=0,(0,Yf.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Is=require("@vkontakte/videoplayer-shared"),zo=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)}},Ko=window.WeakMap?new WeakMap:new zo,Jo=window.WeakMap?new WeakMap:new Map,kx=(a,e=20)=>{let t=0;return(0,Is.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ee=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),i=!!t;t?(0,Xo.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),Ko.set(t,i);let r=new Is.Subscription;return r.add(kx(t,e)),Jo.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},xe=a=>{let e=Jo.get(a);e==null||e.unsubscribe(),Jo.delete(a);let t=Ko.get(a);Ko.delete(a),t?(0,Xo.clearVideoElement)(a):Qf(a)};var L=require("@vkontakte/videoplayer-shared");var _t=require("@vkontakte/videoplayer-shared"),Es=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,_t.isNullable)(r),l=new _t.Subscription;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ot=(a,e,t)=>Es(e,()=>a.loop,i=>{(0,_t.isNonNullable)(i)&&(a.loop=i)},{onError:t}),Pe=(a,e,t,i)=>Es(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,_t.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),He=(a,e,t,i)=>Es(e,()=>a.playbackRate,r=>{(0,_t.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Nt=Es;var Rx=a=>["__",a.language,a.label].join("|"),$x=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Zo=class a{constructor(){this.available$=new L.Subject;this.current$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.subscription=new L.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:L.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Nt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,L.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Nt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,L.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Nt(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:r})),this.subscription.add(Nt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,L.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"addtrack"),(0,L.fromEvent)(e,"removetrack"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,L.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"change"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,L.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,L.filterChanged)()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,L.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,L.isNonNullable)(t.align)&&(r.align=t.align),(0,L.isNonNullable)(t.position)&&(r.position=t.position),(0,L.isNonNullable)(t.size)&&(r.size=t.size),(0,L.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c;let{language:t,label:i}=e,r=e.id?e.id:Rx(e),s=this.externalTracks.has(r),n=(s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)||r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(l=this.externalTracks.get(r))==null?void 0:l.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!$x(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){(0,L.assertNonNullable)(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){(0,L.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.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)}},je=Zo;var vt=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 zf=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},eu=a=>{let e=zf(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Kf=a=>{let e=zf(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var M=require("@vkontakte/videoplayer-shared");var Lx=3,Jf=(a,e,t=Lx)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Ae=a=>{let e=T=>(0,M.fromEvent)(a,T).pipe((0,M.mapTo)(void 0)),i=(0,M.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>(0,M.fromEvent)(a,T))).pipe((0,M.map)(T=>T.type==="ended"?a.readyState<2:a.readyState<3),(0,M.filterChanged)()),r=(0,M.merge)((0,M.fromEvent)(a,"progress"),(0,M.fromEvent)(a,"timeupdate")).pipe((0,M.map)(()=>Jf(a.buffered,a.currentTime))),s=M.clientChecker.isSafari?(0,M.combine)({play:e("play").pipe((0,M.once)()),playing:e("playing")}).pipe((0,M.mapTo)(void 0)):e("playing"),n=(0,M.fromEvent)(a,"volumechange").pipe((0,M.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,M.fromEvent)(a,"ratechange").pipe((0,M.map)(()=>a.playbackRate)),u=(0,M.fromEvent)(a,"error").pipe((0,M.filter)(()=>!!(a.error||a.played.length)),(0,M.map)(()=>{var P;let T=a.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:M.ErrorCategory.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(P=a.error)!=null?P:void 0}})),l=(0,M.fromEvent)(a,"timeupdate").pipe((0,M.map)(()=>a.currentTime)),c=new M.Subject,d=.3,h;l.subscribe(T=>{a.loop&&(0,M.isNonNullable)(h)&&(0,M.isNonNullable)(T)&&h>=a.duration-d&&T<=d&&c.next(h),h=T});let p=e("pause").pipe((0,M.filter)(()=>!a.error&&h!==a.duration)),m=(0,M.fromEvent)(a,"enterpictureinpicture"),g=(0,M.fromEvent)(a,"leavepictureinpicture"),S=new M.ValueSubject(Kf(a));m.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let x=new M.ValueSubject(eu(a));return(0,M.fromEvent)(a,"fullscreenchange").pipe((0,M.map)(()=>eu(a))).subscribe(x),{playing$:s,pause$:p,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$:(0,M.fromEvent)(a,"durationchange").pipe((0,M.map)(()=>a.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:x}};var yt=require("@vkontakte/videoplayer-shared"),Ft=a=>{switch(a){case"mobile":return yt.VideoQuality.Q_144P;case"lowest":return yt.VideoQuality.Q_240P;case"low":return yt.VideoQuality.Q_360P;case"sd":case"medium":return yt.VideoQuality.Q_480P;case"hd":case"high":return yt.VideoQuality.Q_720P;case"fullhd":case"full":return yt.VideoQuality.Q_1080P;case"quadhd":case"quad":return yt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return yt.VideoQuality.Q_2160P}};var ei=Ne(Bi(),1),C=require("@vkontakte/videoplayer-shared");var tu=!1,Tt={},am=a=>{tu=a},sm=()=>{Tt={}},nm=a=>{a(Tt)},Rr=(a,e)=>{var t;tu&&(Tt.meta=(t=Tt.meta)!=null?t:{},Tt.meta[a]=e)},ve=class{constructor(e){this.name=e}next(e){var i,r;if(!tu)return;Tt.series=(i=Tt.series)!=null?i:{};let t=(r=Tt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Tt.series[this.name]=t}};var Fx=new ve("best_bitrate"),um=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var iu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),$r=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,C.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},lm='Assertion "ABR Tracks is empty array" failed',xs=(a,e,t,i)=>{var u;let r=[...e].sort(iu(1)),s=[...t].sort(iu(1)),n=s.filter(l=>(0,C.isNonNullable)(l.bitrate)&&(0,C.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,ei.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,ei.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,ei.default)(n,-1):(0,ei.default)(s,0)},om=a=>"quality"in a,cm=(a,e,t,i)=>{var n;let r=(0,C.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,C.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,C.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=om(o)?"video":"audio",l=om(o)?o.quality:o.bitrate;return e({message:`
|
|
7
|
+
[last ${u} selected] ${l}
|
|
8
|
+
`}),o}return i==null||i.recordSwitch(t),t},Ut=(a,{container:e,throughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{var K,_,D,ee,le;(0,C.assertNotEmptyArray)(a,lm);let p=(K=window.devicePixelRatio)!=null?K:1,m=i.usePixelRatio?i.pixelRatioMultiplier*(p-1)+1:1,g=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*m*i.containerSizeFactor,height:e.height*m*i.containerSizeFactor},S=g&&(0,C.videoSizeToQuality)(g),x=i.considerPlaybackRate&&(0,C.isNonNullable)(o)?o:1,A=a.filter(E=>!(0,C.isInvariantQuality)(E.quality)).sort((E,H)=>(0,C.isHigher)(E.quality,H.quality)?-1:1),T=(_=(0,ei.default)(A,-1))==null?void 0:_.quality,P=(D=(0,ei.default)(A,0))==null?void 0:D.quality,w=(0,C.isNullable)(r)||(0,C.isNonNullable)(r.min)&&(0,C.isNonNullable)(r.max)&&(0,C.isLower)(r.max,r.min)||(0,C.isNonNullable)(r.min)&&P&&(0,C.isHigher)(r.min,P)||(0,C.isNonNullable)(r.max)&&T&&(0,C.isLower)(r.max,T),V=x*um(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),W={},N=A.filter(E=>{if(!(S?(0,C.isLowerOrEqual)(E.quality,S):!0))return W[E.quality]="FitsContainer",!1;if(!((0,C.isNonNullable)(t)&&isFinite(t)&&(0,C.isNonNullable)(E.bitrate)?t-s>=E.bitrate*V:!0))return W[E.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,C.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,C.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,C.isHigher)(E.quality,u.quality))return W[E.quality]="Buffer",!1;if(!!d&&(0,C.isHigherOrEqual)(E.quality,d))return W[E.quality]="DroppedFramesLimit",!1;let ye=w||((0,C.isNullable)(r.max)||(0,C.isLowerOrEqual)(E.quality,r.max))&&((0,C.isNullable)(r.min)||(0,C.isHigherOrEqual)(E.quality,r.min)),pt=(0,C.isNonNullable)(c)&&!c?(0,C.isLowerOrEqual)(E.quality,i.backgroundVideoQualityLimit):!0;return!ye||!pt?(W[E.quality]="FitsQualityLimits",!1):!0})[0];N&&N.bitrate&&Fx.next(N.bitrate);let z=(ee=N!=null?N:A[Math.ceil((A.length-1)/2)])!=null?ee:a[0];return z.quality!==((le=l==null?void 0:l.last)==null?void 0:le.quality)&&h({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
10
10
|
[available video tracks]
|
|
11
11
|
${a.map(E=>`{ id: ${E.id}, quality: ${E.quality}, bitrate: ${E.bitrate} }`).join(`
|
|
12
12
|
`)}
|
|
13
13
|
|
|
14
14
|
[tuning]
|
|
15
|
-
${Object.entries(i!=null?i:{}).map(([E,
|
|
15
|
+
${Object.entries(i!=null?i:{}).map(([E,H])=>`${E}: ${H}`).join(`
|
|
16
16
|
`)}
|
|
17
17
|
|
|
18
18
|
[limit params]
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
playbackRate: ${o},
|
|
23
23
|
playbackRateFactor: ${x},
|
|
24
24
|
forwardBufferHealth: ${n},
|
|
25
|
-
bitrateFactor: ${
|
|
25
|
+
bitrateFactor: ${V},
|
|
26
26
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
27
27
|
droppedVideoMaxQualityLimit: ${d},
|
|
28
28
|
limitsAreInvalid: ${w},
|
|
@@ -30,12 +30,12 @@
|
|
|
30
30
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
31
31
|
|
|
32
32
|
[limited video tracks]
|
|
33
|
-
${Object.entries(
|
|
33
|
+
${Object.entries(W).map(([E,H])=>`${E}: ${H}`).join(`
|
|
34
34
|
`)||"All tracks are available"}
|
|
35
35
|
|
|
36
|
-
[best video track] ${
|
|
37
|
-
[selected video track] ${
|
|
38
|
-
`}),
|
|
36
|
+
[best video track] ${N==null?void 0:N.quality}
|
|
37
|
+
[selected video track] ${z==null?void 0:z.quality}
|
|
38
|
+
`}),cm(i,h,z,l)},dm=(a,e,t,{throughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var g;(0,C.assertNotEmptyArray)(t,lm);let l=r.considerPlaybackRate&&(0,C.isNonNullable)(s)?s:1,c=[...t].sort(iu(-1)),d=a.bitrate;(0,C.assertNonNullable)(d);let h=l*um(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),p,m=xs(a,e,t,r.minVideoAudioRatio);return(0,C.isNonNullable)(i)&&isFinite(i)&&(p=c.find(S=>(0,C.isNonNullable)(S.bitrate)&&(0,C.isNonNullable)(m==null?void 0:m.bitrate)?i-d>=S.bitrate*h&&S.bitrate>=m.bitrate:!1)),p||(p=m),(p==null?void 0:p.bitrate)!==((g=o==null?void 0:o.last)==null?void 0:g.bitrate)&&u({message:`
|
|
39
39
|
[AUDIO TRACKS ABR]
|
|
40
40
|
[available audio tracks]
|
|
41
41
|
${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
|
|
@@ -49,20 +49,20 @@
|
|
|
49
49
|
throughput: ${i},
|
|
50
50
|
reserve: ${d},
|
|
51
51
|
playbackRate: ${s},
|
|
52
|
-
playbackRateFactor: ${
|
|
52
|
+
playbackRateFactor: ${l},
|
|
53
53
|
forwardBufferHealth: ${n},
|
|
54
|
-
bitrateFactor: ${
|
|
54
|
+
bitrateFactor: ${h},
|
|
55
55
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
56
56
|
|
|
57
|
-
[selected audio track] ${
|
|
58
|
-
`}),h&&dm(r,u,h,o)};var pe=a=>new URL(a).hostname;var B=require("@vkontakte/videoplayer-shared");var hm=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"))},we=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!hm(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return hm(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};var De=require("@vkontakte/videoplayer-shared");var ut=require("@vkontakte/videoplayer-shared");function he(){return(0,ut.now)()}function iu(a){return he()-a}function ru(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let c=n.indexOf("?")>-1?"&":"?";return u&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function fm(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Di(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,c=0,l,d,p=!1,h="arraybuffer",m=7e3,g=2e3,S=()=>{if(u)return;(0,ut.assertNonNullable)(l);let D=iu(l),V;if(D<g){V=g-D,setTimeout(S,V);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new r,F()},x=D=>(s=D,J),A=D=>(d=D,J),T=()=>(h="json",J),P=()=>{if(!u){if(--c>=0){S(),i&&i();return}u=!0,d&&d(),t&&t()}},w=D=>(p=D,J),F=()=>{l=he(),n=new r,n.open("get",a);let D=0,V,ee=0,le=()=>((0,ut.assertNonNullable)(l),Math.max(l,Math.max(V||0,ee||0)));if(s&&n.addEventListener("progress",E=>{let U=he();s.updateChunk&&E.loaded>D&&(s.updateChunk(le(),E.loaded-D),D=E.loaded,V=U)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>P())),n.addEventListener("load",()=>{if(u)return;(0,ut.assertNonNullable)(n);let E=n.status;if(E>=200&&E<300){if(n.response.byteLength&&s){let U=n.response.byteLength-D;U&&s.updateChunk&&s.updateChunk(le(),U)}n.responseType==="json"&&!Object.values(n.response).length?P():(d&&d(),e(n.response))}else P()}),n.addEventListener("error",()=>{P()}),p){let E=()=>{(0,ut.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ee=he(),n.removeEventListener("readystatechange",E))};n.addEventListener("readystatechange",E)}return n.responseType=h,n.send(),J},J={withBitrateReporting:x,withParallel:w,withJSONResponse:T,withRetryCount:D=>(c=D,J),withRetryInterval:(D,V)=>((0,ut.isNonNullable)(D)&&(g=D),(0,ut.isNonNullable)(V)&&(m=V),J),withTimeout:D=>(o=D,J),withFinally:A,send:F,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return J}var Lr=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,i){return{start:e,end:t,bytes:i}}_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 i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/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(r)}/${Math.round(i)} 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,i){return this.intervals.push(this._createInterval(e,t,i)),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 Mr=class{constructor(e,t,i,r,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=i,this.MAX_PARALLEL_REQUESTS=r,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 i=he(),r=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=he()-i,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=Di(t,s,()=>r("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=he()}_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=he();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!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,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,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}`),i(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=i,s._retryCB=r,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 mm=require("@vkontakte/videoplayer-shared"),xs=1e4,au=3;var Hx=6e4,jx=10,Gx=1,Wx=500,Cr=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.soundProhibitedEvent$=new mm.Subject,this.chunkRateEstimator=new Lr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ru(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],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=ru(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,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-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 r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.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,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,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)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,De.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{fm(r,"progress",()=>{r.buffered.length?(r.currentTime=r.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 Mr(au,xs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,c=null,l=!1,d=()=>{let P=s&&(!l||l===this.rep);return P||t("Not running!"),P},p=(P,w,F)=>{u&&u.abort(),u=Di(this.urlResolver.resolve(P,!1),w,F,()=>this._retryCallback()).withTimeout(xs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(au).withFinally(()=>{u=null}).send()},h=(P,w,F)=>{(0,De.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(P,!1),w,F,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=P=>{let w=i.playbackRate;i.playbackRate!==P&&(t(`Playback rate switch: ${w}=>${P}`),i.playbackRate=P)},g=P=>{this.lowLatency=P,t(`lowLatency changed to ${P}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let P=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let F=he()-1e4,G=0;for(let Y=0;Y<this.bufferStates.length;Y++){let K=this.bufferStates[Y];P=Math.min(P,K.buf),K.ts<F&&G++}this.bufferStates.splice(0,G),t(`update playback rate; minBuffer=${P} drop=${G} jitter=${this.sourceJitter}`);let W=P-Gx;this.sourceJitter>=0?W-=this.sourceJitter/2:this.sourceJitter-=1,W>3?m(1.15):W>1?m(1.1):W>.3?m(1.05):m(1)}},x=P=>{let w,F=()=>w&&w.start?w.start.length:0,G=E=>w.start[E]/1e3,W=E=>w.dur[E]/1e3,Y=E=>w.fragIndex+E,K=(E,U)=>({chunkIdx:Y(E),startTS:G(E),dur:W(E),discontinuity:U}),J=()=>{let E=0;if(w&&w.dur){let U=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,te=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,se=U;this.sourceJitter>1&&(se+=this.sourceJitter-1);let ce=w.dur.length-1;for(;ce>=0&&(se-=w.dur[ce],!(se<=0));--ce);E=Math.min(ce,w.dur.length-1-te),E=Math.max(E,0)}return K(E,!0)},D=E=>{let U=F();if(!(U<=0)){if((0,De.isNonNullable)(E)){for(let te=0;te<U;te++)if(G(te)>E)return K(te)}return J()}},V=E=>{let U=F(),te=E?E.chunkIdx+1:0,se=te-w.fragIndex;if(!(U<=0)){if(!E||se<0||se-U>jx)return t(`Resync: offset=${se} bChunks=${U} chunk=`+JSON.stringify(E)),J();if(!(se>=U))return K(te-w.fragIndex,!1)}},ee=(E,U,te)=>{c&&c.abort(),c=Di(this.urlResolver.resolve(E,!0,this.lowLatency),U,te,()=>this._retryCallback()).withTimeout(xs).withRetryCount(au).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(E,U)=>{ee(P,te=>{if(!d())return;w=te;let se=!!w.lowLatency;se!==this.lowLatency&&g(se);let ce=0;for(let ye=0;ye<w.dur.length;++ye)ce+=w.dur[ye];ce>0&&((0,De.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ce/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,E(D(U))},()=>this._handleNetworkError())},nextChunk:V}},A=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),(0,De.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:P=>{let{videoElement:w,logger:F}=this.params,G=x(e.jidxUrl),W,Y,K,J,D=0,V,ee,le,E=()=>{V&&(clearTimeout(V),V=void 0);let R=Math.max(Wx,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Te=D+R,$e=he(),Oe=Math.min(1e4,Te-$e);D=$e;let $t=()=>{c||d()&&G.seek(()=>{d()&&(D=he(),U(),E())})};Oe>0?V=window.setTimeout(()=>{this.paused?E():$t()},Oe):$t()},U=()=>{let R;for(;R=G.nextChunk(J);)J=R,pt(R);let Te=G.nextChunk(K);if(Te){if(K&&Te.discontinuity){F("Detected discontinuity; restarting playback"),this.paused?E():(A(),this._initPlayerWith(e));return}ye(Te)}else E()},te=(R,Te)=>{if(!d()||!this.sourceBuffer)return;let $e,Oe,$t,li=Lt=>{window.setTimeout(()=>{d()&&te(R,Te)},Lt)};if(this.sourceBuffer.updating)F("Source buffer is updating; delaying appendBuffer"),li(100);else{let Lt=he(),Ut=w.currentTime;!this.paused&&w.buffered.length>1&&ee===Ut&&Lt-le>500&&(F("Stall suspected; trying to fix"),this._fixupStall()),ee!==Ut&&(ee=Ut,le=Lt);let ci=this._getBufferSizeSec();if(ci>30)F(`Buffered ${ci} seconds; delaying appendBuffer`),li(2e3);else try{this.sourceBuffer.appendBuffer(R),this.videoPlayStarted?(this.bufferStates.push({ts:Lt,buf:ci}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Te&&Te()}catch(zi){if(zi.name==="QuotaExceededError")F("QuotaExceededError; delaying appendBuffer"),$t=this.sourceBuffer.buffered.length,$t!==0&&($e=this.sourceBuffer.buffered.start(0),Oe=Ut,Oe-$e>4&&this.sourceBuffer.remove($e,Oe-3)),li(1e3);else throw zi}}},se=()=>{Y&&W&&(F([`Appending chunk, sz=${Y.byteLength}:`,JSON.stringify(K)]),te(Y,function(){Y=null,U()}))},ce=R=>e.fragUrlTemplate.replace("%%id%%",R.chunkIdx),ye=R=>{d()&&h(ce(R),(Te,$e)=>{if(d()){if($e/=1e3,Y=Te,K=R,n=R.startTS,$e){let Oe=Math.min(10,R.dur/$e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Oe:Oe}se()}},()=>this._handleNetworkError())},pt=R=>{d()&&((0,De.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ce(R),!1)))},Rt=R=>{d()&&(e.cachedHeader=R,te(R,()=>{W=!0,se()}))};s=!0,G.seek(R=>{if(d()){if(D=he(),!R){E();return}J=R,!(0,De.isNullable)(P)||R.startTS>P?ye(R):(K=R,U())}},P),e.cachedHeader?Rt(e.cachedHeader):p(e.headerUrl,Rt,()=>this._handleNetworkError())},stop:A,getTimestampSec:()=>n},l}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,De.isNonNullable)(r)&&(r+=.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,(0,De.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,De.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.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 m=he();if(this.chunkRateEstimator.addInterval(p,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,c=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&iu(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&c(),h},notifySwitch:d=>{let p=he();d<o&&(n=p),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Di(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(xs).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;we(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,c)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({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))},Hx))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var ae=require("@vkontakte/videoplayer-shared"),su=class{constructor(){this.onDroopedVideoFramesLimit$=new ae.Subject;this.subscription=new ae.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ae.Subject;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&&!(0,ae.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,ae.isHigher)(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((0,ae.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ae.interval)(this.droppedFramesChecker.checkTime).pipe((0,ae.filter)(()=>this.playing),(0,ae.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,ae.debounce)(this.droppedFramesChecker.checkTime)),i=(0,ae.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),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 i,r;let t=(r=(i=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,ae.isLower)(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[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}},Ps=su;var As=require("@vkontakte/videoplayer-shared"),bm=require("@vkontakte/videoplayer-shared");var Dr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Yx=(a,e)=>new As.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Dr()))},{...i,...e});r.observe(a);let s=(0,bm.fromEvent)(document,"visibilitychange").pipe((0,As.map)(n=>!document.hidden||Dr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe}}),He=Yx;var Qx=["paused","playing","ready"],zx=["paused","playing","ready"],Br=class{constructor(e){this.subscription=new B.Subscription;this.videoState=new H("stopped");this.representations$=new B.ValueSubject([]);this.textTracksManager=new Ue;this.droppedFramesManager=new Ps;this.maxSeekBackTime$=new B.ValueSubject(1/0);this.zeroTime$=new B.ValueSubject(void 0);this.liveOffset=new vt;this._dashCb=e=>{var t,i,r,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:B.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let c=(t=u.name)!=null?t:u.index.toString(10),l=(i=Nt(u.name))!=null?i:(0,B.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p={...u.video};if(!l)continue;let h={id:c,quality:l,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.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),(0,B.isNonNullable)(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(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="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(zx.includes(e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&Qx.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(fe(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="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(fe(this.params.source.url,u))}return;default:return(0,B.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:B.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};(0,B.merge)(this.videoState.stateChangeStarted$.pipe((0,B.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,B.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})}),this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),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(pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ae(this.video);this.subscription.add(this.representations$.pipe((0,B.map)(r=>r.map(({track:s})=>s)),(0,B.filter)(r=>!!r.length),(0,B.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,B.filterChanged)(),(0,B.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,B.combine)({zeroTime:this.zeroTime$.pipe((0,B.filter)(B.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(Pe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(qe(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(He(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let s=r&&(0,B.videoQualityToHeight)(r);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.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(0,B.assertNever)(r.to)}},t)).add((0,B.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,B.observableFrom)(["init"])).pipe((0,B.debounce)(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),xe(this.video)}createLiveDashPlayer(){let e=new Cr({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var c,l,d,p,h,m;let e=this.representations$.getValue(),t=(l=(c=this.params.desiredState.videoTrack.getTransition())==null?void 0:c.to)!=null?l:this.params.desiredState.videoTrack.getState(),i=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,B.isNonNullable)(t)?t:Ft(e.map(({track:g})=>g),{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=r==null?void 0:r.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(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let g=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;(0,B.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;(0,B.assertNonNullable)(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(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(fe(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var gm=Br;var lt=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var N=require("@vkontakte/videoplayer-shared");var ws=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];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}},Bi=class extends ws{constructor(){super(),this.listeners||ws.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)}},Or=class{constructor(){Object.defineProperty(this,"signal",{value:new Bi,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){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 i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Or.prototype[Symbol.toStringTag]="AbortController",Bi.prototype[Symbol.toStringTag]="AbortSignal");function ks(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 nu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!ks({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(c,l){let d;l&&l.signal&&(d=l.signal,delete l.signal);let p=new t(c,l);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,c)=>{let l=s&&s.prototype.isPrototypeOf(u)?u.signal:c?c.signal:void 0;if(l){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(l.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{l.addEventListener("abort",()=>m(d),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([p,n(u,c)])}return n(u,c)},Request:s}}var Vr=ks({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Sm=Vr?nu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,It=Vr?Sm.fetch:window.fetch,wL=Vr?Sm.Request:window.Request,et=Vr?Or:window.AbortController,kL=Vr?Bi:window.AbortSignal;var Vs=ze(kr(),1);var Et=()=>window.ManagedMediaSource||window.MediaSource,Rs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},vm=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},ym=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ct=require("@vkontakte/videoplayer-shared"),je=document.createElement("video"),Xx='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Zx='video/mp4; codecs="hev1.1.6.L93.B0"',Lm='video/webm; codecs="vp09.00.10.08"',Mm='video/webm; codecs="av01.0.00M.08"',eP='audio/mp4; codecs="mp4a.40.2"',tP='audio/webm; codecs="opus"',Tm,Im,ei={mms:Rs(),mse:vm(),hls:!!((Tm=je.canPlayType)!=null&&Tm.call(je,"application/x-mpegurl")||(Im=je.canPlayType)!=null&&Im.call(je,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Em,xm,ke={mp4:!!((Em=je.canPlayType)!=null&&Em.call(je,"video/mp4")),webm:!!((xm=je.canPlayType)!=null&&xm.call(je,"video/webm")),cmaf:!0},Ls,Pm,Ms,Am,Cs,wm,Ds,km,Bs,Rm,Os,$m,Re={h264:!!((Pm=(Ls=Et())==null?void 0:Ls.isTypeSupported)!=null&&Pm.call(Ls,Xx)),h265:!!((Am=(Ms=Et())==null?void 0:Ms.isTypeSupported)!=null&&Am.call(Ms,Zx)),vp9:!!((wm=(Cs=Et())==null?void 0:Cs.isTypeSupported)!=null&&wm.call(Cs,Lm)),av1:!!((km=(Ds=Et())==null?void 0:Ds.isTypeSupported)!=null&&km.call(Ds,Mm)),aac:!!((Rm=(Bs=Et())==null?void 0:Bs.isTypeSupported)!=null&&Rm.call(Bs,eP)),opus:!!(($m=(Os=Et())==null?void 0:Os.isTypeSupported)!=null&&$m.call(Os,tP))},Oi=(Re.h264||Re.h265)&&Re.aac,ti,iP=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Mm}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Lm}})]);ti={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{iP()}catch(a){console.error(a)}var Vi=ei.hls&&ke.mp4,Cm=()=>Object.keys(Re).filter(a=>Re[a]),Dm=(a,e=!1,t=!1)=>{let i=ei.mse||ei.mms&&t;return a.filter(r=>{switch(r){case"DASH_SEP":return i&&ke.mp4&&Oi;case"DASH_WEBM":return i&&ke.webm&&Re.vp9&&Re.opus;case"DASH_WEBM_AV1":return i&&ke.webm&&Re.av1&&Re.opus;case"DASH_STREAMS":return i&&(ke.mp4&&Oi||ke.webm&&(Re.vp9||Re.av1)&&(Re.opus||Re.aac));case"DASH_LIVE":return ei.mse&&ke.mp4&&Oi;case"DASH_LIVE_CMAF":return i&&ke.mp4&&Oi&&ke.cmaf;case"DASH_ONDEMAND":return i&&ke.mp4&&Oi;case"HLS":case"HLS_ONDEMAND":return Vi||e&&ei.mse&&ke.mp4&&Oi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Vi;case"MPEG":return ke.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ei.webrtc&&ei.ws&&Re.h264&&(ke.mp4||ke.webm);default:return(0,ct.assertNever)(r)}})},$s=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return ti?ti[t].smooth?[t,e]:ti[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ti?ti[t].powerEfficient?[t,e]:ti[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,ct.assertNever)(a)}return[e,t]},Bm=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...$s(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ct.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...$s(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...$s(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...$s(a),...r,"HLS","HLS_ONDEMAND"];default:(0,ct.assertNever)(e)}return Vi?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Om=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=ct.clientChecker.isMac&&ct.clientChecker.isSafari;if(ct.clientChecker.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:(0,ct.assertNever)(a)}else Vi&&!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"]},ou=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Vm=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Vs.default)(t.value.split("."),0)}for(let t of a){let i=(0,Vs.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Vs.default)(e.value.split("."),0)};var _i=require("@vkontakte/videoplayer-shared"),_m=a=>{if(!a)return{id:"EmptyResponse",category:_i.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:_i.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:_i.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:_i.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:_i.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Ni=(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};var v=require("@vkontakte/videoplayer-shared");var Gi=ze(kr(),1);var rP=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},aP=a=>window.clearTimeout(a),Nm=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Fm=!Nm(window.requestIdleCallback)||!Nm(window.cancelIdleCallback),uu=Fm?rP:window.requestIdleCallback,FL=Fm?aP:window.cancelIdleCallback;var wb=ze(ys(),1);var Ge=require("@vkontakte/videoplayer-shared"),sP=16,qm=!1;try{qm=Ge.clientChecker.isSafari&&!!Ge.clientChecker.macVersion&&Ge.clientChecker.macVersion<=sP}catch(a){console.error(a)}var lu=class{constructor(e){this.bufferFull$=new Ge.Subject;this.error$=new Ge.Subject;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:Ge.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i;qm&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),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 r;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.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:Ge.ErrorCategory.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:(0,Ge.assertNever)(t)}}},Um=lu;var cu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var I=require("@vkontakte/videoplayer-shared");var X=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=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,r),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 r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 Fi=class extends X{};var _r=class extends X{};var Nr=class extends X{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Fr=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qr=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ur=class extends X{constructor(e,t){super(e,t),this.data=this.content}};var ue=class extends X{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ii=class extends ue{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 i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}};var Hr=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var jr=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gr=class extends ue{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 Wr=class extends ue{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Yr=class extends ue{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Qr=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zr=class extends ue{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 Kr=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Jr=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xr=class extends ue{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zr=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends ue{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ta=class extends ue{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ia=class extends ue{constructor(t,i){super(t,i);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 r=0;r<this.sampleCount;r++)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 oP={ftyp:Nr,moov:Fr,moof:qr,mdat:Ur,sidx:ii,trak:Hr,mdia:Qr,mfhd:Xr,tkhd:zr,traf:Zr,tfhd:ea,tfdt:ta,trun:ia,minf:Kr,sv3d:jr,st3d:Gr,prhd:Wr,proj:Jr,equi:Yr,uuid:_r,unknown:Fi},ri=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=oP[e];return i?new i(t,new a):new Fi(t,new a)}};var qi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),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 lP=new TextDecoder("ascii"),cP=a=>lP.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",dP=a=>{let e=new ii(a,new ri),t=e.earliestPresentationTime/e.timescale*1e3,i=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:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},pP=(a,e)=>{let i=new ri().parse(a),r=new qi(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,d)},hP=(a,e)=>{let i=new ri().parse(a),s=new qi(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((d,p)=>d+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},fP=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}}},i=new ri().parse(a),r=new qi(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.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},Hm={validateData:cP,parseInit:fP,getIndexRange:()=>{},parseSegments:dP,parseFeedableSegmentChunk:pP,getSegmentEndTime:hP};var xt=require("@vkontakte/videoplayer-shared");var Gm=require("@vkontakte/videoplayer-shared");var jm={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"}},Wm=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 i=ra(a,t),r=i in jm,s=r?jm[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,l=ra(u),d=c*2**((o-1)*8)+l,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ra=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},tt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ra(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:(0,Gm.assertNever)(e)}},ai=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Wm(i);if(!e(r))return;r.type==="master"&&ai(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Ym=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Wm(a);return ai(r.value,({tag:s,type:n,value:o})=>(s===17143?e=tt(o,n):s===17026?t=tt(o,n):s===17029&&(i=tt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Qm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],mP=[231,22612,22743,167,171,163,160,175],bP=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,c,l=!1,d=0;return ai(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let S=tt(m,h);c=ra(S)}else p!==21420&&(c=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=tt(m,h):p===17545?r=tt(m,h):p===21420&&c===475249515?u=tt(m,h):p===374648427?ai(m,({tag:S,type:x,value:A})=>S===30321?(l=tt(A,x)===1,!1):!0):s&&n&&Qm.includes(p)&&(o=!0),!o}),(0,xt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,xt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,xt.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},gP=a=>{if((0,xt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},SP=(a,e)=>{let t=!1,i=!1,r=o=>(0,xt.isNonNullable)(o.time)&&(0,xt.isNonNullable)(o.position),s=[],n;return ai(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=tt(c,u));break;case 183:break;case 241:n&&(n.position=tt(c,u));break;default:t&&Qm.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:l}=o,d=s[u+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},vP=a=>{let e=0,t=!1;try{ai(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):mP.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=[163,160,175].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},zm={validateData:Ym,parseInit:bP,getIndexRange:gP,parseSegments:SP,parseFeedableSegmentChunk:vP};var Ui=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return zm;case"mp4":return Hm}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Su=ze(gb(),1);var gu=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var ji=require("@vkontakte/videoplayer-shared");var Sb=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var vb=a=>{var e;try{let t=ZP(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(c=>{s[c[0]]=c.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let c=o[u];(typeof c=="undefined"||c==="")&&delete o[u]}),o}return null}catch(t){return null}};function ZP(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",l=`^(?:(?<langtag>${`
|
|
57
|
+
[selected audio track] ${p==null?void 0:p.id}
|
|
58
|
+
`}),p&&cm(r,u,p,o)};var pe=a=>new URL(a).hostname;var B=require("@vkontakte/videoplayer-shared");var pm=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"))},we=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!pm(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return pm(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};var De=require("@vkontakte/videoplayer-shared");var ut=require("@vkontakte/videoplayer-shared");function he(){return(0,ut.now)()}function ru(a){return he()-a}function au(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(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 hm(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Oi(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",m=7e3,g=2e3,S=()=>{if(u)return;(0,ut.assertNonNullable)(c);let _=ru(c),D;if(_<g){D=g-_,setTimeout(S,D);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new r,V()},x=_=>(s=_,K),A=_=>(d=_,K),T=()=>(p="json",K),P=()=>{if(!u){if(--l>=0){S(),i&&i();return}u=!0,d&&d(),t&&t()}},w=_=>(h=_,K),V=()=>{c=he(),n=new r,n.open("get",a);let _=0,D,ee=0,le=()=>((0,ut.assertNonNullable)(c),Math.max(c,Math.max(D||0,ee||0)));if(s&&n.addEventListener("progress",E=>{let H=he();s.updateChunk&&E.loaded>_&&(s.updateChunk(le(),E.loaded-_),_=E.loaded,D=H)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>P())),n.addEventListener("load",()=>{if(u)return;(0,ut.assertNonNullable)(n);let E=n.status;if(E>=200&&E<300){if(n.response.byteLength&&s){let H=n.response.byteLength-_;H&&s.updateChunk&&s.updateChunk(le(),H)}n.responseType==="json"&&!Object.values(n.response).length?P():(d&&d(),e(n.response))}else P()}),n.addEventListener("error",()=>{P()}),h){let E=()=>{(0,ut.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ee=he(),n.removeEventListener("readystatechange",E))};n.addEventListener("readystatechange",E)}return n.responseType=p,n.send(),K},K={withBitrateReporting:x,withParallel:w,withJSONResponse:T,withRetryCount:_=>(l=_,K),withRetryInterval:(_,D)=>((0,ut.isNonNullable)(_)&&(g=_),(0,ut.isNonNullable)(D)&&(m=D),K),withTimeout:_=>(o=_,K),withFinally:A,send:V,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return K}var Lr=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,i){return{start:e,end:t,bytes:i}}_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 i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/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(r)}/${Math.round(i)} 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,i){return this.intervals.push(this._createInterval(e,t,i)),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 Mr=class{constructor(e,t,i,r,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=i,this.MAX_PARALLEL_REQUESTS=r,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 i=he(),r=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=he()-i,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=Oi(t,s,()=>r("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=he()}_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=he();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!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,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,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}`),i(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=i,s._retryCB=r,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 fm=require("@vkontakte/videoplayer-shared"),Ps=1e4,su=3;var qx=6e4,Hx=10,jx=1,Gx=500,Cr=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.soundProhibitedEvent$=new fm.Subject,this.chunkRateEstimator=new Lr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=au(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=au(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-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 r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.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,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,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)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,De.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{hm(r,"progress",()=>{r.buffered.length?(r.currentTime=r.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 Mr(su,Ps,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let P=s&&(!c||c===this.rep);return P||t("Not running!"),P},h=(P,w,V)=>{u&&u.abort(),u=Oi(this.urlResolver.resolve(P,!1),w,V,()=>this._retryCallback()).withTimeout(Ps).withBitrateReporting(this.bitrateSwitcher).withRetryCount(su).withFinally(()=>{u=null}).send()},p=(P,w,V)=>{(0,De.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(P,!1),w,V,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=P=>{let w=i.playbackRate;i.playbackRate!==P&&(t(`Playback rate switch: ${w}=>${P}`),i.playbackRate=P)},g=P=>{this.lowLatency=P,t(`lowLatency changed to ${P}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let P=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let V=he()-1e4,W=0;for(let N=0;N<this.bufferStates.length;N++){let z=this.bufferStates[N];P=Math.min(P,z.buf),z.ts<V&&W++}this.bufferStates.splice(0,W),t(`update playback rate; minBuffer=${P} drop=${W} jitter=${this.sourceJitter}`);let J=P-jx;this.sourceJitter>=0?J-=this.sourceJitter/2:this.sourceJitter-=1,J>3?m(1.15):J>1?m(1.1):J>.3?m(1.05):m(1)}},x=P=>{let w,V=()=>w&&w.start?w.start.length:0,W=E=>w.start[E]/1e3,J=E=>w.dur[E]/1e3,N=E=>w.fragIndex+E,z=(E,H)=>({chunkIdx:N(E),startTS:W(E),dur:J(E),discontinuity:H}),K=()=>{let E=0;if(w&&w.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,te=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,se=H;this.sourceJitter>1&&(se+=this.sourceJitter-1);let ce=w.dur.length-1;for(;ce>=0&&(se-=w.dur[ce],!(se<=0));--ce);E=Math.min(ce,w.dur.length-1-te),E=Math.max(E,0)}return z(E,!0)},_=E=>{let H=V();if(!(H<=0)){if((0,De.isNonNullable)(E)){for(let te=0;te<H;te++)if(W(te)>E)return z(te)}return K()}},D=E=>{let H=V(),te=E?E.chunkIdx+1:0,se=te-w.fragIndex;if(!(H<=0)){if(!E||se<0||se-H>Hx)return t(`Resync: offset=${se} bChunks=${H} chunk=`+JSON.stringify(E)),K();if(!(se>=H))return z(te-w.fragIndex,!1)}},ee=(E,H,te)=>{l&&l.abort(),l=Oi(this.urlResolver.resolve(E,!0,this.lowLatency),H,te,()=>this._retryCallback()).withTimeout(Ps).withRetryCount(su).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(E,H)=>{ee(P,te=>{if(!d())return;w=te;let se=!!w.lowLatency;se!==this.lowLatency&&g(se);let ce=0;for(let ye=0;ye<w.dur.length;++ye)ce+=w.dur[ye];ce>0&&((0,De.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ce/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,E(_(H))},()=>this._handleNetworkError())},nextChunk:D}},A=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,De.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:P=>{let{videoElement:w,logger:V}=this.params,W=x(e.jidxUrl),J,N,z,K,_=0,D,ee,le,E=()=>{D&&(clearTimeout(D),D=void 0);let R=Math.max(Gx,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Te=_+R,$e=he(),Ve=Math.min(1e4,Te-$e);_=$e;let $t=()=>{l||d()&&W.seek(()=>{d()&&(_=he(),H(),E())})};Ve>0?D=window.setTimeout(()=>{this.paused?E():$t()},Ve):$t()},H=()=>{let R;for(;R=W.nextChunk(K);)K=R,pt(R);let Te=W.nextChunk(z);if(Te){if(z&&Te.discontinuity){V("Detected discontinuity; restarting playback"),this.paused?E():(A(),this._initPlayerWith(e));return}ye(Te)}else E()},te=(R,Te)=>{if(!d()||!this.sourceBuffer)return;let $e,Ve,$t,ci=Lt=>{window.setTimeout(()=>{d()&&te(R,Te)},Lt)};if(this.sourceBuffer.updating)V("Source buffer is updating; delaying appendBuffer"),ci(100);else{let Lt=he(),Ht=w.currentTime;!this.paused&&w.buffered.length>1&&ee===Ht&&Lt-le>500&&(V("Stall suspected; trying to fix"),this._fixupStall()),ee!==Ht&&(ee=Ht,le=Lt);let di=this._getBufferSizeSec();if(di>30)V(`Buffered ${di} seconds; delaying appendBuffer`),ci(2e3);else try{this.sourceBuffer.appendBuffer(R),this.videoPlayStarted?(this.bufferStates.push({ts:Lt,buf:di}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Te&&Te()}catch(Ji){if(Ji.name==="QuotaExceededError")V("QuotaExceededError; delaying appendBuffer"),$t=this.sourceBuffer.buffered.length,$t!==0&&($e=this.sourceBuffer.buffered.start(0),Ve=Ht,Ve-$e>4&&this.sourceBuffer.remove($e,Ve-3)),ci(1e3);else throw Ji}}},se=()=>{N&&J&&(V([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(z)]),te(N,function(){N=null,H()}))},ce=R=>e.fragUrlTemplate.replace("%%id%%",R.chunkIdx),ye=R=>{d()&&p(ce(R),(Te,$e)=>{if(d()){if($e/=1e3,N=Te,z=R,n=R.startTS,$e){let Ve=Math.min(10,R.dur/$e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ve:Ve}se()}},()=>this._handleNetworkError())},pt=R=>{d()&&((0,De.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ce(R),!1)))},Rt=R=>{d()&&(e.cachedHeader=R,te(R,()=>{J=!0,se()}))};s=!0,W.seek(R=>{if(d()){if(_=he(),!R){E();return}K=R,!(0,De.isNullable)(P)||R.startTS>P?ye(R):(z=R,H())}},P),e.cachedHeader?Rt(e.cachedHeader):h(e.headerUrl,Rt,()=>this._handleNetworkError())},stop:A,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,De.isNonNullable)(r)&&(r+=.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,(0,De.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,De.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let m=he();if(this.chunkRateEstimator.addInterval(h,m,p)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:S}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&ru(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=he();d<o&&(n=h),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Oi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Ps).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;we(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&r.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):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({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))},qx))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var ae=require("@vkontakte/videoplayer-shared"),nu=class{constructor(){this.onDroopedVideoFramesLimit$=new ae.Subject;this.subscription=new ae.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ae.Subject;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&&!(0,ae.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,ae.isHigher)(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((0,ae.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ae.interval)(this.droppedFramesChecker.checkTime).pipe((0,ae.filter)(()=>this.playing),(0,ae.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,ae.debounce)(this.droppedFramesChecker.checkTime)),i=(0,ae.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),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 i,r;let t=(r=(i=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,ae.isLower)(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[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}},As=nu;var ws=require("@vkontakte/videoplayer-shared"),mm=require("@vkontakte/videoplayer-shared");var Dr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Wx=(a,e)=>new ws.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Dr()))},{...i,...e});r.observe(a);let s=(0,mm.fromEvent)(document,"visibilitychange").pipe((0,ws.map)(n=>!document.hidden||Dr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe}}),Ge=Wx;var Yx=["paused","playing","ready"],Qx=["paused","playing","ready"],Br=class{constructor(e){this.subscription=new B.Subscription;this.videoState=new j("stopped");this.representations$=new B.ValueSubject([]);this.textTracksManager=new je;this.droppedFramesManager=new As;this.maxSeekBackTime$=new B.ValueSubject(1/0);this.zeroTime$=new B.ValueSubject(void 0);this.liveOffset=new vt;this._dashCb=e=>{var t,i,r,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:B.ErrorCategory.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=(i=Ft(u.name))!=null?i:(0,B.videoSizeToQuality)(u.video),d=u.bitrate/1e3,h={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.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),(0,B.isNonNullable)(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(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="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(Qx.includes(e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&Yx.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(me(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="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(me(this.params.source.url,u))}return;default:return(0,B.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:B.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};(0,B.merge)(this.videoState.stateChangeStarted$.pipe((0,B.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,B.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})}),this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),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(pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ae(this.video);this.subscription.add(this.representations$.pipe((0,B.map)(r=>r.map(({track:s})=>s)),(0,B.filter)(r=>!!r.length),(0,B.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,B.filterChanged)(),(0,B.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,B.combine)({zeroTime:this.zeroTime$.pipe((0,B.filter)(B.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(Pe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(He(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ge(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let s=r&&(0,B.videoQualityToHeight)(r);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.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(0,B.assertNever)(r.to)}},t)).add((0,B.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,B.observableFrom)(["init"])).pipe((0,B.debounce)(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),xe(this.video)}createLiveDashPlayer(){let e=new Cr({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,h,p,m;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(),i=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,B.isNonNullable)(t)?t:Ut(e.map(({track:g})=>g),{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=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let g=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;(0,B.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;(0,B.assertNonNullable)(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(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(me(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var bm=Br;var lt=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var U=require("@vkontakte/videoplayer-shared");var ks=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];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}},Vi=class extends ks{constructor(){super(),this.listeners||ks.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)}},Or=class{constructor(){Object.defineProperty(this,"signal",{value:new Vi,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){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 i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Or.prototype[Symbol.toStringTag]="AbortController",Vi.prototype[Symbol.toStringTag]="AbortSignal");function Rs(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 ou(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Rs({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},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(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Vr=Rs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),gm=Vr?ou({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,It=Vr?gm.fetch:window.fetch,AL=Vr?gm.Request:window.Request,et=Vr?Or:window.AbortController,wL=Vr?Vi:window.AbortSignal;var _s=Ne(Bi(),1);var Et=()=>window.ManagedMediaSource||window.MediaSource,$s=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Sm=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},vm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ct=require("@vkontakte/videoplayer-shared"),We=document.createElement("video"),Jx='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Xx='video/mp4; codecs="hev1.1.6.L93.B0"',$m='video/webm; codecs="vp09.00.10.08"',Lm='video/webm; codecs="av01.0.00M.08"',Zx='audio/mp4; codecs="mp4a.40.2"',eP='audio/webm; codecs="opus"',ym,Tm,ti={mms:$s(),mse:Sm(),hls:!!((ym=We.canPlayType)!=null&&ym.call(We,"application/x-mpegurl")||(Tm=We.canPlayType)!=null&&Tm.call(We,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Im,Em,ke={mp4:!!((Im=We.canPlayType)!=null&&Im.call(We,"video/mp4")),webm:!!((Em=We.canPlayType)!=null&&Em.call(We,"video/webm")),cmaf:!0},Ms,xm,Cs,Pm,Ds,Am,Bs,wm,Os,km,Vs,Rm,Re={h264:!!((xm=(Ms=Et())==null?void 0:Ms.isTypeSupported)!=null&&xm.call(Ms,Jx)),h265:!!((Pm=(Cs=Et())==null?void 0:Cs.isTypeSupported)!=null&&Pm.call(Cs,Xx)),vp9:!!((Am=(Ds=Et())==null?void 0:Ds.isTypeSupported)!=null&&Am.call(Ds,$m)),av1:!!((wm=(Bs=Et())==null?void 0:Bs.isTypeSupported)!=null&&wm.call(Bs,Lm)),aac:!!((km=(Os=Et())==null?void 0:Os.isTypeSupported)!=null&&km.call(Os,Zx)),opus:!!((Rm=(Vs=Et())==null?void 0:Vs.isTypeSupported)!=null&&Rm.call(Vs,eP))},_i=(Re.h264||Re.h265)&&Re.aac,ii,tP=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Lm}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:$m}})]);ii={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{tP()}catch(a){console.error(a)}var Ni=ti.hls&&ke.mp4,Mm=()=>Object.keys(Re).filter(a=>Re[a]),Cm=(a,e=!1,t=!1)=>{let i=ti.mse||ti.mms&&t;return a.filter(r=>{switch(r){case"DASH_SEP":return i&&ke.mp4&&_i;case"DASH_WEBM":return i&&ke.webm&&Re.vp9&&Re.opus;case"DASH_WEBM_AV1":return i&&ke.webm&&Re.av1&&Re.opus;case"DASH_STREAMS":return i&&(ke.mp4&&_i||ke.webm&&(Re.vp9||Re.av1)&&(Re.opus||Re.aac));case"DASH_LIVE":return ti.mse&&ke.mp4&&_i;case"DASH_LIVE_CMAF":return i&&ke.mp4&&_i&&ke.cmaf;case"DASH_ONDEMAND":return i&&ke.mp4&&_i;case"HLS":case"HLS_ONDEMAND":return Ni||e&&ti.mse&&ke.mp4&&_i;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Ni;case"MPEG":return ke.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ti.webrtc&&ti.ws&&Re.h264&&(ke.mp4||ke.webm);default:return(0,ct.assertNever)(r)}})},Ls=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 ii?ii[t].smooth?[t,e]:ii[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ii?ii[t].powerEfficient?[t,e]:ii[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,ct.assertNever)(a)}return[e,t]},Dm=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Ls(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ct.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Ls(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ls(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ls(a),...r,"HLS","HLS_ONDEMAND"];default:(0,ct.assertNever)(e)}return Ni?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Bm=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=ct.clientChecker.isMac&&ct.clientChecker.isSafari;if(ct.clientChecker.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:(0,ct.assertNever)(a)}else Ni&&!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"]},uu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Om=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,_s.default)(t.value.split("."),0)}for(let t of a){let i=(0,_s.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,_s.default)(e.value.split("."),0)};var Fi=require("@vkontakte/videoplayer-shared"),Vm=a=>{if(!a)return{id:"EmptyResponse",category:Fi.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Fi.ErrorCategory.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:Fi.ErrorCategory.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:Fi.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Fi.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Ui=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared");var Yi=Ne(Bi(),1);var iP=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},rP=a=>window.clearTimeout(a),_m=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Nm=!_m(window.requestIdleCallback)||!_m(window.cancelIdleCallback),lu=Nm?iP:window.requestIdleCallback,NL=Nm?rP:window.cancelIdleCallback;var wb=Ne(Ts(),1);var Ye=require("@vkontakte/videoplayer-shared"),aP=16,Fm=!1;try{Fm=Ye.clientChecker.isSafari&&!!Ye.clientChecker.macVersion&&Ye.clientChecker.macVersion<=aP}catch(a){console.error(a)}var cu=class{constructor(e){this.bufferFull$=new Ye.Subject;this.error$=new Ye.Subject;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:Ye.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i;Fm&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),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 r;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.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:Ye.ErrorCategory.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:(0,Ye.assertNever)(t)}}},Um=cu;var du=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var I=require("@vkontakte/videoplayer-shared");var X=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=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,r),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 r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 qi=class extends X{};var _r=class extends X{};var Nr=class extends X{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Fr=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ur=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qr=class extends X{constructor(e,t){super(e,t),this.data=this.content}};var ue=class extends X{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ri=class extends ue{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 i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Hr=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var jr=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gr=class extends ue{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 Wr=class extends ue{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Yr=class extends ue{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Qr=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zr=class extends ue{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 Kr=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Jr=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xr=class extends ue{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zr=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends ue{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ta=class extends ue{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ia=class extends ue{constructor(t,i){super(t,i);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 r=0;r<this.sampleCount;r++)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 nP={ftyp:Nr,moov:Fr,moof:Ur,mdat:qr,sidx:ri,trak:Hr,mdia:Qr,mfhd:Xr,tkhd:zr,traf:Zr,tfhd:ea,tfdt:ta,trun:ia,minf:Kr,sv3d:jr,st3d:Gr,prhd:Wr,proj:Jr,equi:Yr,uuid:_r,unknown:qi},ai=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=nP[e];return i?new i(t,new a):new qi(t,new a)}};var Hi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),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 uP=new TextDecoder("ascii"),lP=a=>uP.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",cP=a=>{let e=new ri(a,new ai),t=e.earliestPresentationTime/e.timescale*1e3,i=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:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},dP=(a,e)=>{let i=new ai().parse(a),r=new Hi(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.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)},pP=(a,e)=>{let i=new ai().parse(a),s=new Hi(i).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,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},hP=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}}},i=new ai().parse(a),r=new Hi(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.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},qm={validateData:lP,parseInit:hP,getIndexRange:()=>{},parseSegments:cP,parseFeedableSegmentChunk:dP,getSegmentEndTime:pP};var xt=require("@vkontakte/videoplayer-shared");var jm=require("@vkontakte/videoplayer-shared");var Hm={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"}},Gm=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 i=ra(a,t),r=i in Hm,s=r?Hm[i].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=ra(u),d=l*2**((o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},ra=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},tt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ra(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:(0,jm.assertNever)(e)}},si=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Gm(i);if(!e(r))return;r.type==="master"&&si(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Wm=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Gm(a);return si(r.value,({tag:s,type:n,value:o})=>(s===17143?e=tt(o,n):s===17026?t=tt(o,n):s===17029&&(i=tt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Ym=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],fP=[231,22612,22743,167,171,163,160,175],mP=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return si(a,({tag:h,type:p,value:m,valueSize:g})=>{if(h===21419){let S=tt(m,p);l=ra(S)}else h!==21420&&(l=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+g):h===357149030?s=!0:h===290298740?n=!0:h===2807729?i=tt(m,p):h===17545?r=tt(m,p):h===21420&&l===475249515?u=tt(m,p):h===374648427?si(m,({tag:S,type:x,value:A})=>S===30321?(c=tt(A,x)===1,!1):!0):s&&n&&Ym.includes(h)&&(o=!0),!o}),(0,xt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,xt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,xt.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*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}}}},bP=a=>{if((0,xt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},gP=(a,e)=>{let t=!1,i=!1,r=o=>(0,xt.isNonNullable)(o.time)&&(0,xt.isNonNullable)(o.position),s=[],n;return si(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=tt(l,u));break;case 183:break;case 241:n&&(n.position=tt(l,u));break;default:t&&Ym.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(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}}})},SP=a=>{let e=0,t=!1;try{si(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):fP.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=[163,160,175].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Qm={validateData:Wm,parseInit:mP,getIndexRange:bP,parseSegments:gP,parseFeedableSegmentChunk:SP};var ji=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Qm;case"mp4":return qm}}throw new ReferenceError(`Unsupported mime type ${a}`)};var vu=Ne(bb(),1),yb=Ne(Bi(),1);var Su=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var Wi=require("@vkontakte/videoplayer-shared");var gb=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Sb=a=>{var e;try{let t=XP(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function XP(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
59
59
|
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
60
60
|
(-(?<script>[a-z]{4}))?
|
|
61
61
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
62
62
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
63
63
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
64
64
|
(?:-(?<privateuse>(?:${e})))?
|
|
65
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(l,"i")}var yb=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?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),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Pt=(a,e)=>{let t=a;t=(0,Su.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Su.default)(t,n,(o,u)=>(0,ji.isNullable)(s)?o:(0,ji.isNullable)(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Tb=(a,e)=>{var P,w,F,G,W,Y,K,J,D,V,ee,le,E,U,te,se,ce,ye,pt,Rt,R,Te,$e,Oe,$t,li,Lt,Ut,ci,zi,Mu,Cu,Du,Bu,Ou,Vu,_u,Nu,Fu,qu,Uu,Hu,ju,Gu,Wu,Yu,Qu,zu,Ku,Ju,Xu,Zu,el,tl,il,rl,al,sl,nl,ol,ul,ll,cl;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=s.getElementsByTagName("Period")[0],o=(F=(w=(P=s.querySelector("BaseURL"))==null?void 0:P.textContent)==null?void 0:w.trim())!=null?F:"",u=n.children,c=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=l?new Date(l).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],S=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=yb(h);else if(m){let me=yb(m);(0,ji.isNonNullable)(me)&&(p=me)}else S&&(p=parseInt(S,10));let x=0,A=(W=(G=s.getAttribute("profiles"))==null?void 0:G.split(","))!=null?W:[];for(let me of u){let Xb=(Y=me.getAttribute("id"))!=null?Y:"id"+(x++).toString(10),Ki=(K=me.getAttribute("mimeType"))!=null?K:"",en=(J=me.getAttribute("codecs"))!=null?J:"",tn=(D=me.getAttribute("contentType"))!=null?D:Ki==null?void 0:Ki.split("/")[0],Zb=(ee=(V=me.getAttribute("profiles"))==null?void 0:V.split(","))!=null?ee:[],dl=(E=vb((le=me.getAttribute("lang"))!=null?le:""))!=null?E:{},eg=(ce=(se=(te=(U=me.querySelector("Label"))==null?void 0:U.textContent)==null?void 0:te.trim())!=null?se:me.getAttribute("label"))!=null?ce:void 0,tg=me.querySelectorAll("Representation"),ig=me.querySelector("SegmentTemplate"),rg=(pt=(ye=me.querySelector("Role"))==null?void 0:ye.getAttribute("value"))!=null?pt:void 0,Ji=tn,de={id:Xb,language:dl.language,isDefault:rg==="main",label:eg,codecs:en,hdr:Ji==="video"&&gu(en),mime:Ki,representations:[]};for(let ie of tg){let ag=(Rt=ie.getAttribute("lang"))!=null?Rt:void 0,sg=(R=ie.getAttribute("label"))!=null?R:void 0,ng=(Oe=($e=(Te=ie.querySelector("BaseURL"))==null?void 0:Te.textContent)==null?void 0:$e.trim())!=null?Oe:"",xa=new URL(ng||o,e).toString(),di=($t=ie.getAttribute("mimeType"))!=null?$t:Ki,Pa=(Lt=(li=ie.getAttribute("codecs"))!=null?li:en)!=null?Lt:"",Aa;if(tn==="text"){let Mt=ie.getAttribute("id")||"",wa=((Ut=dl.privateuse)==null?void 0:Ut.includes("x-auto"))||Mt.includes("_auto"),Ht=ie.querySelector("SegmentTemplate");if(Ht){let Xi={representationId:(ci=ie.getAttribute("id"))!=null?ci:void 0,bandwidth:(zi=ie.getAttribute("bandwidth"))!=null?zi:void 0},ka=parseInt((Mu=ie.getAttribute("bandwidth"))!=null?Mu:"",10)/1e3,Ra=(Du=parseInt((Cu=Ht.getAttribute("startNumber"))!=null?Cu:"",10))!=null?Du:1,pi=parseInt((Bu=Ht.getAttribute("timescale"))!=null?Bu:"",10),rn=(Ou=Ht.querySelectorAll("SegmentTimeline S"))!=null?Ou:[],hi=Ht.getAttribute("media");if(!hi)continue;let $a=[],La=0,Ma="",fi=0,Zi=Ra,be=0;for(let Ye of rn){let jt=parseInt((Vu=Ye.getAttribute("d"))!=null?Vu:"",10),Ve=parseInt((_u=Ye.getAttribute("r"))!=null?_u:"",10)||0,Ct=parseInt((Nu=Ye.getAttribute("t"))!=null?Nu:"",10);be=Number.isFinite(Ct)?Ct:be;let Gt=jt/pi*1e3,Dt=be/pi*1e3;for(let rt=0;rt<Ve+1;rt++){let Bt=Pt(hi,{...Xi,segmentNumber:Zi.toString(10),segmentTime:(be+rt*jt).toString(10)}),mi=(Dt!=null?Dt:0)+rt*Gt,tr=mi+Gt;Zi++,$a.push({time:{from:mi,to:tr},url:Bt})}be+=(Ve+1)*jt,La+=(Ve+1)*Gt}fi=be/pi*1e3,Ma=Pt(hi,{...Xi,segmentNumber:Zi.toString(10),segmentTime:be.toString(10)});let er={time:{from:fi,to:1/0},url:Ma},ht={type:"template",baseUrl:xa,segmentTemplateUrl:hi,initUrl:"",totalSegmentsDurationMs:La,segments:$a,nextSegmentBeyondManifest:er,timescale:pi};Aa={id:Mt,kind:"text",segmentReference:ht,profiles:[],duration:p,bitrate:ka,mime:"",codecs:"",width:0,height:0,isAuto:wa}}else Aa={id:Mt,isAuto:wa,kind:"text",url:xa}}else{let Mt=(qu=(Fu=ie.getAttribute("contentType"))!=null?Fu:di==null?void 0:di.split("/")[0])!=null?qu:tn,wa=(Hu=(Uu=me.getAttribute("profiles"))==null?void 0:Uu.split(","))!=null?Hu:[],Ht=parseInt((ju=ie.getAttribute("width"))!=null?ju:"",10),Xi=parseInt((Gu=ie.getAttribute("height"))!=null?Gu:"",10),ka=parseInt((Wu=ie.getAttribute("bandwidth"))!=null?Wu:"",10)/1e3,Ra=(Yu=ie.getAttribute("frameRate"))!=null?Yu:"",pi=(Qu=ie.getAttribute("quality"))!=null?Qu:void 0,rn=Ra?Sb(Ra):void 0,hi=(zu=ie.getAttribute("id"))!=null?zu:"id"+(x++).toString(10),$a=Mt==="video"?`${Xi}p`:Mt==="audio"?`${ka}Kbps`:Pa,La=`${hi}@${$a}`,Ma=[...A,...Zb,...wa],fi,Zi=ie.querySelector("SegmentBase"),be=(Ku=ie.querySelector("SegmentTemplate"))!=null?Ku:ig;if(Zi){let ht=(Xu=(Ju=ie.querySelector("SegmentBase Initialization"))==null?void 0:Ju.getAttribute("range"))!=null?Xu:"",[Ye,jt]=ht.split("-").map(Bt=>parseInt(Bt,10)),Ve={from:Ye,to:jt},Ct=(Zu=ie.querySelector("SegmentBase"))==null?void 0:Zu.getAttribute("indexRange"),[Gt,Dt]=Ct?Ct.split("-").map(Bt=>parseInt(Bt,10)):[],rt=Ct?{from:Gt,to:Dt}:void 0;fi={type:"byteRange",url:xa,initRange:Ve,indexRange:rt}}else if(be){let ht={representationId:(el=ie.getAttribute("id"))!=null?el:void 0,bandwidth:(tl=ie.getAttribute("bandwidth"))!=null?tl:void 0},Ye=parseInt((il=be.getAttribute("timescale"))!=null?il:"",10),jt=(rl=be.getAttribute("initialization"))!=null?rl:"",Ve=be.getAttribute("media"),Ct=(sl=parseInt((al=be.getAttribute("startNumber"))!=null?al:"",10))!=null?sl:1,Gt=Pt(jt,ht);if(!Ve)throw new ReferenceError("No media attribute in SegmentTemplate");let Dt=(nl=be.querySelectorAll("SegmentTimeline S"))!=null?nl:[],rt=[],Bt=0,mi="",tr=0;if(Dt.length){let Ca=Ct,Qe=0;for(let bi of Dt){let at=parseInt((ol=bi.getAttribute("d"))!=null?ol:"",10),Wt=parseInt((ul=bi.getAttribute("r"))!=null?ul:"",10)||0,Da=parseInt((ll=bi.getAttribute("t"))!=null?ll:"",10);Qe=Number.isFinite(Da)?Da:Qe;let an=at/Ye*1e3,sn=Qe/Ye*1e3;for(let Ba=0;Ba<Wt+1;Ba++){let ug=Pt(Ve,{...ht,segmentNumber:Ca.toString(10),segmentTime:(Qe+Ba*at).toString(10)}),pl=(sn!=null?sn:0)+Ba*an,lg=pl+an;Ca++,rt.push({time:{from:pl,to:lg},url:ug})}Qe+=(Wt+1)*at,Bt+=(Wt+1)*an}tr=Qe/Ye*1e3,mi=Pt(Ve,{...ht,segmentNumber:Ca.toString(10),segmentTime:Qe.toString(10)})}else if((0,ji.isNonNullable)(p)){let Qe=parseInt((cl=be.getAttribute("duration"))!=null?cl:"",10)/Ye*1e3,bi=Math.ceil(p/Qe),at=0;for(let Wt=1;Wt<bi;Wt++){let Da=Pt(Ve,{...ht,segmentNumber:Wt.toString(10),segmentTime:at.toString(10)});rt.push({time:{from:at,to:at+Qe},url:Da}),at+=Qe}tr=at,mi=Pt(Ve,{...ht,segmentNumber:bi.toString(10),segmentTime:at.toString(10)})}let og={time:{from:tr,to:1/0},url:mi};fi={type:"template",baseUrl:xa,segmentTemplateUrl:Ve,initUrl:Gt,totalSegmentsDurationMs:Bt,segments:rt,nextSegmentBeyondManifest:og,timescale:Ye}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Mt||!di)continue;let er={video:"video",audio:"audio",text:"text"}[Mt];if(!er)continue;Ji||(Ji=er),Aa={id:La,kind:er,segmentReference:fi,profiles:Ma,duration:p,bitrate:ka,mime:di,codecs:Pa,width:Ht,height:Xi,fps:rn,quality:pi}}de.language||(de.language=ag),de.label||(de.label=sg),de.mime||(de.mime=di),de.codecs||(de.codecs=Pa),de.hdr||(de.hdr=Ji==="video"&&gu(Pa)),de.representations.push(Aa)}Ji&&r[Ji].push(de)}return{dynamic:c,liveAvailabilityStartTime:d,duration:p,streams:r}};var aa=ze(kr(),1);var Ib=require("@vkontakte/videoplayer-shared"),Eb=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s})=>{var o;let n=(o=s?Nt(s):void 0)!=null?o:(0,Ib.videoSizeToQuality)({width:e,height:t});return n&&{id:a,quality:n,bitrate:i,size:{width:e,height:t},fps:r}},xb=({id:a,bitrate:e})=>({id:a,bitrate:e}),_s=(a,e,t)=>{var r;let i=e.indexOf(a);return(r=(0,aa.default)(t,Math.round(t.length*i/e.length)))!=null?r:(0,aa.default)(t,-1)},Pb=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Ab=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Tu=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,aa.default)(i.split("."),0),isDefault:r}),Iu=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,aa.default)(r.split("."),0)}),Ns=a=>"url"in a,We=a=>a.type==="template",sa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var na=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new I.ValueSubject(0);this.onLastSegment$=new I.ValueSubject(!1);this.fullyBuffered$=new I.ValueSubject(!1);this.playingRepresentation$=new I.ValueSubject(void 0);this.playingRepresentationInit$=new I.ValueSubject(void 0);this.error$=new I.Subject;this.gaps=[];this.subscription=new I.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new et;this.switchAbortController=new et;this.destroyAbortController=new et;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,I.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Um(this.sourceBuffer),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,cu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=lt(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,c<l)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,I.assertNonNullable)(i,"No init buffer for starting representation"),(0,I.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchToOld=(0,I.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,I.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,I.isNullable)(s)||(0,I.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,I.assertNonNullable)(r,"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();(0,I.isNonNullable)(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){var u,c;let t=(u=e==null?void 0:e.flatMap(l=>l.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let d=t.find(m=>m.id===l);d&&this.representations.set(l,d);let p=this.representations.get(l);if(!p||!We(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let i=(c=this.switchingToRepresentationId)!=null?c:this.downloadingRepresentationId,r=this.representations.get(i);(0,I.assertNonNullable)(r);let s=this.segments.get(i);(0,I.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,I.assertNonNullable)(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,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.dynamic),this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new et,(0,I.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,I.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,I.isNullable)(o)||(0,I.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,I.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,I.isNonNullable)(u)&&!this.isLive&&(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0,this.maintain(u)}}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new et,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;if((0,I.isNullable)(e)||(0,I.isNullable)(this.downloadingRepresentationId)||(0,I.isNullable)(this.playingRepresentationId)||(0,I.isNullable)(this.sourceBuffer)||(0,I.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,I.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((c=r==null?void 0:r.time.to)!=null?c:0)-((l=r==null?void 0:r.time.from)!=null?l:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=lt(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&cu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=lt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{let p=(0,Gi.default)(o,0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&<(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Gi.default)(i,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;(0,I.isNonNullable)(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?i:[];for(let o of t){if(!o||!We(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),c=(r=this.segments.get(o.id))!=null?r:[],l=(n=(s=(0,Gi.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(l)>=Math.floor(p.time.from)&&Math.floor(l)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(d+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,I.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let i of this.representations.values()){let r=i.segmentReference;if(!We(r))return;let s=(t=this.segments.get(i.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*r.timescale/1e3).toString(10),c=Pt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.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.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let g=p<=i&&h>=i,S=p>i||g||m===0&&i===0,x=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&p<=i+x||h<=i+x;return(d==="none"||d==="partially_ejected"&&S&&A&&this.sourceBuffer&&!(Ni(this.sourceBuffer.buffered,p)&&Ni(this.sourceBuffer.buffered,h)))&&S&&A});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let s=e,n=0,o=0,u=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let d=r;d<s.length&&(n<=c||o<=l);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){We(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,I.abortable)(o,async function*(){let l=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,I.now)(),!l)return;let d=new DataView(l);if(!isFinite(r.segment.time.to)){let p=t.segmentReference.timescale,h=Ui(t.mime);r.segment.time.to=h.getSegmentEndTime(d,p)}u&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),sa(l)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,I.abortable)(n,async function*(){let u=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),(0,I.fromEvent)(window,"online").pipe((0,I.once)()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,I.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),sa(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(We(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Gi.default)(e,0).byte.from,to:(0,Gi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,I.now)(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!We(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,l)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,I.now)();let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=Ui(n.mime).parseFeedableSegmentChunk(c,this.isLive);l!=null&&l.byteLength&&(u.status="partially_fed",o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,c=e.byteLength;for(let l of this.activeSegments){let{segment:d}=l,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:c;if(l.representationId!==t||!(!p||d.byte.from>=i&&d.byte.to<i+e.byteLength))continue;if(s.aborted){n();continue}let g=p?d.byte.from-i:0,S=p?d.byte.to-i:e.byteLength,x=g<r,A=S<=r;if(d.status==="downloading"&&x&&A){d.status="downloaded";let T=new DataView(e.buffer,e.byteOffset+g,h),P=this.getCurrentPosition();(0,I.isNonNullable)(P)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-P,this.bufferAccumulation.accumulated.push({segmentView:T,segmentProgress:l}),this.activeSegments.delete(l));let w=({segmentView:F,segmentProgress:G})=>this.sourceBufferTaskQueue.append(F,s).then(W=>W&&!s.aborted?this.onSegmentFullyAppended(G,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(w),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||(0,I.isNullable)(P))&&(w({segmentView:T,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&x&&!A&&(l.loadedBytes=Math.min(h,r-g),l.loadedBytes>l.feedingBytes)){let T=new DataView(e.buffer,e.byteOffset+g+l.feedingBytes,l.loadedBytes-l.feedingBytes),P=l.loadedBytes===h?T:Ui(o.mime).parseFeedableSegmentChunk(T);P!=null&&P.byteLength&&(d.status="partially_fed",l.feedingBytes+=P.byteLength,this.sourceBufferTaskQueue.append(P,s).then(w=>{if(s.aborted)n();else if(w)l.fedBytes+=P.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let l=c.byte.from-i,d=c.byte.to-i,p=d-l+1,h=l<r,m=d<=r;if(h){if(c.status==="downloading"&&m){c.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+l,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-l),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+l+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?g:Ui(o.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(c.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ns(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");(0,I.assertNonNullable)(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=uu(()=>(0,wb.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,I.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ui(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:c,segments:l}=o,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d);let p=l;this.isLive&&We(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),i&&this.error$.next({id:"LoadInits",category:I.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)}async pruneBufferNew(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,I.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=[],s=0,n=u=>{u.sort((l,d)=>l.from-d.from);let c=[u[0]];for(let l=1;l<u.length;l++){let{from:d,to:p}=u[l],h=c[c.length-1];h.to>=d?h.to=Math.max(h.to,p):c.push(u[l])}return c},o=u=>{var l;if(s>=t)return r;r.push({...u.time}),r=n(r);let c=Ns(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let l=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let p={time:{from:c,to:l},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>=e+u&&l.status==="fed"&&o(l)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1}async pruneBufferOld(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,I.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=0,s=1/0,n=-1/0,o=!1,u=c=>{var d;s=Math.min(s,c.time.from),n=Math.max(n,c.time.to);let l=Ns(c)?(d=c.size)!=null?d:0:c.byte.to-c.byte.from;r+=l};for(let c of this.segments.values())for(let l of c){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status==="fed"&&u(l)}if(o=isFinite(s)&&isFinite(n),!o){r=0,s=1/0,n=-1/0;for(let c of this.segments.values())for(let l of c){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status==="fed"&&u(l)}}if(o=isFinite(s)&&isFinite(n),!o)for(let c=0;c<this.sourceBuffer.buffered.length;c++){let l=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)){s=l,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&i){r=0,s=1/0,n=-1/0;let c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>e+c&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(0,I.isNullable)(e)?0:lt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.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<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){(0,I.assertNonNullable)(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=uu(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:I.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,I.isNullable)(this.sourceBuffer)||(0,I.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),c=e.filter(l=>n>=l.from&&n<l.to-t||o>l.from+t&&o<=l.to);u||(c.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var oa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var kb=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};var Q=require("@vkontakte/videoplayer-shared");var Fs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1}){this.lastConnectionType$=new Q.ValueSubject(void 0);this.lastConnectionReused$=new Q.ValueSubject(void 0);this.lastRequestFirstBytes$=new Q.ValueSubject(void 0);this.abortAllController=new et;this.subscription=new Q.Subscription;this.fetchManifest=(0,Q.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=oa(i));let r=yield It(i,{signal:this.abortAllController.signal}).catch(ua);return r?(t.log("success",(0,Q.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,Q.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,Q.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var J,D;let c=e,l=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let V=new URL(c,location.href);V.searchParams.append("bytes",`${i.from}-${i.to}`),c=V.toString();break}default:(0,Q.assertNever)(t)}this.requestQuic&&(c=oa(c));let p=this.abortAllController.signal,h;if(n){let V=new et;if(h=(0,Q.merge)((0,Q.fromEvent)(this.abortAllController.signal,"abort"),(0,Q.fromEvent)(n,"abort")).subscribe(()=>{try{V.abort()}catch(ee){ua(ee)}}),this.abortAllController.signal.aborted||n.aborted)try{V.abort()}catch(ee){ua(ee)}p=V.signal}let m=(0,Q.now)();d.log("startRequest",(0,Q.flattenObject)({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield It(c,{priority:s,headers:l,signal:p}).catch(ua),S=(0,Q.now)();if(!g)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((J=this.throughputEstimator)==null||J.addRawRtt(S-m),!g.ok||!g.body){h==null||h.unsubscribe();let V=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:V}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){h==null||h.unsubscribe();let V=(0,Q.now)(),ee={requestStartedAt:m,requestEndedAt:V,duration:V-m};return d.log("endRequest",(0,Q.flattenObject)(ee)),d.end(),g.arrayBuffer()}let[x,A]=g.body.tee(),T=x.getReader();o&&((D=this.throughputEstimator)==null||D.trackStream(A,u));let P=0,w=new Uint8Array(0),F=!1,G=V=>{h==null||h.unsubscribe(),F=!0,ua(V)},W=(0,Q.abortable)(p,async function*({done:V,value:ee}){if(P===0&&this.lastRequestFirstBytes$.next((0,Q.now)()-m),p.aborted){h==null||h.unsubscribe();return}if(!V&&ee){let le=new Uint8Array(w.length+ee.length);le.set(w),le.set(ee,w.length),w=le,P+=ee.byteLength,r==null||r(new DataView(w.buffer),P),yield T==null?void 0:T.read().then(W,G)}}.bind(this));yield T==null?void 0:T.read().then(W,G),h==null||h.unsubscribe();let Y=(0,Q.now)(),K={failed:F,requestStartedAt:m,requestEndedAt:Y,duration:Y-m};return F?(d.error("endRequest",(0,Q.flattenObject)(K)),d.end(),null):(d.log("endRequest",(0,Q.flattenObject)(K)),d.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,Q.abortable)(this.abortAllController.signal,async function*(e,t,i){var x;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,r),o=Math.max(l,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let p=new DataView(d,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(x=e.indexRange)!=null?x:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let A=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!A)return null;g=new DataView(A)}let S=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(d),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,Q.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:i}=kb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,Q.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ua=a=>{if(!sa(a))throw a};var si=(a,e,t)=>t*e+(1-t)*a,Eu=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Rb=(a,e,t,i)=>{let r=0,s=t,n=Eu(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};var la=require("@vkontakte/videoplayer-shared"),qt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new la.ValueSubject(e.initial),this.debounced$=new la.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ve(`raw_${t}`),this.smoothedSeries$=new ve(`smoothed_${t}`),this.reportedSeries$=new ve(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;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)&&((0,la.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var qs=class extends qt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=si(this.slow,e,this.params.emaAlphaSlow),this.fast=si(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Us=class extends qt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Eu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=si(this.emaSmoothed,e,this.params.emaAlpha);let i=Rb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Hs=class extends qt{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?si(this.smoothed,t,this.params.emaAlpha):t}};var ni=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new qs({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Us({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Hs({initial:e,label:"liveEdgeDelay",...t})}};var xu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var js=require("@vkontakte/videoplayer-shared");var ca=class a{constructor(e,t){this.currentRepresentation$=new js.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,js.isNullable)(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let c=s.segments.find(l=>l.time.from<=e&&l.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&We(t.segmentReference))}};var iA=["timeupdate","progress","play","seeked","stalled","waiting"],rA=["timeupdate","progress","loadeddata","playing","seeked"];var Gs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new v.Subscription;this.representationSubscription=new v.Subscription;this.state$=new H("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentAudioRepresentation$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.currentLiveTextRepresentation$=new v.ValueSubject(null);this.isLive$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.isActiveLowLatency$=new v.ValueSubject(!1);this.timeInWaiting=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new et;this.initManifest=(0,v.abortable)(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=fe(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Tb(e!=null?e:"",this.manifestUrlString)}catch(u){let c=(n=_m(e))!=null?n:{id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(c)}if(!t)return null;let i=(u,c,l)=>{var d,p,h,m;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,c)&&((m=(h=Et())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${c}; codecs="${l}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let l=t.streams[u].filter(({mime:h,codecs:m})=>i(u,h,m)),d=new Set(l.map(({codecs:h})=>h)),p=Vm(d);if(p&&(r[u]=l.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=r.video.some(S=>S.hdr),g=r.video.some(S=>!S.hdr);v.clientChecker.isHDR&&h&&m?r.video=r.video.filter(S=>S.hdr):g&&(r.video=r.video.filter(S=>!S.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",(0,v.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,async function*(e,t,i){var d;this.tracer.log("initRepresentationsStart",(0,v.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,v.fromEvent)(p,"error").pipe((0,v.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?ym():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Rs())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.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 na("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new na("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(ca.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new ca(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,v.interval)(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=Yo(this.manifestUrlString,2);this.manifestUrlString=fe(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add((0,v.merge)(...rA.map(p=>(0,v.fromEvent)(this.element,p))).pipe((0,v.map)(p=>this.element?lt(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.tap)(p=>{var h;p>this.tuning.dash.bufferEmptinessTolerance&&((h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,v.filterChanged)()).subscribe(h=>xu(this.element,1))),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,v.filter)(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add((0,v.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:m})=>{if(!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,A=h-g,T=1;Math.abs(A)>S&&(T=1+Math.sign(A)*x),xu(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let m=0;if(h){let x=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(T=>{var P,w;return(w=(P=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:P.to)!=null?w:x}))-x}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if((0,v.assertNonNullable)(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,S=Yo(this.manifestUrlString,2),x=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,A=Math.min(x,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,P=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,w=isFinite(h)?h:m,F=this.isActiveLowLatency$.getValue(),G=x<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLowLatency$.next(F&&G);let W="none";if(F?W="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&G?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(Y=>Y.proceedLowLatencyLive()),W="active_low_latency"):S!==0&&w<A?W="live_forward_buffering":w<A+P&&(W="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),W==="live_forward_buffering"||W==="live_with_target_offset"){let Y=p-(A+T),K=this.normolizeLiveOffset(Math.trunc(S+Y/g)),J=Math.abs(K-S),D;!h||J<=this.tuning.dashCmafLive.offsetCalculationError?D=S:K>0&&J>this.tuning.dashCmafLive.offsetCalculationError?D=K:D=0,this.manifestUrlString=fe(this.manifestUrlString,D,2)}W!=="none"&&W!=="active_low_latency"&&(p=0,this.updateLive())}))}let u=(0,v.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,v.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add((0,v.merge)(this.forceEnded$,(0,v.combine)({allBuffersFull:u,someBufferEnded:c}).pipe((0,v.filter)(({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:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,v.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let l=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),We(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/1e3,this.audioBufferManager&&(0,v.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(i=this.liveTextManager)==null||i.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Fs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=ni.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){var i,r,s;(0,v.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=fe(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((i=this.videoBufferManager)==null?void 0:i.seekLive(this.manifest.streams.video)),await((r=this.audioBufferManager)==null?void 0:r.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...iA.map(e=>(0,v.fromEvent)(this.element,e)),(0,v.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,v.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{var t,i,r;this.element&&this.element.readyState===2&&!this.element.seeking&&Ni(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var m,g,S,x,A,T,P,w,F,G;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting},n=(0,v.now)(),o=100,u=(g=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?g:0,c=(x=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?x:0,l=(T=(A=this.videoBufferManager)==null?void 0:A.getForwardBufferDuration())!=null?T:0,d=(w=(P=this.audioBufferManager)==null?void 0:P.getForwardBufferDuration())!=null?w:0,p=l<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&d<o&&n-c>this.tuning.dash.crashOnStallTWithoutDataTimeout;if(this.tuning.useNewProviderReinitLogic&&(p||h)&&this.timeInWaiting>this.tuning.dash.crashOnStallTWithoutDataTimeout||this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.timeInWaiting} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s={...s,liveLastSeekOffset:this.liveLastSeekOffset};else{let W=this.element.currentTime*1e3;(F=this.videoBufferManager)==null||F.maintain(W),(G=this.audioBufferManager)==null||G.maintain(W),s={...s,position:W}}this.tracer.log("stallIntervalCallback",(0,v.flattenObject)(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(i=this.audioBufferManager)==null||i.startAccumulateBuffer(),(r=this.stallWatchdogSubscription)==null||r.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:this.tuning.useNewProviderReinitLogic?v.ErrorCategory.NETWORK:v.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)}seek(e,t){var r,s,n,o,u,c;(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Ni(this.element.buffered,i)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(c=this.audioBufferManager)==null||c.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,v.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,v.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,r=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=i&&o.to+s>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r.push(1/0):r.push(o.to));if(r.length){let n=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:r,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,v.flattenObject)(t)))}}};var Ws=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ys=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i: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,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Lb=`attribute vec2 a_vertex;
|
|
65
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var vb=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?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),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Pt=(a,e)=>{let t=a;t=(0,vu.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,vu.default)(t,n,(o,u)=>(0,Wi.isNullable)(s)?o:(0,Wi.isNullable)(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Tb=(a,e)=>{var w,V,W,J,N,z,K,_,D,ee,le,E,H,te,se,ce,ye,pt,Rt,R,Te,$e,Ve,$t,ci,Lt,Ht,di,Ji,Cu,Du,Bu,Ou,Vu,_u,Nu,Fu,Uu,qu,Hu,ju,Gu,Wu,Yu,Qu,zu,Ku,Ju,Xu,Zu,el,tl,il,rl,al,sl,nl,ol,ul,ll;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(fe=>{var xa,Mt;return(Mt=(xa=fe.textContent)==null?void 0:xa.trim())!=null?Mt:""}),u=(w=(0,yb.default)(o,0))!=null?w:"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,p,m=s.getAttribute("mediaPresentationDuration"),g=n.getAttribute("duration"),S=s.getElementsByTagName("vk:Attrs")[0],x=S==null?void 0:S.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)p=vb(m);else if(g){let fe=vb(g);(0,Wi.isNonNullable)(fe)&&(p=fe)}else x&&(p=parseInt(x,10));let A=0,T=(W=(V=s.getAttribute("profiles"))==null?void 0:V.split(","))!=null?W:[];for(let fe of l){let xa=(J=fe.getAttribute("id"))!=null?J:"id"+(A++).toString(10),Mt=(N=fe.getAttribute("mimeType"))!=null?N:"",tn=(z=fe.getAttribute("codecs"))!=null?z:"",rn=(K=fe.getAttribute("contentType"))!=null?K:Mt==null?void 0:Mt.split("/")[0],Xb=(D=(_=fe.getAttribute("profiles"))==null?void 0:_.split(","))!=null?D:[],cl=(le=Sb((ee=fe.getAttribute("lang"))!=null?ee:""))!=null?le:{},Zb=(te=(H=(E=fe.querySelector("Label"))==null?void 0:E.textContent)==null?void 0:H.trim())!=null?te:void 0,eg=fe.querySelectorAll("Representation"),tg=fe.querySelector("SegmentTemplate"),ig=(ce=(se=fe.querySelector("Role"))==null?void 0:se.getAttribute("value"))!=null?ce:void 0,Xi=rn,de={id:xa,language:cl.language,isDefault:ig==="main",label:Zb,codecs:tn,hdr:Xi==="video"&&Su(tn),mime:Mt,representations:[]};for(let ie of eg){let rg=(ye=ie.getAttribute("lang"))!=null?ye:void 0,ag=(pt=ie.getAttribute("label"))!=null?pt:void 0,sg=(Te=(R=(Rt=ie.querySelector("BaseURL"))==null?void 0:Rt.textContent)==null?void 0:R.trim())!=null?Te:"",Pa=new URL(sg||u,e).toString(),pi=($e=ie.getAttribute("mimeType"))!=null?$e:Mt,Aa=($t=(Ve=ie.getAttribute("codecs"))!=null?Ve:tn)!=null?$t:"",wa;if(rn==="text"){let Ct=ie.getAttribute("id")||"",ka=((ci=cl.privateuse)==null?void 0:ci.includes("x-auto"))||Ct.includes("_auto"),jt=ie.querySelector("SegmentTemplate");if(jt){let Zi={representationId:(Lt=ie.getAttribute("id"))!=null?Lt:void 0,bandwidth:(Ht=ie.getAttribute("bandwidth"))!=null?Ht:void 0},Ra=parseInt((di=ie.getAttribute("bandwidth"))!=null?di:"",10)/1e3,$a=(Cu=parseInt((Ji=jt.getAttribute("startNumber"))!=null?Ji:"",10))!=null?Cu:1,hi=parseInt((Du=jt.getAttribute("timescale"))!=null?Du:"",10),an=(Bu=jt.querySelectorAll("SegmentTimeline S"))!=null?Bu:[],fi=jt.getAttribute("media");if(!fi)continue;let La=[],Ma=0,Ca="",mi=0,er=$a,be=0;for(let Qe of an){let Gt=parseInt((Ou=Qe.getAttribute("d"))!=null?Ou:"",10),_e=parseInt((Vu=Qe.getAttribute("r"))!=null?Vu:"",10)||0,Dt=parseInt((_u=Qe.getAttribute("t"))!=null?_u:"",10);be=Number.isFinite(Dt)?Dt:be;let Wt=Gt/hi*1e3,Bt=be/hi*1e3;for(let rt=0;rt<_e+1;rt++){let Ot=Pt(fi,{...Zi,segmentNumber:er.toString(10),segmentTime:(be+rt*Gt).toString(10)}),bi=(Bt!=null?Bt:0)+rt*Wt,ir=bi+Wt;er++,La.push({time:{from:bi,to:ir},url:Ot})}be+=(_e+1)*Gt,Ma+=(_e+1)*Wt}mi=be/hi*1e3,Ca=Pt(fi,{...Zi,segmentNumber:er.toString(10),segmentTime:be.toString(10)});let tr={time:{from:mi,to:1/0},url:Ca},ht={type:"template",baseUrl:Pa,segmentTemplateUrl:fi,initUrl:"",totalSegmentsDurationMs:Ma,segments:La,nextSegmentBeyondManifest:tr,timescale:hi};wa={id:Ct,kind:"text",segmentReference:ht,profiles:[],duration:p,bitrate:Ra,mime:"",codecs:"",width:0,height:0,isAuto:ka}}else wa={id:Ct,isAuto:ka,kind:"text",url:Pa}}else{let Ct=(Fu=(Nu=ie.getAttribute("contentType"))!=null?Nu:pi==null?void 0:pi.split("/")[0])!=null?Fu:rn,ka=(qu=(Uu=fe.getAttribute("profiles"))==null?void 0:Uu.split(","))!=null?qu:[],jt=parseInt((Hu=ie.getAttribute("width"))!=null?Hu:"",10),Zi=parseInt((ju=ie.getAttribute("height"))!=null?ju:"",10),Ra=parseInt((Gu=ie.getAttribute("bandwidth"))!=null?Gu:"",10)/1e3,$a=(Wu=ie.getAttribute("frameRate"))!=null?Wu:"",hi=(Yu=ie.getAttribute("quality"))!=null?Yu:void 0,an=$a?gb($a):void 0,fi=(Qu=ie.getAttribute("id"))!=null?Qu:"id"+(A++).toString(10),La=Ct==="video"?`${Zi}p`:Ct==="audio"?`${Ra}Kbps`:Aa,Ma=`${fi}@${La}`,Ca=[...T,...Xb,...ka],mi,er=ie.querySelector("SegmentBase"),be=(zu=ie.querySelector("SegmentTemplate"))!=null?zu:tg;if(er){let ht=(Ju=(Ku=ie.querySelector("SegmentBase Initialization"))==null?void 0:Ku.getAttribute("range"))!=null?Ju:"",[Qe,Gt]=ht.split("-").map(Ot=>parseInt(Ot,10)),_e={from:Qe,to:Gt},Dt=(Xu=ie.querySelector("SegmentBase"))==null?void 0:Xu.getAttribute("indexRange"),[Wt,Bt]=Dt?Dt.split("-").map(Ot=>parseInt(Ot,10)):[],rt=Dt?{from:Wt,to:Bt}:void 0;mi={type:"byteRange",url:Pa,initRange:_e,indexRange:rt}}else if(be){let ht={representationId:(Zu=ie.getAttribute("id"))!=null?Zu:void 0,bandwidth:(el=ie.getAttribute("bandwidth"))!=null?el:void 0},Qe=parseInt((tl=be.getAttribute("timescale"))!=null?tl:"",10),Gt=(il=be.getAttribute("initialization"))!=null?il:"",_e=be.getAttribute("media"),Dt=(al=parseInt((rl=be.getAttribute("startNumber"))!=null?rl:"",10))!=null?al:1,Wt=Pt(Gt,ht);if(!_e)throw new ReferenceError("No media attribute in SegmentTemplate");let Bt=(sl=be.querySelectorAll("SegmentTimeline S"))!=null?sl:[],rt=[],Ot=0,bi="",ir=0;if(Bt.length){let Da=Dt,ze=0;for(let gi of Bt){let at=parseInt((nl=gi.getAttribute("d"))!=null?nl:"",10),Yt=parseInt((ol=gi.getAttribute("r"))!=null?ol:"",10)||0,Ba=parseInt((ul=gi.getAttribute("t"))!=null?ul:"",10);ze=Number.isFinite(Ba)?Ba:ze;let sn=at/Qe*1e3,nn=ze/Qe*1e3;for(let Oa=0;Oa<Yt+1;Oa++){let og=Pt(_e,{...ht,segmentNumber:Da.toString(10),segmentTime:(ze+Oa*at).toString(10)}),dl=(nn!=null?nn:0)+Oa*sn,ug=dl+sn;Da++,rt.push({time:{from:dl,to:ug},url:og})}ze+=(Yt+1)*at,Ot+=(Yt+1)*sn}ir=ze/Qe*1e3,bi=Pt(_e,{...ht,segmentNumber:Da.toString(10),segmentTime:ze.toString(10)})}else if((0,Wi.isNonNullable)(p)){let ze=parseInt((ll=be.getAttribute("duration"))!=null?ll:"",10)/Qe*1e3,gi=Math.ceil(p/ze),at=0;for(let Yt=1;Yt<gi;Yt++){let Ba=Pt(_e,{...ht,segmentNumber:Yt.toString(10),segmentTime:at.toString(10)});rt.push({time:{from:at,to:at+ze},url:Ba}),at+=ze}ir=at,bi=Pt(_e,{...ht,segmentNumber:gi.toString(10),segmentTime:at.toString(10)})}let ng={time:{from:ir,to:1/0},url:bi};mi={type:"template",baseUrl:Pa,segmentTemplateUrl:_e,initUrl:Wt,totalSegmentsDurationMs:Ot,segments:rt,nextSegmentBeyondManifest:ng,timescale:Qe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ct||!pi)continue;let tr={video:"video",audio:"audio",text:"text"}[Ct];if(!tr)continue;Xi||(Xi=tr),wa={id:Ma,kind:tr,segmentReference:mi,profiles:Ca,duration:p,bitrate:Ra,mime:pi,codecs:Aa,width:jt,height:Zi,fps:an,quality:hi}}de.language||(de.language=rg),de.label||(de.label=ag),de.mime||(de.mime=pi),de.codecs||(de.codecs=Aa),de.hdr||(de.hdr=Xi==="video"&&Su(Aa)),de.representations.push(wa)}Xi&&r[Xi].push(de)}return{dynamic:c,liveAvailabilityStartTime:h,duration:p,streams:r,baseUrls:o}};var aa=Ne(Bi(),1);var Ib=require("@vkontakte/videoplayer-shared"),Eb=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s})=>{var o;let n=(o=s?Ft(s):void 0)!=null?o:(0,Ib.videoSizeToQuality)({width:e,height:t});return n&&{id:a,quality:n,bitrate:i,size:{width:e,height:t},fps:r}},xb=({id:a,bitrate:e})=>({id:a,bitrate:e}),Ns=(a,e,t)=>{var r;let i=e.indexOf(a);return(r=(0,aa.default)(t,Math.round(t.length*i/e.length)))!=null?r:(0,aa.default)(t,-1)},Pb=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Ab=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Iu=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,aa.default)(i.split("."),0),isDefault:r}),Eu=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,aa.default)(r.split("."),0)}),Fs=a=>"url"in a,Be=a=>a.type==="template",sa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var na=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new I.ValueSubject(0);this.onLastSegment$=new I.ValueSubject(!1);this.fullyBuffered$=new I.ValueSubject(!1);this.playingRepresentation$=new I.ValueSubject(void 0);this.playingRepresentationInit$=new I.ValueSubject(void 0);this.error$=new I.Subject;this.gaps=[];this.subscription=new I.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new et;this.switchAbortController=new et;this.destroyAbortController=new et;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,I.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Um(this.sourceBuffer),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.ErrorCategory.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,du(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=lt(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 i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,I.assertNonNullable)(i,"No init buffer for starting representation"),(0,I.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchToOld=(0,I.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,I.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,I.isNullable)(s)||(0,I.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,I.assertNonNullable)(r,"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();(0,I.isNonNullable)(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!Be(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,I.assertNonNullable)(r);let s=this.segments.get(i);(0,I.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,I.assertNonNullable)(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,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new et,(0,I.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,I.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,I.isNullable)(o)||(0,I.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,I.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,I.isNonNullable)(u)&&!this.isLive&&(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0,this.maintain(u)}}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new et,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if((0,I.isNullable)(e)||(0,I.isNullable)(this.downloadingRepresentationId)||(0,I.isNullable)(this.playingRepresentationId)||(0,I.isNullable)(this.sourceBuffer)||(0,I.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,I.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=r==null?void 0:r.time.to)!=null?l:0)-((c=r==null?void 0:r.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=lt(this.sourceBuffer.buffered,e),p=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=r.time.to-e+100&&(s=p)}if(isFinite(this.bufferLimit)&&du(this.sourceBuffer.buffered)>=this.bufferLimit){let d=lt(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{let h=(0,Yi.default)(o,0);h&&h.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&<(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Yi.default)(i,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;(0,I.isNonNullable)(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?i:[];for(let o of t){if(!o||!Be(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=(r=this.segments.get(o.id))!=null?r:[],c=(n=(s=(0,Yi.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(h=>Math.floor(c)>=Math.floor(h.time.from)&&Math.floor(c)<=Math.floor(h.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(d+1);this.segments.set(o.id,[...l,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,I.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let i of this.representations.values()){let r=i.segmentReference;if(!Be(r))return;let s=(t=this.segments.get(i.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*r.timescale/1e3).toString(10),l=Pt(r.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 i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.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.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:d,time:{from:h,to:p}},m)=>{let g=h<=i&&p>=i,S=h>i||g||m===0&&i===0,x=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&h<=i+x||p<=i+x;return(d==="none"||d==="partially_ejected"&&S&&A&&this.sourceBuffer&&!(Ui(this.sourceBuffer.buffered,h)&&Ui(this.sourceBuffer.buffered,p)))&&S&&A});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+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=r;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,i="auto"){Be(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,I.abortable)(o,async function*(){let c=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,I.now)(),!c)return;let d=new DataView(c);if(!isFinite(r.segment.time.to)){let h=t.segmentReference.timescale,p=ji(t.mime);r.segment.time.to=p.getSegmentEndTime(d,h)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),sa(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Be(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,I.abortable)(n,async function*(){let u=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,I.fromEvent)(window,"online").pipe((0,I.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,I.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),sa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Be(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Yi.default)(e,0).byte.from,to:(0,Yi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,I.now)(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Be(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,I.now)();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:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=ji(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,loaded:r,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,h=u==="byteRange",p=h?d.byte.to-d.byte.from+1:l;if(c.representationId!==t||!(!h||d.byte.from>=i&&d.byte.to<i+e.byteLength))continue;if(s.aborted){n();continue}let g=h?d.byte.from-i:0,S=h?d.byte.to-i:e.byteLength,x=g<r,A=S<=r;if(d.status==="downloading"&&x&&A){d.status="downloaded";let T=new DataView(e.buffer,e.byteOffset+g,p),P=this.getCurrentPosition();(0,I.isNonNullable)(P)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-P,this.bufferAccumulation.accumulated.push({segmentView:T,segmentProgress:c}),this.activeSegments.delete(c));let w=({segmentView:V,segmentProgress:W})=>this.sourceBufferTaskQueue.append(V,s).then(J=>J&&!s.aborted?this.onSegmentFullyAppended(W,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(w),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||(0,I.isNullable)(P))&&(w({segmentView:T,segmentProgress:c}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&x&&!A&&(c.loadedBytes=Math.min(p,r-g),c.loadedBytes>c.feedingBytes)){let T=new DataView(e.buffer,e.byteOffset+g+c.feedingBytes,c.loadedBytes-c.feedingBytes),P=c.loadedBytes===p?T:ji(o.mime).parseFeedableSegmentChunk(T);P!=null&&P.byteLength&&(d.status="partially_fed",c.feedingBytes+=P.byteLength,this.sourceBufferTaskQueue.append(P,s).then(w=>{if(s.aborted)n();else if(w)c.fedBytes+=P.byteLength,c.fedBytes===p&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<p)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let c=l.byte.from-i,d=l.byte.to-i,h=d-c+1,p=c<r,m=d<=r;if(p){if(l.status==="downloading"&&m){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,h);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===h?g:ji(o.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):n())}}}}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Fs(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");(0,I.assertNonNullable)(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=lu(()=>(0,wb.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,I.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ji(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&Be(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:I.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)}async pruneBufferNew(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,I.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=[],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:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Fs(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 h of this.segments.values())for(let p of h)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(r.length&&i){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 r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async pruneBufferOld(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,I.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=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=Fs(l)?(d=l.size)!=null?d:0:l.byte.to-l.byte.from;r+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){r=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)||r>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 h of this.segments.values())for(let p of h)if(p.status==="none"&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&i){r=0,s=1/0,n=-1/0;let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+l&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(0,I.isNullable)(e)?0:lt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.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<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){(0,I.assertNonNullable)(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=lu(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:I.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,I.isNullable)(this.sourceBuffer)||(0,I.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var oa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var kb=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};var Y=require("@vkontakte/videoplayer-shared");var Us=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1}){this.lastConnectionType$=new Y.ValueSubject(void 0);this.lastConnectionReused$=new Y.ValueSubject(void 0);this.lastRequestFirstBytes$=new Y.ValueSubject(void 0);this.abortAllController=new et;this.subscription=new Y.Subscription;this.fetchManifest=(0,Y.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=oa(i));let r=yield It(i,{signal:this.abortAllController.signal}).catch(ua);return r?(t.log("success",(0,Y.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,Y.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,Y.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var K,_;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let D=new URL(l,location.href);D.searchParams.append("bytes",`${i.from}-${i.to}`),l=D.toString();break}default:(0,Y.assertNever)(t)}this.requestQuic&&(l=oa(l));let h=this.abortAllController.signal,p;if(n){let D=new et;if(p=(0,Y.merge)((0,Y.fromEvent)(this.abortAllController.signal,"abort"),(0,Y.fromEvent)(n,"abort")).subscribe(()=>{try{D.abort()}catch(ee){ua(ee)}}),this.abortAllController.signal.aborted||n.aborted)try{D.abort()}catch(ee){ua(ee)}h=D.signal}let m=(0,Y.now)();d.log("startRequest",(0,Y.flattenObject)({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield It(l,{priority:s,headers:c,signal:h}).catch(ua),S=(0,Y.now)();if(!g)return d.error("error",{message:"No response in request"}),d.end(),p==null||p.unsubscribe(),null;if((K=this.throughputEstimator)==null||K.addRawRtt(S-m),!g.ok||!g.body){p==null||p.unsubscribe();let D=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:D}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){p==null||p.unsubscribe();let D=(0,Y.now)(),ee={requestStartedAt:m,requestEndedAt:D,duration:D-m};return d.log("endRequest",(0,Y.flattenObject)(ee)),d.end(),g.arrayBuffer()}let[x,A]=g.body.tee(),T=x.getReader();o&&((_=this.throughputEstimator)==null||_.trackStream(A,u));let P=0,w=new Uint8Array(0),V=!1,W=D=>{p==null||p.unsubscribe(),V=!0,ua(D)},J=(0,Y.abortable)(h,async function*({done:D,value:ee}){if(P===0&&this.lastRequestFirstBytes$.next((0,Y.now)()-m),h.aborted){p==null||p.unsubscribe();return}if(!D&&ee){let le=new Uint8Array(w.length+ee.length);le.set(w),le.set(ee,w.length),w=le,P+=ee.byteLength,r==null||r(new DataView(w.buffer),P),yield T==null?void 0:T.read().then(J,W)}}.bind(this));yield T==null?void 0:T.read().then(J,W),p==null||p.unsubscribe();let N=(0,Y.now)(),z={failed:V,requestStartedAt:m,requestEndedAt:N,duration:N-m};return V?(d.error("endRequest",(0,Y.flattenObject)(z)),d.end(),null):(d.log("endRequest",(0,Y.flattenObject)(z)),d.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,Y.abortable)(this.abortAllController.signal,async function*(e,t,i){var x;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,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,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let h=new DataView(d,r-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=(x=e.indexRange)!=null?x:t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let A=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!A)return null;g=new DataView(A)}let S=t.parseSegments(g,p,m);return{init:p,dataView:new DataView(d),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,Y.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:i}=kb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,Y.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ua=a=>{if(!sa(a))throw a};var ni=(a,e,t)=>t*e+(1-t)*a,xu=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Rb=(a,e,t,i)=>{let r=0,s=t,n=xu(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};var la=require("@vkontakte/videoplayer-shared"),qt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new la.ValueSubject(e.initial),this.debounced$=new la.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ve(`raw_${t}`),this.smoothedSeries$=new ve(`smoothed_${t}`),this.reportedSeries$=new ve(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;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)&&((0,la.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var qs=class extends qt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ni(this.slow,e,this.params.emaAlphaSlow),this.fast=ni(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Hs=class extends qt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=xu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ni(this.emaSmoothed,e,this.params.emaAlpha);let i=Rb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var js=class extends qt{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?ni(this.smoothed,t,this.params.emaAlpha):t}};var oi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new qs({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Hs({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new js({initial:e,label:"liveEdgeDelay",...t})}};var Pu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var Gs=require("@vkontakte/videoplayer-shared");var ca=class a{constructor(e,t){this.currentRepresentation$=new Gs.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,Gs.isNullable)(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Be(t.segmentReference))}};var tA=["timeupdate","progress","play","seeked","stalled","waiting"],iA=["timeupdate","progress","loadeddata","playing","seeked"];var Ws=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new v.Subscription;this.representationSubscription=new v.Subscription;this.state$=new j("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentAudioRepresentation$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.currentLiveTextRepresentation$=new v.ValueSubject(null);this.isLive$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.isActiveLowLatency$=new v.ValueSubject(!1);this.timeInWaiting=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new et;this.initManifest=(0,v.abortable)(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=me(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Tb(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Vm(e))!=null?n:{id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,h,p,m;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((m=(p=Et())==null?void 0:p.isTypeSupported)!=null&&m.call(p,`${l}; codecs="${c}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:m})=>i(u,p,m)),d=new Set(c.map(({codecs:p})=>p)),h=Om(d);if(h&&(r[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,m=r.video.some(S=>S.hdr),g=r.video.some(S=>!S.hdr);v.clientChecker.isHDR&&p&&m?r.video=r.video.filter(S=>S.hdr):g&&(r.video=r.video.filter(S=>!S.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",(0,v.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",(0,v.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,v.fromEvent)(p,"error").pipe((0,v.filter)(m=>{var g;return!!((g=this.element)!=null&&g.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?vm():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&$s())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.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,m)=>[...p,...m.representations],[]);if(this.videoBufferManager=new na("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((m,g)=>[...m,...g.representations],[]);this.audioBufferManager=new na("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}ca.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new ca(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,v.interval)(1e3).subscribe(p=>{var m;if((m=this.element)!=null&&m.paused){let g=Qo(this.manifestUrlString,2);this.manifestUrlString=me(this.manifestUrlString,g+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.timeInWaiting=0};if(this.representationSubscription.add((0,v.merge)(...iA.map(p=>(0,v.fromEvent)(this.element,p))).pipe((0,v.map)(p=>this.element?lt(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,v.merge)((0,v.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,v.filterChanged)()).subscribe(m=>Pu(this.element,1))),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,v.filter)(({bufferLength:m,isActiveLowLatency:g})=>g&&!!m)).subscribe(({bufferLength:m})=>this.liveEstimatedDelay.next(m))),this.representationSubscription.add((0,v.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:m,isActiveLowLatency:g})=>{if(!g)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,x=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,A=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=m-S,P=1;Math.abs(T)>x&&(P=1+Math.sign(T)*A),Pu(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var S,x;let g=0;if(m){let A=((x=(S=this.element)==null?void 0:S.currentTime)!=null?x:0)*1e3;g=Math.min(...this.bufferManagers.map(P=>{var w,V;return(V=(w=P.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?V:A}))-A}this.liveLoadBufferLength$.getValue()!==g&&this.liveLoadBufferLength$.next(g)}));let p=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:g})=>{if((0,v.assertNonNullable)(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,x=Qo(this.manifestUrlString,2),A=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(A,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),P=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,w=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,V=isFinite(m)?m:g,W=this.isActiveLowLatency$.getValue(),J=A<=this.tuning.live.activeLiveDelay&&x===0;this.isActiveLowLatency$.next(W&&J);let N="none";if(W?N="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&J?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(z=>z.proceedLowLatencyLive()),N="active_low_latency"):x!==0&&V<T?N="live_forward_buffering":V<T+w&&(N="live_with_target_offset"),isFinite(m)&&(p=m>p?m:p),N==="live_forward_buffering"||N==="live_with_target_offset"){let z=p-(T+P),K=this.normolizeLiveOffset(Math.trunc(x+z/S)),_=Math.abs(K-x),D;!m||_<=this.tuning.dashCmafLive.offsetCalculationError?D=x:K>0&&_>this.tuning.dashCmafLive.offsetCalculationError?D=K:D=0,this.manifestUrlString=me(this.manifestUrlString,D,2)}N!=="none"&&N!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=(0,v.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,v.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add((0,v.merge)(this.forceEnded$,(0,v.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,v.filter)(({allBuffersFull:p,someBufferEnded:m})=>p&&m))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(p=this.source)==null||p.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add((0,v.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var m;return(m=this.source)==null?void 0:m.addEventListener("sourceopen",p)}));let d=[(h=this.manifest.duration)!=null?h:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let m=[];return p.duration&&m.push(p.duration),Be(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&(0,v.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(i=this.liveTextManager)==null||i.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Us({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=oi.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){var i,r,s;(0,v.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=me(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((i=this.videoBufferManager)==null?void 0:i.seekLive(this.manifest.streams.video)),await((r=this.audioBufferManager)==null?void 0:r.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...tA.map(e=>(0,v.fromEvent)(this.element,e)),(0,v.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,v.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{var t,i,r;this.element&&this.element.readyState===2&&!this.element.seeking&&Ui(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var m,g,S,x,A,T,P,w,V,W;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting},n=(0,v.now)(),o=100,u=(g=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?g:0,l=(x=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?x:0,c=(T=(A=this.videoBufferManager)==null?void 0:A.getForwardBufferDuration())!=null?T:0,d=(w=(P=this.audioBufferManager)==null?void 0:P.getForwardBufferDuration())!=null?w:0,h=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if(this.tuning.useNewProviderReinitLogic&&(h||p)&&this.timeInWaiting>this.tuning.dash.crashOnStallTWithoutDataTimeout||this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.timeInWaiting} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s.liveLastSeekOffset=this.liveLastSeekOffset;else{let J=this.element.currentTime*1e3;(V=this.videoBufferManager)==null||V.maintain(J),(W=this.audioBufferManager)==null||W.maintain(J),s.position=J}this.tracer.log("stallIntervalCallback",(0,v.flattenObject)(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(i=this.audioBufferManager)==null||i.startAccumulateBuffer(),(r=this.stallWatchdogSubscription)==null||r.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:this.tuning.useNewProviderReinitLogic?v.ErrorCategory.NETWORK:v.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)}seek(e,t){var r,s,n,o,u,l;(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Ui(this.element.buffered,i)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(l=this.audioBufferManager)==null||l.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,v.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,v.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,r=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=i&&o.to+s>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r.push(1/0):r.push(o.to));if(r.length){let n=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:r,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,v.flattenObject)(t)))}}};var Ys=class{constructor(e,t){this.fov=e,this.orientation=t}};var Qs=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i: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,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Lb=`attribute vec2 a_vertex;
|
|
66
66
|
attribute vec2 a_texel;
|
|
67
67
|
|
|
68
68
|
varying vec2 v_texel;
|
|
@@ -116,5 +116,5 @@ void main(void) {
|
|
|
116
116
|
// sample using new coordinates
|
|
117
117
|
gl_FragColor = texture2D(u_texture, tc);
|
|
118
118
|
}
|
|
119
|
-
`;var Qs=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Ws(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ys(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"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),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(i,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(r,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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Lb,this.gl.VERTEX_SHADER),i=this.createShader(Mb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),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,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),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,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,c=e+i,l=t+r,d=e-i,p=t+r;return[s,n,o,u,c,l,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var oi=class{constructor(e){this.subscription=new N.Subscription;this.videoState=new H("stopped");this.elementSize$=new N.ValueSubject(void 0);this.textTracksManager=new Ue;this.droppedFramesManager=new Ps;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new $r;this.audioTrackSwitchHistory=new $r;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let c=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(r.position-c,r.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"),k(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"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&k(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()):(i==null?void 0:i.to)==="playing"&&k(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()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,N.assertNever)(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Qs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.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=Ee(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(pe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Gs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Ae(this.video),r=this.constructor.name,s=o=>{e.error$.next({id:r,category:N.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){var c;let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,N.filter)(l=>!!l.length),(0,N.once)()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})})),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.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.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((0,N.filter)(N.isNonNullable),(0,N.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,N.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),s((0,N.observeElementSize)(this.video),this.elementSize$),s(He(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,N.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of d.audio){h.push(Tu(m));let g=[];for(let S of m.representations){let x=xb(S);g.push(x),this.audioTracksMap.set(x,{stream:m,representation:S})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(Iu(h));let m=[];for(let g of h.representations){let S=Eb(g);S&&(m.push(S),this.videoTracksMap.set(S,{stream:h,representation:g}))}this.videoStreamsMap.set(h,m)}if(this.params.output.availableVideoStreams$.next(p),this.textTracksManager)for(let h of d.text)for(let m of h.representations){let g=Pb(h,m);this.textTracksMap.set(g,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=l=>e.error$.next({id:"RepresentationSwitch",category:N.ErrorCategory.WTF,message:"Switching representations threw",thrown:l});this.subscription.add((0,N.merge)(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$,(0,N.fromEvent)(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,m]=p,g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),l==="manifest_ready")this.player.initRepresentations(h.id,m==null?void 0:m.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(n),m){let S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,S).catch(n)}},r)),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((0,N.filterChanged)()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Iu(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,N.filterChanged)()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Tu(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,p;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),(c=this.textTracksManager)==null||c.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,N.map)(({to:l})=>l==="ready"),(0,N.filterChanged)());this.subscription.add((0,N.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add((0,N.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,N.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,N.observableFrom)(["init"])).pipe((0,N.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var F,G,W,Y,K,J,D,V,ee,le,E,U,te,se,ce,ye,pt,Rt;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(F=e.videoTrack.getState())==null?void 0:F.id,n=[...this.videoTracksMap.keys()].find(({id:R})=>R===r),o=t.currentVideoTrack$.getValue(),u=((Y=(W=e.videoStream.getState())!=null?W:n&&((G=this.videoTracksMap.get(n))==null?void 0:G.stream))!=null?Y:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let c=[...this.videoStreamsMap.keys()].find(({id:R})=>R===u.id),l=c&&this.videoStreamsMap.get(c);if(!l)return;let d=lt(this.video.buffered,this.video.currentTime*1e3),p=i?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),m=(K=e.audioStream.getState())!=null?K:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(J=[...this.audioStreamsMap.keys()].find(({id:R})=>R===(m==null?void 0:m.id)))!=null?J:this.audioStreamsMap.keys().next().value,S=0;if(g){if(n&&!i)if(this.params.tuning.useSeparateAudioVideoABR){let R=Es(n,l,(D=this.audioStreamsMap.get(g))!=null?D:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,(V=R==null?void 0:R.bitrate)!=null?V:-1/0)}else{let R=_s(n,l,(ee=this.audioStreamsMap.get(g))!=null?ee:[]);S=Math.max(S,(le=R==null?void 0:R.bitrate)!=null?le:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let R=Es(o,l,(E=this.audioStreamsMap.get(g))!=null?E:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,(U=R==null?void 0:R.bitrate)!=null?U:-1/0)}else{let R=_s(o,l,(te=this.audioStreamsMap.get(g))!=null?te:[]);S=Math.max(S,(se=R==null?void 0:R.bitrate)!=null?se:-1/0)}}let x=Ft(l,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),A=i?x!=null?x:n:n!=null?n:x,T;this.params.tuning.useSeparateAudioVideoABR?T=g&&pm(A,l,(ce=this.audioStreamsMap.get(g))!=null?ce:[],{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}):T=g&&_s(A,l,(ye=this.audioStreamsMap.get(g))!=null?ye:[]);let P=(pt=this.videoTracksMap.get(A))==null?void 0:pt.representation,w=T&&((Rt=this.audioTracksMap.get(T))==null?void 0:Rt.representation);if(P&&w)return[P,w];if(P&&!w&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:N.ErrorCategory.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),xe(this.video),this.tracer.end()}};var pa=class extends oi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var ui=require("@vkontakte/videoplayer-shared");var ha=class extends oi{constructor(e){super(e),this.liveOffset=new vt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,ui.combine)({interval:(0,ui.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(r-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add((0,ui.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ui.map)(({liveBufferTime:r,liveAvailabilityStartTime:s})=>r&&s?r+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(r=>{if(r){let s=Ab(r);this.params.output.availableTextTracks$.next([s])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="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,r)})}};var Cb=ze(ys(),1);var j=require("@vkontakte/videoplayer-shared"),it={};var Wi=(a,e)=>new j.Observable(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),fa=class{constructor(e){this.subscription=new j.Subscription;this.videoState=new H("initializing");this.textTracksManager=new Ue;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,j.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,j.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,j.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,j.assertNever)(e)}break;default:(0,j.assertNever)(t)}};this.video=Ee(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(pe(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),xe(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:j.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Cb.default)(import("hls.js").then(r=>{e||(it.Hls=r.default,it.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){(0,j.assertNonNullable)(it.Hls,"hls.js not loaded"),this.hls=new it.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,j.assertNonNullable)(it.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=c=>{t.error$.next({id:"HlsJsProvider",category:j.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:c})},r=Ae(this.video),s=(c,l)=>this.subscription.add(c.subscribe(l,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,i)),this.subscription.add(Pe(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.video,e.playbackRate,r.playbackRateState$,i)),s(He(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,j.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(Wi(this.hls,it.Events.ERROR).subscribe(c=>{var l;c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:j.ErrorCategory.WTF,message:`HlsJs fatal ${c.type} ${c.details}, ${(l=c.err)==null?void 0:l.message} ${c.reason}`,thrown:c.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var c;((c=this.videoState.getTransition())==null?void 0:c.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(Wi(this.hls,it.Events.MANIFEST_PARSED).pipe((0,j.map)(({levels:c})=>c.reduce((l,d)=>{var A,T;let p=d.name||d.height.toString(10),{width:h,height:m}=d,g=(T=Nt((A=d.attrs.QUALITY)!=null?A:""))!=null?T:(0,j.videoSizeToQuality)({width:h,height:m});if(!g)return l;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,x={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:S};return this.trackLevels.set(p,{track:x,level:d}),l.push(x),l},[]))),t.availableVideoTracks$),s(Wi(this.hls,it.Events.MANIFEST_PARSED),c=>{if(c.subtitleTracks.length>0){let l=[];for(let d of c.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;l.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(l)}}),s(Wi(this.hls,it.Events.LEVEL_LOADING).pipe((0,j.map)(({url:c})=>pe(c))),t.hostname$),s(Wi(this.hls,it.Events.FRAG_CHANGED),c=>{var p,h,m,g;let{video:l,audio:d}=c.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=l==null?void 0:l.endPTS)!=null?p:0)-((h=l==null?void 0:l.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(_t(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,c=>{this.hls.nextLevel=c?-1:this.hls.currentLevel,this.hls.loadLevel=c?-1:this.hls.loadLevel},{onError:i}));let n=c=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:d})=>d===c))==null?void 0:l.track},o=Wi(this.hls,it.Events.LEVEL_SWITCHED).pipe((0,j.map)(({level:c})=>n(this.hls.levels[c])));o.pipe((0,j.filter)(j.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(_t(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),c=>{var m;if((0,j.isNullable)(c))return;let l=(m=this.trackLevels.get(c.id))==null?void 0:m.level;if(!l)return;let d=this.hls.levels.indexOf(l),p=this.hls.currentLevel,h=this.hls.levels[p];!h||l.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,j.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,j.observableFrom)(["init"])).pipe((0,j.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:j.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),k(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"),k(this.params.desiredState.playbackState,"stopped",!0)}};var Db="X-Playback-Duration",Pu=async a=>{var r;let e=await It(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Db)?parseInt(e.headers.get(Db),10):void 0};var q=require("@vkontakte/videoplayer-shared");var wu=ze(no(),1);var zs=require("@vkontakte/videoplayer-shared");var uA=a=>{let e=null;if(a.QUALITY&&(e=Nt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,zs.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},lA=(a,e)=>{var s,n;let t=a.split(`
|
|
120
|
-
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],c=u.match(/^#EXT-X-STREAM-INF:(.+)/),l=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!l)){if(c){let d=(0,wu.default)(c[1].split(",").map(A=>A.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=uA(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[A,T]=d.RESOLUTION.split("x").map(P=>parseInt(P,10));A&&T&&(S={width:A,height:T})}let x=new URL(t[++o],e).toString();h&&i.push({id:p,quality:h,url:x,bandwidth:m,size:S,fps:g})}if(l){let d=(0,wu.default)(l[1].split(",").map(g=>g.split("=")).map(([g,S])=>[g,S.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&r.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},cA=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Au=0,Bb=async(a,e=a,t)=>{let r=await(await It(a)).text();Au+=1;try{let{qualityManifests:s,textTracks:n}=lA(r,e);return{qualityManifests:s,textTracks:n}}catch(s){if(Au<=t.manifestRetryMaxCount)return await cA((0,zs.getExponentialDelay)(Au-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Bb(a,e,t)}return{qualityManifests:[],textTracks:[]}},Ks=Bb;var ma=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new H("stopped");this.textTracksManager=new Ue;this.manifests$=new q.ValueSubject([]);this.liveOffset=new vt;this.manifestStartTime$=new q.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,q.assertNever)(t)}};var t;this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:q.VideoQuality.INVARIANT,url:this.params.source.url},Ks(fe(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:i})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:q.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:q.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),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(pe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new q.ValueSubject((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,c,l,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(c=t.getState())==null?void 0:c.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:q.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ae(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,r.playbackRateState$,i)),s(He(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe((0,q.filterChanged)(),(0,q.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,q.isNonNullable)(c.to)){let d=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(pe(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,c,l;let o=(l=(c=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:c.call(u))==null?void 0:l.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,q.combine)({startTime:this.manifestStartTime$.pipe((0,q.filter)(q.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,q.map)(o=>o.map(({id:u,quality:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,q.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var o,u;let e=this.selectManifest();if((0,q.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:l}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[d,p]of[[c,"mq"],[l,"lq"]]){let h=String(parseFloat(d||""));p&&d&&r.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=fe(r.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Pu(n).then(c=>{var l;if(!(0,q.isNullable)(c))this.maxSeekBackTime$.next(c);else{let d=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();if((0,q.isNullable)(d)||!isFinite(d))try{It(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let g=new URL(h,n).toString();Pu(g).then(S=>{(0,q.isNullable)(S)||this.maxSeekBackTime$.next(S)})}})}catch(p){}}})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:q.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}};var z=require("@vkontakte/videoplayer-shared");var ba=class{constructor(e){this.subscription=new z.Subscription;this.videoState=new H("stopped");this.textTracksManager=new Ue;this.manifests$=new z.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,z.assertNever)(t)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:z.VideoQuality.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(pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ks(fe(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:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:z.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,c,l,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(c=t.getState())==null?void 0:c.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:z.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ae(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,z.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,z.isNonNullable)(c.to)){let p=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let h=this.manifests$.getValue().find(m=>m.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(pe(h.url));let m=this.params.desiredState.playbackRate.getState(),g=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(m!==g){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(m),S.playbackRate=m)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe((0,z.map)(o=>o.map(({id:u,quality:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!z.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,z.merge)((0,z.fromEvent)(o,"addtrack"),(0,z.fromEvent)(o,"removetrack"),(0,z.fromEvent)(o,"change"),(0,z.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,z.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,z.observableFrom)(["init"])).pipe((0,z.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,z.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[c,l]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(c||""));l&&c&&r.searchParams.set(l,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:z.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Z=require("@vkontakte/videoplayer-shared");var ga=class{constructor(e){this.subscription=new Z.Subscription;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new Ue;this.syncPlayback=()=>{var u,c,l;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((l=(c=this.trackUrls[n.to.id])==null?void 0:c.track)==null?void 0:l.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(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()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,Z.assertNever)(e)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),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,i=o=>{e.error$.next({id:"MpegProvider",category:Z.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ae(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,Z.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,r.playbackRateState$,i)),s(He(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,c;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,Z.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),d=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(l!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(l),p.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=(0,Z.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Z.observableFrom)(["init"])).pipe((0,Z.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),xe(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,Z.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,Z.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=oa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(pe(t))}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Z.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var r,s,n,o;let t,i=e;if(e&&((r=this.params.output.currentVideoTrack$.getValue())==null?void 0:r.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!(0,Z.isInvariantQuality)(d.track.quality)&&(0,Z.isLowerOrEqual)(d.track.quality,e)))==null?void 0:s.track,c=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,l=(o=this.trackUrls[c!=null?c:"0"])==null?void 0:o.track;if(u&&l&&(0,Z.isHigherOrEqual)(l.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!(0,Z.isInvariantQuality)(h.track.quality)&&(0,Z.isHigher)(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(i=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(c=>c.track);t=Ft(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:i})}};var re=require("@vkontakte/videoplayer-shared");var Vb=require("@vkontakte/videoplayer-shared"),Ob=["stun:videostun.mycdn.me:80"],dA=1e3,pA=3,ku=()=>null,Js=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=ku;this.externalStopCallback=ku;this.externalErrorCallback=ku;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Ob}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:Vb.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))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),dA)}normalizeOptions(e={}){let t={stunServerList:Ob,maxRetryNumber:pA,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Sa=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new re.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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"),k(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"),k(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()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,re.assertNever)(e)}};this.subscription=new re.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ee(e.container,e.tuning),this.liveStreamClient=new Js(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),xe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:re.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,re.merge)(this.videoState.stateChangeStarted$.pipe((0,re.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,re.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let r=Ae(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),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(He(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Pe(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).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(0,re.assertNever)(n.to)}},i)).add((0,re.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}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(pe(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:re.VideoQuality.INVARIANT}),this.video.srcObject=e,k(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:re.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var va=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}};var y=require("@vkontakte/videoplayer-shared");var At=require("@vkontakte/videoplayer-shared"),_b=a=>new At.Observable(e=>{let t=new At.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,At.map)(({from:c,to:l})=>`${c}-${l}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,At.map)(({type:c})=>c!==void 0)),n=new At.Subject,o=0,u="unknown";return t.add(i.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(c=>{o&&(window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Be=require("@vkontakte/videoplayer-shared");var ya=null,Xs=null;function Ru(){return ya||(ya=new(window.AudioContext||window.webkitAudioContext)),Xs||(Xs=new GainNode(ya,{gain:1}),Xs.connect(ya.destination)),{audioCtx:ya,gainNode:Xs}}var Nb=require("@vkontakte/videoplayer-shared");var Yi=class Yi{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.audioContextInit=!1;this.subscriptions=new Be.Subscription;this.lastAudioContextResumeId=0;this.subscriptions.add(this.provider$.pipe((0,Be.filter)(s=>!!s.type),(0,Be.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){Nb.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Be.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Be.filter)(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,Be.once)()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:r}=Ru(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,i.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Yi.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r),this.audioContextInit=!0}catch(o){this.volumeMultiplierError$.next({id:Yi.errorId,category:Be.ErrorCategory.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:Yi.errorId,category:Be.ErrorCategory.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){if(this.audioContextInit){let{gainNode:e}=Ru();e.gain.value=1}this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Yi.errorId="VolumeMultiplierManager";var Qi=Yi;var hA={chunkDuration:5e3,maxParallelRequests:5},Ta=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,soundProhibitedEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,loadedMetadataEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject("")};this.subscription=new y.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Dm([...Om(this.params.tuning),...Bm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(c=>(0,y.isNonNullable)(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(c=>!r.includes(c)),...t.filter(c=>r.includes(c))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new va(s);let n=[...ou(!0),...ou(!1)];this.chromecastFormatsIterator=new va(n.filter(c=>(0,y.isNonNullable)(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Qi.isSupported()&&(this.volumeMultiplierManager=new Qi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,y.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,y.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,s=this.providerOutput,n={container:i,source:null,desiredState:r,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(0,y.assertNonNullable)(o),new pa({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new ha({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),Vi||!this.params.tuning.useHlsJs?new ba({...n,source:o}):new fa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new ma({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new ga({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new gm({...n,source:o,config:{...hA,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Sa({container:i,source:o,desiredState:r,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(0,y.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,y.assertNonNullable)(o),new wr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,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(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.assertNever)(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(0,y.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,Fb.default)(Object.entries(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,i=0;return e.add((0,y.merge)(this.providerOutput.error$,_b({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(r=>({id:`ProviderHangup:${r}`,category:y.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,y.filter)(({to:s})=>s==="playing"),(0,y.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===y.ErrorCategory.NETWORK,u=r.category===y.ErrorCategory.FATAL,c=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<this.params.tuning.providerErrorLimit&&!u,d=c&&!u&&(o&&t||!l);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:c,tryFailover:d,canReinitProvider:l},this.params.tuning.useNewProviderReinitLogic?l?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN"):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(i++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var O=require("@vkontakte/videoplayer-shared");var fA=5e3,qb="one_video_throughput",Ub="one_video_rtt",wt=window.navigator.connection,Hb=()=>{let a=wt==null?void 0:wt.downlink;if((0,O.isNonNullable)(a)&&a!==10)return a*1e3},jb=()=>{let a=wt==null?void 0:wt.rtt;if((0,O.isNonNullable)(a)&&a!==3e3)return a},Gb=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},$u=class a{constructor(e){this.subscription=new O.Subscription;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(qb)||(e.useBrowserEstimation?Hb():void 0)||fA,i=(s=(r=a.load(Ub))!=null?r:e.useBrowserEstimation?jb():void 0)!=null?s:0;if(this.throughput$=new O.ValueSubject(t),this.rtt$=new O.ValueSubject(i),this.rttAdjustedThroughput$=new O.ValueSubject(Gb(t,i,e.rttPenaltyRequestSize)),this.throughput=ni.getSmoothedValue(t,-1,e),this.rtt=ni.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=Hb();u&&this.throughput.next(u);let c=jb();(0,O.isNonNullable)(c)&&this.rtt.next(c)};wt&&"onchange"in wt&&this.subscription.add((0,O.fromEvent)(wt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{O.safeStorage.set(qb,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{O.safeStorage.set(Ub,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,O.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,O.map)(({throughput:n,rtt:o})=>Gb(n,o,e.rttPenaltyRequestSize)),(0,O.filter)(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,i=(0,O.now)(),r=new O.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,O.fromEvent)(e,"progress").pipe((0,O.once)()).subscribe(s=>{t=s.loaded,i=(0,O.now)()}));break;case 1:case 0:r.add((0,O.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,O.now)()}));break}r.add((0,O.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,O.now)(),u=n-t,c=o-i;this.addRawSpeed(u,c,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=(0,O.now)(),n=0,o=(0,O.now)(),u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},c=async({done:l,value:d})=>{if(l)!t&&this.addRawSpeed(r,(0,O.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=(0,O.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=(0,O.now)()}else n+=d.byteLength;o=(0,O.now)()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,O.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,O.now)()-o,this.concurrentDownloads.size),n=0,o=(0,O.now)());await(i==null?void 0:i.read().then(c,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(c,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=O.safeStorage.get(e);if((0,O.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},Wb=$u;var Ia=require("@vkontakte/videoplayer-shared"),Yb={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:10,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:1,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Ia.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ia.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useNewSwitchTo:!1,useSeparateAudioVideoABR:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,useNewProviderReinitLogic:!1,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},Qb=a=>{var e;return{...(0,Ia.fillWithDefault)(a,Yb),configName:[...(e=a.configName)!=null?e:[],...Yb.configName]}};var f=require("@vkontakte/videoplayer-shared");var kt=require("@vkontakte/videoplayer-shared"),Lu=({seekState:a,position$:e})=>(0,kt.merge)(a.stateChangeEnded$.pipe((0,kt.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,kt.filter)(kt.isNonNullable)),e.pipe((0,kt.filter)(()=>a.getState().state==="none")));var zb=require("@vkontakte/videoplayer-shared"),Kb=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,zb.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var Zs=require("@vkontakte/videoplayer-shared"),Jb=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,Zs.filter)(r=>r.length>0),(0,Zs.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var Ea=class{constructor(e={configName:[]},t=f.Tracer.createRootTracer(!1)){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new H("stopped"),seekState:new H({state:"none"}),volume:new H({volume:1,muted:!1}),videoTrack:new H(void 0),videoStream:new H(void 0),audioStream:new H(void 0),autoVideoTrackSwitching:new H(!0),autoVideoTrackLimits:new H({}),isLooped:new H(!1),playbackRate:new H(1),externalTextTracks:new H([]),internalTextTracks:new H([]),currentTextTrack:new H(void 0),textTrackCuesSettings:new H({}),cameraOrientation:new H({x:0,y:0})};this.info={playbackState$:new f.ValueSubject("stopped"),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:om};if(this.initLogs(),this.tuning=Qb(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Na({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Wb(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let c=o.map(p=>JSON.stringify(p,(h,m)=>{let g=typeof m;return["number","string","boolean"].includes(g)?m:m===null?null:`<${g}>`})),l=`Player.${String(r)}`,d=`Exception calling ${l} (${c.join(", ")})`;throw this.events.fatalError$.next({id:l,category:f.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var r,s,n;this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",(0,f.flattenObject)(i)),this.domContainer=Kb(e),this.chromecastInitializer.contentId=(r=e.meta)==null?void 0:r.videoId,this.providerContainer=new Ta({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Dr()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;return e>=i&&!r&&(s=i-.1),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var i;(0,f.assertNonNullable)(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",(0,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return Jb(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.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((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe((0,f.map)(n=>n.map(({quality:o})=>o).sort((o,u)=>(0,f.isInvariantQuality)(o)?1:(0,f.isInvariantQuality)(u)?-1:(0,f.isHigher)(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,f.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).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((0,f.map)(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((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(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((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Lu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let c=this.getActiveLiveDelay(u);return n&&Math.abs(o)<c/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(Lu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).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((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.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((0,f.once)(),(0,f.map)(n=>n!=null?n:(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-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 f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>i.next(!1)));let r=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,f.filterChanged)());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,c;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(c=n==null?void 0:n.size)==null?void 0:c.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,f.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),c=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),d;l==="CONNECTED"?d="second_screen":u?c?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(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 f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t,i=(r=this.desiredState.videoTrack.getState())==null?void 0:r.quality;i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=Ft(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((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(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;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),nm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>sm(i)),this.providerContainer.current$.subscribe(({type:i})=>Rr("provider",i)),e.duration$.subscribe(i=>Rr("duration",i)),e.availableVideoTracks$.pipe((0,f.filter)(i=>!!i.length),(0,f.once)()).subscribe(i=>Rr("tracks",i)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe((0,f.map)(i=>i==null?void 0:i.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(i=>this.subscription.add(i)),Rr("codecs",Cm())}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,f.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,f.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(i=>i.end>0),(0,f.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(r)})})};this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var dt=require("@vkontakte/videoplayer-shared"),mA=`@vkontakte/videoplayer-core@${nn}`;
|
|
119
|
+
`;var zs=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Ys(this.params.fov,this.params.orientation),this.cameraRotationManager=new Qs(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"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),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(i,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(r,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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Lb,this.gl.VERTEX_SHADER),i=this.createShader(Mb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),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,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),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,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,h=t+r;return[s,n,o,u,l,c,d,h]}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 ui=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new j("stopped");this.elementSize$=new U.ValueSubject(void 0);this.textTracksManager=new je;this.droppedFramesManager=new As;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new $r;this.audioTrackSwitchHistory=new $r;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(r.position-l,r.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"),k(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"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&k(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()):(i==null?void 0:i.to)==="playing"&&k(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()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,U.assertNever)(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new zs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.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=Ee(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(pe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Ws({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Ae(this.video),r=this.constructor.name,s=o=>{e.error$.next({id:r,category:U.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){var l;let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,U.filter)(c=>!!c.length),(0,U.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})})),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.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.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((0,U.filter)(U.isNonNullable),(0,U.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,U.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(He(this.video,t.playbackRate,i.playbackRateState$,r)),s((0,U.observeElementSize)(this.video),this.elementSize$),s(Ge(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,U.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let m of d.audio){p.push(Iu(m));let g=[];for(let S of m.representations){let x=xb(S);g.push(x),this.audioTracksMap.set(x,{stream:m,representation:S})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(p)}let h=[];for(let p of d.video){h.push(Eu(p));let m=[];for(let g of p.representations){let S=Eb(g);S&&(m.push(S),this.videoTracksMap.set(S,{stream:p,representation:g}))}this.videoStreamsMap.set(p,m)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let p of d.text)for(let m of p.representations){let g=Pb(p,m);this.textTracksMap.set(g,{stream:p,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=c=>e.error$.next({id:"RepresentationSwitch",category:U.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,U.merge)(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$,(0,U.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[p,m]=h,g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(p.id,m==null?void 0:m.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),m){let S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,S).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,U.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:p}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===p.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Eu(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,U.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:p}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===p.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Iu(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,h;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),(l=this.textTracksManager)==null||l.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,U.map)(({to:c})=>c==="ready"),(0,U.filterChanged)());this.subscription.add((0,U.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,U.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,U.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var V,W,J,N,z,K,_,D,ee,le,E,H,te,se,ce,ye,pt,Rt;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(V=e.videoTrack.getState())==null?void 0:V.id,n=[...this.videoTracksMap.keys()].find(({id:R})=>R===r),o=t.currentVideoTrack$.getValue(),u=((N=(J=e.videoStream.getState())!=null?J:n&&((W=this.videoTracksMap.get(n))==null?void 0:W.stream))!=null?N:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:R})=>R===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=lt(this.video.buffered,this.video.currentTime*1e3),h=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=(z=e.audioStream.getState())!=null?z:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(K=[...this.audioStreamsMap.keys()].find(({id:R})=>R===(m==null?void 0:m.id)))!=null?K:this.audioStreamsMap.keys().next().value,S=0;if(g){if(n&&!i)if(this.params.tuning.useSeparateAudioVideoABR){let R=xs(n,c,(_=this.audioStreamsMap.get(g))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,(D=R==null?void 0:R.bitrate)!=null?D:-1/0)}else{let R=Ns(n,c,(ee=this.audioStreamsMap.get(g))!=null?ee:[]);S=Math.max(S,(le=R==null?void 0:R.bitrate)!=null?le:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let R=xs(o,c,(E=this.audioStreamsMap.get(g))!=null?E:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,(H=R==null?void 0:R.bitrate)!=null?H:-1/0)}else{let R=Ns(o,c,(te=this.audioStreamsMap.get(g))!=null?te:[]);S=Math.max(S,(se=R==null?void 0:R.bitrate)!=null?se:-1/0)}}let x=Ut(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:p,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),A=i?x!=null?x:n:n!=null?n:x,T;this.params.tuning.useSeparateAudioVideoABR?T=g&&dm(A,c,(ce=this.audioStreamsMap.get(g))!=null?ce:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:p,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):T=g&&Ns(A,c,(ye=this.audioStreamsMap.get(g))!=null?ye:[]);let P=(pt=this.videoTracksMap.get(A))==null?void 0:pt.representation,w=T&&((Rt=this.audioTracksMap.get(T))==null?void 0:Rt.representation);if(P&&w)return[P,w];if(P&&!w&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:U.ErrorCategory.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),xe(this.video),this.tracer.end()}};var pa=class extends ui{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var li=require("@vkontakte/videoplayer-shared");var ha=class extends ui{constructor(e){super(e),this.liveOffset=new vt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,li.combine)({interval:(0,li.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(r-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add((0,li.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,li.map)(({liveBufferTime:r,liveAvailabilityStartTime:s})=>r&&s?r+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(r=>{if(r){let s=Ab(r);this.params.output.availableTextTracks$.next([s])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="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,r)})}};var Cb=Ne(Ts(),1);var G=require("@vkontakte/videoplayer-shared"),it={};var Qi=(a,e)=>new G.Observable(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),fa=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new j("initializing");this.textTracksManager=new je;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,G.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,G.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,G.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,G.assertNever)(e)}break;default:(0,G.assertNever)(t)}};this.video=Ee(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(pe(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),xe(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:G.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Cb.default)(import("hls.js").then(r=>{e||(it.Hls=r.default,it.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){(0,G.assertNonNullable)(it.Hls,"hls.js not loaded"),this.hls=new it.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,G.assertNonNullable)(it.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:G.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=Ae(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,i)),this.subscription.add(Pe(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(He(this.video,e.playbackRate,r.playbackRateState$,i)),s(Ge(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,G.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Qi(this.hls,it.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:G.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(Qi(this.hls,it.Events.MANIFEST_PARSED).pipe((0,G.map)(({levels:l})=>l.reduce((c,d)=>{var A,T;let h=d.name||d.height.toString(10),{width:p,height:m}=d,g=(T=Ft((A=d.attrs.QUALITY)!=null?A:""))!=null?T:(0,G.videoSizeToQuality)({width:p,height:m});if(!g)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,x={id:h.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:S};return this.trackLevels.set(h,{track:x,level:d}),c.push(x),c},[]))),t.availableVideoTracks$),s(Qi(this.hls,it.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang;c.push({id:h,url:p,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Qi(this.hls,it.Events.LEVEL_LOADING).pipe((0,G.map)(({url:l})=>pe(l))),t.hostname$),s(Qi(this.hls,it.Events.FRAG_CHANGED),l=>{var h,p,m,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(Nt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=Qi(this.hls,it.Events.LEVEL_SWITCHED).pipe((0,G.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,G.filter)(G.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Nt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if((0,G.isNullable)(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,G.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),k(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"),k(this.params.desiredState.playbackState,"stopped",!0)}};var Db="X-Playback-Duration",Au=async a=>{var r;let e=await It(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Db)?parseInt(e.headers.get(Db),10):void 0};var q=require("@vkontakte/videoplayer-shared");var ku=Ne(oo(),1);var Ks=require("@vkontakte/videoplayer-shared");var oA=a=>{let e=null;if(a.QUALITY&&(e=Ft(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,Ks.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},uA=(a,e)=>{var s,n;let t=a.split(`
|
|
120
|
+
`),i=[],r=[];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(A=>A.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=oA(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[A,T]=d.RESOLUTION.split("x").map(P=>parseInt(P,10));A&&T&&(S={width:A,height:T})}let x=new URL(t[++o],e).toString();p&&i.push({id:h,quality:p,url:x,bandwidth:m,size:S,fps:g})}if(c){let d=(0,ku.default)(c[1].split(",").map(g=>g.split("=")).map(([g,S])=>[g,S.replace(/^"|"$/g,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,m=d.NAME;h&&p&&r.push({type:"internal",id:p,label:m,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},lA=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),wu=0,Bb=async(a,e=a,t)=>{let r=await(await It(a)).text();wu+=1;try{let{qualityManifests:s,textTracks:n}=uA(r,e);return{qualityManifests:s,textTracks:n}}catch(s){if(wu<=t.manifestRetryMaxCount)return await lA((0,Ks.getExponentialDelay)(wu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Bb(a,e,t)}return{qualityManifests:[],textTracks:[]}},Js=Bb;var ma=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new j("stopped");this.textTracksManager=new je;this.manifests$=new q.ValueSubject([]);this.liveOffset=new vt;this.manifestStartTime$=new q.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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"),k(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((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="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(r==null?void 0:r.to)==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,q.assertNever)(t)}};var t;this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:q.VideoQuality.INVARIANT,url:this.params.source.url},Js(me(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:i})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:q.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:q.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),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(pe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new q.ValueSubject((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.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=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:q.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ae(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(He(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ge(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe((0,q.filterChanged)(),(0,q.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.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&&(0,q.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(pe(h.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)},i)),this.subscription.add(r.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)},i)),this.subscription.add((0,q.combine)({startTime:this.manifestStartTime$.pipe((0,q.filter)(q.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,q.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,q.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var o,u;let e=this.selectManifest();if((0,q.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[d,h]of[[l,"mq"],[c,"lq"]]){let p=String(parseFloat(d||""));h&&d&&r.searchParams.set(h,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=me(r.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Au(n).then(l=>{var c;if(!(0,q.isNullable)(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if((0,q.isNullable)(d)||!isFinite(d))try{It(n).then(h=>h.text()).then(h=>{var m;let p=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:m[1];if(p){let g=new URL(p,n).toString();Au(g).then(S=>{(0,q.isNullable)(S)||this.maxSeekBackTime$.next(S)})}})}catch(h){}}})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:q.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}};var Q=require("@vkontakte/videoplayer-shared");var ba=class{constructor(e){this.subscription=new Q.Subscription;this.videoState=new j("stopped");this.textTracksManager=new je;this.manifests$=new Q.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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"),k(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((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,Q.assertNever)(t)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Q.VideoQuality.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(pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Js(me(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:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Q.ErrorCategory.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,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.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=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Q.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ae(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,Q.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(He(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.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&&(0,Q.isNonNullable)(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(m=>m.id===h);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(pe(p.url));let m=this.params.desiredState.playbackRate.getState(),g=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(m!==g){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(m),S.playbackRate=m)}}}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)},i))),this.subscription.add(this.manifests$.pipe((0,Q.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!Q.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,Q.merge)((0,Q.fromEvent)(o,"addtrack"),(0,Q.fromEvent)(o,"removetrack"),(0,Q.fromEvent)(o,"change"),(0,Q.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,Q.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,Q.observableFrom)(["init"])).pipe((0,Q.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,Q.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Q.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Z=require("@vkontakte/videoplayer-shared");var ga=class{constructor(e){this.subscription=new Z.Subscription;this.videoState=new j("stopped");this.trackUrls={};this.textTracksManager=new je;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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"),k(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((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(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()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,Z.assertNever)(e)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),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,i=o=>{e.error$.next({id:"MpegProvider",category:Z.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ae(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,Z.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(He(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ge(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.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&&(0,Z.isNonNullable)(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 h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=(0,Z.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Z.observableFrom)(["init"])).pipe((0,Z.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),xe(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,Z.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,Z.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=oa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(pe(t))}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Z.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var r,s,n,o;let t,i=e;if(e&&((r=this.params.output.currentVideoTrack$.getValue())==null?void 0:r.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!(0,Z.isInvariantQuality)(d.track.quality)&&(0,Z.isLowerOrEqual)(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&&(0,Z.isHigherOrEqual)(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(p=>!(0,Z.isInvariantQuality)(p.track.quality)&&(0,Z.isHigher)(p.track.quality,e)),h=d.length;h&&(t=d[h-1].track)}t&&(i=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=Ut(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:i})}};var re=require("@vkontakte/videoplayer-shared");var Vb=require("@vkontakte/videoplayer-shared"),Ob=["stun:videostun.mycdn.me:80"],cA=1e3,dA=3,Ru=()=>null,Xs=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=Ru;this.externalStopCallback=Ru;this.externalErrorCallback=Ru;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Ob}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:Vb.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))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),cA)}normalizeOptions(e={}){let t={stunServerList:Ob,maxRetryNumber:dA,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Sa=class{constructor(e){this.videoState=new j("stopped");this.maxSeekBackTime$=new re.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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"),k(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"),k(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()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,re.assertNever)(e)}};this.subscription=new re.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ee(e.container,e.tuning),this.liveStreamClient=new Xs(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),xe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:re.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,re.merge)(this.videoState.stateChangeStarted$.pipe((0,re.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,re.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let r=Ae(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),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(Ge(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Pe(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).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(0,re.assertNever)(n.to)}},i)).add((0,re.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}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(pe(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:re.VideoQuality.INVARIANT}),this.video.srcObject=e,k(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:re.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var va=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}};var y=require("@vkontakte/videoplayer-shared");var At=require("@vkontakte/videoplayer-shared"),_b=a=>new At.Observable(e=>{let t=new At.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,At.map)(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,At.map)(({type:l})=>l!==void 0)),n=new At.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.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()}});var Oe=require("@vkontakte/videoplayer-shared");var ya=null,Zs=null;function $u(){return ya||(ya=new(window.AudioContext||window.webkitAudioContext)),Zs||(Zs=new GainNode(ya,{gain:1}),Zs.connect(ya.destination)),{audioCtx:ya,gainNode:Zs}}var Nb=require("@vkontakte/videoplayer-shared");var zi=class zi{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.audioContextInit=!1;this.subscriptions=new Oe.Subscription;this.lastAudioContextResumeId=0;this.subscriptions.add(this.provider$.pipe((0,Oe.filter)(s=>!!s.type),(0,Oe.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){Nb.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Oe.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Oe.filter)(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,Oe.once)()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:r}=$u(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,i.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${zi.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r),this.audioContextInit=!0}catch(o){this.volumeMultiplierError$.next({id:zi.errorId,category:Oe.ErrorCategory.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:zi.errorId,category:Oe.ErrorCategory.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){if(this.audioContextInit){let{gainNode:e}=$u();e.gain.value=1}this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};zi.errorId="VolumeMultiplierManager";var Ki=zi;var pA={chunkDuration:5e3,maxParallelRequests:5},Ta=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,soundProhibitedEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,loadedMetadataEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject("")};this.subscription=new y.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Cm([...Bm(this.params.tuning),...Dm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(l=>(0,y.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new va(s);let n=[...uu(!0),...uu(!1)];this.chromecastFormatsIterator=new va(n.filter(l=>(0,y.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Ki.isSupported()&&(this.volumeMultiplierManager=new Ki(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,y.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,y.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,s=this.providerOutput,n={container:i,source:null,desiredState:r,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(0,y.assertNonNullable)(o),new pa({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new ha({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),Ni||!this.params.tuning.useHlsJs?new ba({...n,source:o}):new fa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new ma({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new ga({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new bm({...n,source:o,config:{...pA,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Sa({container:i,source:o,desiredState:r,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(0,y.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,y.assertNonNullable)(o),new kr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,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(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.assertNever)(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(0,y.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,Fb.default)(Object.entries(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,i=0;return e.add((0,y.merge)(this.providerOutput.error$.pipe((0,y.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),_b({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(r=>({id:`ProviderHangup:${r}`,category:y.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,y.filter)(({to:s})=>s==="playing"),(0,y.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===y.ErrorCategory.NETWORK,u=r.category===y.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},this.params.tuning.useNewProviderReinitLogic?c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN"):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(i++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var O=require("@vkontakte/videoplayer-shared");var hA=5e3,Ub="one_video_throughput",qb="one_video_rtt",wt=window.navigator.connection,Hb=()=>{let a=wt==null?void 0:wt.downlink;if((0,O.isNonNullable)(a)&&a!==10)return a*1e3},jb=()=>{let a=wt==null?void 0:wt.rtt;if((0,O.isNonNullable)(a)&&a!==3e3)return a},Gb=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Lu=class a{constructor(e){this.subscription=new O.Subscription;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(Ub)||(e.useBrowserEstimation?Hb():void 0)||hA,i=(s=(r=a.load(qb))!=null?r:e.useBrowserEstimation?jb():void 0)!=null?s:0;if(this.throughput$=new O.ValueSubject(t),this.rtt$=new O.ValueSubject(i),this.rttAdjustedThroughput$=new O.ValueSubject(Gb(t,i,e.rttPenaltyRequestSize)),this.throughput=oi.getSmoothedValue(t,-1,e),this.rtt=oi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=Hb();u&&this.throughput.next(u);let l=jb();(0,O.isNonNullable)(l)&&this.rtt.next(l)};wt&&"onchange"in wt&&this.subscription.add((0,O.fromEvent)(wt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{O.safeStorage.set(Ub,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{O.safeStorage.set(qb,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,O.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,O.map)(({throughput:n,rtt:o})=>Gb(n,o,e.rttPenaltyRequestSize)),(0,O.filter)(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,i=(0,O.now)(),r=new O.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,O.fromEvent)(e,"progress").pipe((0,O.once)()).subscribe(s=>{t=s.loaded,i=(0,O.now)()}));break;case 1:case 0:r.add((0,O.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,O.now)()}));break}r.add((0,O.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,O.now)(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=(0,O.now)(),n=0,o=(0,O.now)(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,(0,O.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=(0,O.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=(0,O.now)()}else n+=d.byteLength;o=(0,O.now)()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,O.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,O.now)()-o,this.concurrentDownloads.size),n=0,o=(0,O.now)());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=O.safeStorage.get(e);if((0,O.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},Wb=Lu;var Ia=require("@vkontakte/videoplayer-shared"),Yb={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:10,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:1,limitByContainer:!0,containerSizeFactor:1.5,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Ia.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ia.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!0,useNewPartialSegmentFeeding:!0,useNewSwitchTo:!1,useSeparateAudioVideoABR:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,useNewProviderReinitLogic:!0,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,ignoreAudioRendererError:!1},Qb=a=>{var e;return{...(0,Ia.fillWithDefault)(a,Yb),configName:[...(e=a.configName)!=null?e:[],...Yb.configName]}};var f=require("@vkontakte/videoplayer-shared");var kt=require("@vkontakte/videoplayer-shared"),Mu=({seekState:a,position$:e})=>(0,kt.merge)(a.stateChangeEnded$.pipe((0,kt.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,kt.filter)(kt.isNonNullable)),e.pipe((0,kt.filter)(()=>a.getState().state==="none")));var zb=require("@vkontakte/videoplayer-shared"),Kb=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,zb.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var en=require("@vkontakte/videoplayer-shared"),Jb=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,en.filter)(r=>r.length>0),(0,en.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var Ea=class{constructor(e={configName:[]},t=f.Tracer.createRootTracer(!1)){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new j("stopped"),seekState:new j({state:"none"}),volume:new j({volume:1,muted:!1}),videoTrack:new j(void 0),videoStream:new j(void 0),audioStream:new j(void 0),autoVideoTrackSwitching:new j(!0),autoVideoTrackLimits:new j({}),isLooped:new j(!1),playbackRate:new j(1),externalTextTracks:new j([]),internalTextTracks:new j([]),currentTextTrack:new j(void 0),textTrackCuesSettings:new j({}),cameraOrientation:new j({x:0,y:0})};this.info={playbackState$:new f.ValueSubject("stopped"),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:nm};if(this.initLogs(),this.tuning=Qb(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Fa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Wb(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,m)=>{let g=typeof m;return["number","string","boolean"].includes(g)?m:m===null?null:`<${g}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:f.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var r,s,n;this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",(0,f.flattenObject)(i)),this.domContainer=Kb(e),this.chromecastInitializer.contentId=(r=e.meta)==null?void 0:r.videoId,this.providerContainer=new Ta({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Dr()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;return e>=i&&!r&&(s=i-.1),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var i;(0,f.assertNonNullable)(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",(0,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return Jb(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.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((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe((0,f.map)(n=>n.map(({quality:o})=>o).sort((o,u)=>(0,f.isInvariantQuality)(o)?1:(0,f.isInvariantQuality)(u)?-1:(0,f.isHigher)(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,f.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).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((0,f.map)(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((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(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((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Mu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(Mu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).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((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.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((0,f.once)(),(0,f.map)(n=>n!=null?n:(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-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 f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>i.next(!1)));let r=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,f.filterChanged)());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(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((0,f.merge)(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((0,f.map)(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 f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t,i=(r=this.desiredState.videoTrack.getState())==null?void 0:r.quality;i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=Ut(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((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(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;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),sm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>am(i)),this.providerContainer.current$.subscribe(({type:i})=>Rr("provider",i)),e.duration$.subscribe(i=>Rr("duration",i)),e.availableVideoTracks$.pipe((0,f.filter)(i=>!!i.length),(0,f.once)()).subscribe(i=>Rr("tracks",i)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe((0,f.map)(i=>i==null?void 0:i.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(i=>this.subscription.add(i)),Rr("codecs",Mm())}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,f.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,f.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(i=>i.end>0),(0,f.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(r)})})};this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var dt=require("@vkontakte/videoplayer-shared"),fA=`@vkontakte/videoplayer-core@${on}`;
|