@vkontakte/videoplayer-core 2.0.111-dev.2c18acf4.0 → 2.0.111-dev.974e99b3.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 CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.111-dev.2c18acf4.0
3
- * Mon, 16 Sep 2024 09:48:10 GMT
2
+ * @vkontakte/videoplayer-core v2.0.111-dev.974e99b3.0
3
+ * Thu, 19 Sep 2024 08:04:36 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-111/doc/
5
5
  */
6
- "use strict";var ig=Object.create;var Qr=Object.defineProperty,ag=Object.defineProperties,sg=Object.getOwnPropertyDescriptor,ng=Object.getOwnPropertyDescriptors,og=Object.getOwnPropertyNames,Ia=Object.getOwnPropertySymbols,ug=Object.getPrototypeOf,Js=Object.prototype.hasOwnProperty,Ku=Object.prototype.propertyIsEnumerable;var cg=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var it=Math.pow,zu=(a,e,t)=>e in a?Qr(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,C=(a,e)=>{for(var t in e||(e={}))Js.call(e,t)&&zu(a,t,e[t]);if(Ia)for(var t of Ia(e))Ku.call(e,t)&&zu(a,t,e[t]);return a},z=(a,e)=>ag(a,ng(e));var Ju=(a,e)=>{var t={};for(var r in a)Js.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&Ia)for(var r of Ia(a))e.indexOf(r)<0&&Ku.call(a,r)&&(t[r]=a[r]);return t};var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),lg=(a,e)=>{for(var t in e)Qr(a,t,{get:e[t],enumerable:!0})},Xu=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of og(e))!Js.call(a,i)&&i!==t&&Qr(a,i,{get:()=>e[i],enumerable:!(r=sg(e,i))||r.enumerable});return a};var ze=(a,e,t)=>(t=a!=null?ig(ug(a)):{},Xu(e||!a||!a.__esModule?Qr(t,"default",{value:a,enumerable:!0}):t,a)),dg=a=>Xu(Qr({},"__esModule",{value:!0}),a);var O=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(c){i(c)}},n=u=>{try{o(t.throw(u))}catch(c){i(c)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),Xs=function(a,e){this[0]=a,this[1]=e},me=(a,e,t)=>{var r=(n,o,u,c)=>{try{var l=t[n](o),d=(o=l.value)instanceof Xs,p=l.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,c):u({value:h,done:p})).catch(h=>r("throw",h,u,c))}catch(h){c(h)}},i=n=>s[n]=o=>new Promise((u,c)=>r(n,o,u,c)),s={};return t=t.apply(a,e),s[cg("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var De=b((IA,ec)=>{"use strict";ec.exports=function(a){try{return!!a()}catch(e){return!0}}});var Kr=b((EA,tc)=>{"use strict";var hg=De();tc.exports=!hg(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Pe=b((xA,ac)=>{"use strict";var rc=Kr(),ic=Function.prototype,en=ic.call,fg=rc&&ic.bind.bind(en,en);ac.exports=rc?fg:function(a){return function(){return en.apply(a,arguments)}}});var pr=b((PA,nc)=>{"use strict";var sc=Pe(),mg=sc({}.toString),bg=sc("".slice);nc.exports=function(a){return bg(mg(a),8,-1)}});var uc=b((AA,oc)=>{"use strict";var gg=Pe(),Sg=De(),vg=pr(),tn=Object,yg=gg("".split);oc.exports=Sg(function(){return!tn("z").propertyIsEnumerable(0)})?function(a){return vg(a)==="String"?yg(a,""):tn(a)}:tn});var hr=b((wA,cc)=>{"use strict";cc.exports=function(a){return a==null}});var Jr=b((kA,lc)=>{"use strict";var Tg=hr(),Ig=TypeError;lc.exports=function(a){if(Tg(a))throw new Ig("Can't call method on "+a);return a}});var fr=b((RA,dc)=>{"use strict";var Eg=uc(),xg=Jr();dc.exports=function(a){return Eg(xg(a))}});var rn=b(($A,pc)=>{"use strict";pc.exports=function(){}});var jt=b((LA,hc)=>{"use strict";hc.exports={}});var le=b((an,fc)=>{"use strict";var Xr=function(a){return a&&a.Math===Math&&a};fc.exports=Xr(typeof globalThis=="object"&&globalThis)||Xr(typeof window=="object"&&window)||Xr(typeof self=="object"&&self)||Xr(typeof global=="object"&&global)||Xr(typeof an=="object"&&an)||function(){return this}()||Function("return this")()});var ce=b((MA,mc)=>{"use strict";var sn=typeof document=="object"&&document.all;mc.exports=typeof sn=="undefined"&&sn!==void 0?function(a){return typeof a=="function"||a===sn}:function(a){return typeof a=="function"}});var Sc=b((CA,gc)=>{"use strict";var Pg=le(),Ag=ce(),bc=Pg.WeakMap;gc.exports=Ag(bc)&&/native code/.test(String(bc))});var Fe=b((DA,vc)=>{"use strict";var wg=ce();vc.exports=function(a){return typeof a=="object"?a!==null:wg(a)}});var qe=b((BA,yc)=>{"use strict";var kg=De();yc.exports=!kg(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Aa=b((OA,Ic)=>{"use strict";var Rg=le(),Tc=Fe(),nn=Rg.document,$g=Tc(nn)&&Tc(nn.createElement);Ic.exports=function(a){return $g?nn.createElement(a):{}}});var on=b((VA,Ec)=>{"use strict";var Lg=qe(),Mg=De(),Cg=Aa();Ec.exports=!Lg&&!Mg(function(){return Object.defineProperty(Cg("div"),"a",{get:function(){return 7}}).a!==7})});var un=b((_A,xc)=>{"use strict";var Dg=qe(),Bg=De();xc.exports=Dg&&Bg(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var at=b((NA,Pc)=>{"use strict";var Og=Fe(),Vg=String,_g=TypeError;Pc.exports=function(a){if(Og(a))return a;throw new _g(Vg(a)+" is not an object")}});var Be=b((FA,Ac)=>{"use strict";var Ng=Kr(),wa=Function.prototype.call;Ac.exports=Ng?wa.bind(wa):function(){return wa.apply(wa,arguments)}});var ka=b((qA,wc)=>{"use strict";wc.exports={}});var dt=b((UA,Rc)=>{"use strict";var cn=ka(),ln=le(),Fg=ce(),kc=function(a){return Fg(a)?a:void 0};Rc.exports=function(a,e){return arguments.length<2?kc(cn[a])||kc(ln[a]):cn[a]&&cn[a][e]||ln[a]&&ln[a][e]}});var Zr=b((HA,$c)=>{"use strict";var qg=Pe();$c.exports=qg({}.isPrototypeOf)});var mr=b((jA,Cc)=>{"use strict";var Ug=le(),Lc=Ug.navigator,Mc=Lc&&Lc.userAgent;Cc.exports=Mc?String(Mc):""});var pn=b((GA,Nc)=>{"use strict";var _c=le(),dn=mr(),Dc=_c.process,Bc=_c.Deno,Oc=Dc&&Dc.versions||Bc&&Bc.version,Vc=Oc&&Oc.v8,Ke,Ra;Vc&&(Ke=Vc.split("."),Ra=Ke[0]>0&&Ke[0]<4?1:+(Ke[0]+Ke[1]));!Ra&&dn&&(Ke=dn.match(/Edge\/(\d+)/),(!Ke||Ke[1]>=74)&&(Ke=dn.match(/Chrome\/(\d+)/),Ke&&(Ra=+Ke[1])));Nc.exports=Ra});var hn=b((WA,qc)=>{"use strict";var Fc=pn(),Hg=De(),jg=le(),Gg=jg.String;qc.exports=!!Object.getOwnPropertySymbols&&!Hg(function(){var a=Symbol("symbol detection");return!Gg(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Fc&&Fc<41})});var fn=b((YA,Uc)=>{"use strict";var Wg=hn();Uc.exports=Wg&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var mn=b((QA,Hc)=>{"use strict";var Yg=dt(),Qg=ce(),zg=Zr(),Kg=fn(),Jg=Object;Hc.exports=Kg?function(a){return typeof a=="symbol"}:function(a){var e=Yg("Symbol");return Qg(e)&&zg(e.prototype,Jg(a))}});var ei=b((zA,jc)=>{"use strict";var Xg=String;jc.exports=function(a){try{return Xg(a)}catch(e){return"Object"}}});var pt=b((KA,Gc)=>{"use strict";var Zg=ce(),eS=ei(),tS=TypeError;Gc.exports=function(a){if(Zg(a))return a;throw new tS(eS(a)+" is not a function")}});var ti=b((JA,Wc)=>{"use strict";var rS=pt(),iS=hr();Wc.exports=function(a,e){var t=a[e];return iS(t)?void 0:rS(t)}});var Qc=b((XA,Yc)=>{"use strict";var bn=Be(),gn=ce(),Sn=Fe(),aS=TypeError;Yc.exports=function(a,e){var t,r;if(e==="string"&&gn(t=a.toString)&&!Sn(r=bn(t,a))||gn(t=a.valueOf)&&!Sn(r=bn(t,a))||e!=="string"&&gn(t=a.toString)&&!Sn(r=bn(t,a)))return r;throw new aS("Can't convert object to primitive value")}});var Je=b((ZA,zc)=>{"use strict";zc.exports=!0});var Xc=b((ew,Jc)=>{"use strict";var Kc=le(),sS=Object.defineProperty;Jc.exports=function(a,e){try{sS(Kc,a,{value:e,configurable:!0,writable:!0})}catch(t){Kc[a]=e}return e}});var ri=b((tw,tl)=>{"use strict";var nS=Je(),oS=le(),uS=Xc(),Zc="__core-js_shared__",el=tl.exports=oS[Zc]||uS(Zc,{});(el.versions||(el.versions=[])).push({version:"3.38.0",mode:nS?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var vn=b((rw,il)=>{"use strict";var rl=ri();il.exports=function(a,e){return rl[a]||(rl[a]=e||{})}});var ii=b((iw,al)=>{"use strict";var cS=Jr(),lS=Object;al.exports=function(a){return lS(cS(a))}});var Xe=b((aw,sl)=>{"use strict";var dS=Pe(),pS=ii(),hS=dS({}.hasOwnProperty);sl.exports=Object.hasOwn||function(e,t){return hS(pS(e),t)}});var yn=b((sw,nl)=>{"use strict";var fS=Pe(),mS=0,bS=Math.random(),gS=fS(1 .toString);nl.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+gS(++mS+bS,36)}});var ye=b((nw,ul)=>{"use strict";var SS=le(),vS=vn(),ol=Xe(),yS=yn(),TS=hn(),IS=fn(),br=SS.Symbol,Tn=vS("wks"),ES=IS?br.for||br:br&&br.withoutSetter||yS;ul.exports=function(a){return ol(Tn,a)||(Tn[a]=TS&&ol(br,a)?br[a]:ES("Symbol."+a)),Tn[a]}});var pl=b((ow,dl)=>{"use strict";var xS=Be(),cl=Fe(),ll=mn(),PS=ti(),AS=Qc(),wS=ye(),kS=TypeError,RS=wS("toPrimitive");dl.exports=function(a,e){if(!cl(a)||ll(a))return a;var t=PS(a,RS),r;if(t){if(e===void 0&&(e="default"),r=xS(t,a,e),!cl(r)||ll(r))return r;throw new kS("Can't convert object to primitive value")}return e===void 0&&(e="number"),AS(a,e)}});var In=b((uw,hl)=>{"use strict";var $S=pl(),LS=mn();hl.exports=function(a){var e=$S(a,"string");return LS(e)?e:e+""}});var Gt=b(ml=>{"use strict";var MS=qe(),CS=on(),DS=un(),$a=at(),fl=In(),BS=TypeError,En=Object.defineProperty,OS=Object.getOwnPropertyDescriptor,xn="enumerable",Pn="configurable",An="writable";ml.f=MS?DS?function(e,t,r){if($a(e),t=fl(t),$a(r),typeof e=="function"&&t==="prototype"&&"value"in r&&An in r&&!r[An]){var i=OS(e,t);i&&i[An]&&(e[t]=r.value,r={configurable:Pn in r?r[Pn]:i[Pn],enumerable:xn in r?r[xn]:i[xn],writable:!1})}return En(e,t,r)}:En:function(e,t,r){if($a(e),t=fl(t),$a(r),CS)try{return En(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new BS("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var ai=b((lw,bl)=>{"use strict";bl.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var gr=b((dw,gl)=>{"use strict";var VS=qe(),_S=Gt(),NS=ai();gl.exports=VS?function(a,e,t){return _S.f(a,e,NS(1,t))}:function(a,e,t){return a[e]=t,a}});var La=b((pw,vl)=>{"use strict";var FS=vn(),qS=yn(),Sl=FS("keys");vl.exports=function(a){return Sl[a]||(Sl[a]=qS(a))}});var Ma=b((hw,yl)=>{"use strict";yl.exports={}});var $n=b((fw,El)=>{"use strict";var US=Sc(),Il=le(),HS=Fe(),jS=gr(),wn=Xe(),kn=ri(),GS=La(),WS=Ma(),Tl="Object already initialized",Rn=Il.TypeError,YS=Il.WeakMap,Ca,si,Da,QS=function(a){return Da(a)?si(a):Ca(a,{})},zS=function(a){return function(e){var t;if(!HS(e)||(t=si(e)).type!==a)throw new Rn("Incompatible receiver, "+a+" required");return t}};US||kn.state?(Ze=kn.state||(kn.state=new YS),Ze.get=Ze.get,Ze.has=Ze.has,Ze.set=Ze.set,Ca=function(a,e){if(Ze.has(a))throw new Rn(Tl);return e.facade=a,Ze.set(a,e),e},si=function(a){return Ze.get(a)||{}},Da=function(a){return Ze.has(a)}):(Wt=GS("state"),WS[Wt]=!0,Ca=function(a,e){if(wn(a,Wt))throw new Rn(Tl);return e.facade=a,jS(a,Wt,e),e},si=function(a){return wn(a,Wt)?a[Wt]:{}},Da=function(a){return wn(a,Wt)});var Ze,Wt;El.exports={set:Ca,get:si,has:Da,enforce:QS,getterFor:zS}});var Ln=b((mw,wl)=>{"use strict";var KS=Kr(),Al=Function.prototype,xl=Al.apply,Pl=Al.call;wl.exports=typeof Reflect=="object"&&Reflect.apply||(KS?Pl.bind(xl):function(){return Pl.apply(xl,arguments)})});var Mn=b((bw,kl)=>{"use strict";var JS=pr(),XS=Pe();kl.exports=function(a){if(JS(a)==="Function")return XS(a)}});var Ml=b(Ll=>{"use strict";var Rl={}.propertyIsEnumerable,$l=Object.getOwnPropertyDescriptor,ZS=$l&&!Rl.call({1:2},1);Ll.f=ZS?function(e){var t=$l(this,e);return!!t&&t.enumerable}:Rl});var Bl=b(Dl=>{"use strict";var ev=qe(),tv=Be(),rv=Ml(),iv=ai(),av=fr(),sv=In(),nv=Xe(),ov=on(),Cl=Object.getOwnPropertyDescriptor;Dl.f=ev?Cl:function(e,t){if(e=av(e),t=sv(t),ov)try{return Cl(e,t)}catch(r){}if(nv(e,t))return iv(!tv(rv.f,e,t),e[t])}});var Cn=b((vw,Ol)=>{"use strict";var uv=De(),cv=ce(),lv=/#|\.prototype\./,ni=function(a,e){var t=pv[dv(a)];return t===fv?!0:t===hv?!1:cv(e)?uv(e):!!e},dv=ni.normalize=function(a){return String(a).replace(lv,".").toLowerCase()},pv=ni.data={},hv=ni.NATIVE="N",fv=ni.POLYFILL="P";Ol.exports=ni});var oi=b((yw,_l)=>{"use strict";var Vl=Mn(),mv=pt(),bv=Kr(),gv=Vl(Vl.bind);_l.exports=function(a,e){return mv(a),e===void 0?a:bv?gv(a,e):function(){return a.apply(e,arguments)}}});var Ue=b((Tw,Fl)=>{"use strict";var ui=le(),Sv=Ln(),vv=Mn(),yv=ce(),Tv=Bl().f,Iv=Cn(),Sr=ka(),Ev=oi(),vr=gr(),Nl=Xe();ri();var xv=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return Sv(a,this,arguments)};return e.prototype=a.prototype,e};Fl.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?ui:i?ui[t]:ui[t]&&ui[t].prototype,o=r?Sr:Sr[t]||vr(Sr,t,{})[t],u=o.prototype,c,l,d,p,h,m,g,S,T;for(p in e)c=Iv(r?p:t+(i?".":"#")+p,a.forced),l=!c&&n&&Nl(n,p),m=o[p],l&&(a.dontCallGetSet?(T=Tv(n,p),g=T&&T.value):g=n[p]),h=l&&g?g:e[p],!(!c&&!s&&typeof m==typeof h)&&(a.bind&&l?S=Ev(h,ui):a.wrap&&l?S=xv(h):s&&yv(h)?S=vv(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&vr(S,"sham",!0),vr(o,p,S),s&&(d=t+"Prototype",Nl(Sr,d)||vr(Sr,d,{}),vr(Sr[d],p,h),a.real&&u&&(c||!u[p])&&vr(u,p,h)))}});var Hl=b((Iw,Ul)=>{"use strict";var Dn=qe(),Pv=Xe(),ql=Function.prototype,Av=Dn&&Object.getOwnPropertyDescriptor,Bn=Pv(ql,"name"),wv=Bn&&function(){}.name==="something",kv=Bn&&(!Dn||Dn&&Av(ql,"name").configurable);Ul.exports={EXISTS:Bn,PROPER:wv,CONFIGURABLE:kv}});var Gl=b((Ew,jl)=>{"use strict";var Rv=Math.ceil,$v=Math.floor;jl.exports=Math.trunc||function(e){var t=+e;return(t>0?$v:Rv)(t)}});var Ba=b((xw,Wl)=>{"use strict";var Lv=Gl();Wl.exports=function(a){var e=+a;return e!==e||e===0?0:Lv(e)}});var Ql=b((Pw,Yl)=>{"use strict";var Mv=Ba(),Cv=Math.max,Dv=Math.min;Yl.exports=function(a,e){var t=Mv(a);return t<0?Cv(t+e,0):Dv(t,e)}});var Kl=b((Aw,zl)=>{"use strict";var Bv=Ba(),Ov=Math.min;zl.exports=function(a){var e=Bv(a);return e>0?Ov(e,9007199254740991):0}});var Oa=b((ww,Jl)=>{"use strict";var Vv=Kl();Jl.exports=function(a){return Vv(a.length)}});var ed=b((kw,Zl)=>{"use strict";var _v=fr(),Nv=Ql(),Fv=Oa(),Xl=function(a){return function(e,t,r){var i=_v(e),s=Fv(i);if(s===0)return!a&&-1;var n=Nv(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Zl.exports={includes:Xl(!0),indexOf:Xl(!1)}});var id=b((Rw,rd)=>{"use strict";var qv=Pe(),On=Xe(),Uv=fr(),Hv=ed().indexOf,jv=Ma(),td=qv([].push);rd.exports=function(a,e){var t=Uv(a),r=0,i=[],s;for(s in t)!On(jv,s)&&On(t,s)&&td(i,s);for(;e.length>r;)On(t,s=e[r++])&&(~Hv(i,s)||td(i,s));return i}});var Vn=b(($w,ad)=>{"use strict";ad.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var nd=b((Lw,sd)=>{"use strict";var Gv=id(),Wv=Vn();sd.exports=Object.keys||function(e){return Gv(e,Wv)}});var ud=b(od=>{"use strict";var Yv=qe(),Qv=un(),zv=Gt(),Kv=at(),Jv=fr(),Xv=nd();od.f=Yv&&!Qv?Object.defineProperties:function(e,t){Kv(e);for(var r=Jv(t),i=Xv(t),s=i.length,n=0,o;s>n;)zv.f(e,o=i[n++],r[o]);return e}});var _n=b((Cw,cd)=>{"use strict";var Zv=dt();cd.exports=Zv("document","documentElement")});var Un=b((Dw,bd)=>{"use strict";var ey=at(),ty=ud(),ld=Vn(),ry=Ma(),iy=_n(),ay=Aa(),sy=La(),dd=">",pd="<",Fn="prototype",qn="script",fd=sy("IE_PROTO"),Nn=function(){},md=function(a){return pd+qn+dd+a+pd+"/"+qn+dd},hd=function(a){a.write(md("")),a.close();var e=a.parentWindow.Object;return a=null,e},ny=function(){var a=ay("iframe"),e="java"+qn+":",t;return a.style.display="none",iy.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(md("document.F=Object")),t.close(),t.F},Va,_a=function(){try{Va=new ActiveXObject("htmlfile")}catch(e){}_a=typeof document!="undefined"?document.domain&&Va?hd(Va):ny():hd(Va);for(var a=ld.length;a--;)delete _a[Fn][ld[a]];return _a()};ry[fd]=!0;bd.exports=Object.create||function(e,t){var r;return e!==null?(Nn[Fn]=ey(e),r=new Nn,Nn[Fn]=null,r[fd]=e):r=_a(),t===void 0?r:ty.f(r,t)}});var Sd=b((Bw,gd)=>{"use strict";var oy=De();gd.exports=!oy(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var jn=b((Ow,yd)=>{"use strict";var uy=Xe(),cy=ce(),ly=ii(),dy=La(),py=Sd(),vd=dy("IE_PROTO"),Hn=Object,hy=Hn.prototype;yd.exports=py?Hn.getPrototypeOf:function(a){var e=ly(a);if(uy(e,vd))return e[vd];var t=e.constructor;return cy(t)&&e instanceof t?t.prototype:e instanceof Hn?hy:null}});var yr=b((Vw,Td)=>{"use strict";var fy=gr();Td.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:fy(a,e,t),a}});var Qn=b((_w,xd)=>{"use strict";var my=De(),by=ce(),gy=Fe(),Sy=Un(),Id=jn(),vy=yr(),yy=ye(),Ty=Je(),Yn=yy("iterator"),Ed=!1,ht,Gn,Wn;[].keys&&(Wn=[].keys(),"next"in Wn?(Gn=Id(Id(Wn)),Gn!==Object.prototype&&(ht=Gn)):Ed=!0);var Iy=!gy(ht)||my(function(){var a={};return ht[Yn].call(a)!==a});Iy?ht={}:Ty&&(ht=Sy(ht));by(ht[Yn])||vy(ht,Yn,function(){return this});xd.exports={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:Ed}});var Na=b((Nw,Ad)=>{"use strict";var Ey=ye(),xy=Ey("toStringTag"),Pd={};Pd[xy]="z";Ad.exports=String(Pd)==="[object z]"});var ci=b((Fw,wd)=>{"use strict";var Py=Na(),Ay=ce(),Fa=pr(),wy=ye(),ky=wy("toStringTag"),Ry=Object,$y=Fa(function(){return arguments}())==="Arguments",Ly=function(a,e){try{return a[e]}catch(t){}};wd.exports=Py?Fa:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=Ly(e=Ry(a),ky))=="string"?t:$y?Fa(e):(r=Fa(e))==="Object"&&Ay(e.callee)?"Arguments":r}});var Rd=b((qw,kd)=>{"use strict";var My=Na(),Cy=ci();kd.exports=My?{}.toString:function(){return"[object "+Cy(this)+"]"}});var li=b((Uw,Ld)=>{"use strict";var Dy=Na(),By=Gt().f,Oy=gr(),Vy=Xe(),_y=Rd(),Ny=ye(),$d=Ny("toStringTag");Ld.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(Vy(i,$d)||By(i,$d,{configurable:!0,value:e}),r&&!Dy&&Oy(i,"toString",_y))}});var Cd=b((Hw,Md)=>{"use strict";var Fy=Qn().IteratorPrototype,qy=Un(),Uy=ai(),Hy=li(),jy=jt(),Gy=function(){return this};Md.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=qy(Fy,{next:Uy(+!r,t)}),Hy(a,i,!1,!0),jy[i]=Gy,a}});var Bd=b((jw,Dd)=>{"use strict";var Wy=Pe(),Yy=pt();Dd.exports=function(a,e,t){try{return Wy(Yy(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Vd=b((Gw,Od)=>{"use strict";var Qy=Fe();Od.exports=function(a){return Qy(a)||a===null}});var Nd=b((Ww,_d)=>{"use strict";var zy=Vd(),Ky=String,Jy=TypeError;_d.exports=function(a){if(zy(a))return a;throw new Jy("Can't set "+Ky(a)+" as a prototype")}});var zn=b((Yw,Fd)=>{"use strict";var Xy=Bd(),Zy=Fe(),eT=Jr(),tT=Nd();Fd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Xy(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return eT(i),tT(s),Zy(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Jd=b((Qw,Kd)=>{"use strict";var rT=Ue(),iT=Be(),qa=Je(),Qd=Hl(),aT=ce(),sT=Cd(),qd=jn(),Ud=zn(),nT=li(),oT=gr(),Kn=yr(),uT=ye(),Hd=jt(),zd=Qn(),cT=Qd.PROPER,lT=Qd.CONFIGURABLE,jd=zd.IteratorPrototype,Ua=zd.BUGGY_SAFARI_ITERATORS,di=uT("iterator"),Gd="keys",pi="values",Wd="entries",Yd=function(){return this};Kd.exports=function(a,e,t,r,i,s,n){sT(t,e,r);var o=function(T){if(T===i&&p)return p;if(!Ua&&T&&T in l)return l[T];switch(T){case Gd:return function(){return new t(this,T)};case pi:return function(){return new t(this,T)};case Wd:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[di]||l["@@iterator"]||i&&l[i],p=!Ua&&d||o(i),h=e==="Array"&&l.entries||d,m,g,S;if(h&&(m=qd(h.call(new a)),m!==Object.prototype&&m.next&&(!qa&&qd(m)!==jd&&(Ud?Ud(m,jd):aT(m[di])||Kn(m,di,Yd)),nT(m,u,!0,!0),qa&&(Hd[u]=Yd))),cT&&i===pi&&d&&d.name!==pi&&(!qa&&lT?oT(l,"name",pi):(c=!0,p=function(){return iT(d,this)})),i)if(g={values:o(pi),keys:s?p:o(Gd),entries:o(Wd)},n)for(S in g)(Ua||c||!(S in l))&&Kn(l,S,g[S]);else rT({target:e,proto:!0,forced:Ua||c},g);return(!qa||n)&&l[di]!==p&&Kn(l,di,p,{name:i}),Hd[e]=p,g}});var Zd=b((zw,Xd)=>{"use strict";Xd.exports=function(a,e){return{value:a,done:e}}});var Xn=b((Kw,ap)=>{"use strict";var dT=fr(),Jn=rn(),ep=jt(),rp=$n(),pT=Gt().f,hT=Jd(),Ha=Zd(),fT=Je(),mT=qe(),ip="Array Iterator",bT=rp.set,gT=rp.getterFor(ip);ap.exports=hT(Array,"Array",function(a,e){bT(this,{type:ip,target:dT(a),index:0,kind:e})},function(){var a=gT(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ha(void 0,!0);switch(a.kind){case"keys":return Ha(t,!1);case"values":return Ha(e[t],!1)}return Ha([t,e[t]],!1)},"values");var tp=ep.Arguments=ep.Array;Jn("keys");Jn("values");Jn("entries");if(!fT&&mT&&tp.name!=="values")try{pT(tp,"name",{value:"values"})}catch(a){}});var np=b((Jw,sp)=>{"use strict";var ST=ye(),vT=jt(),yT=ST("iterator"),TT=Array.prototype;sp.exports=function(a){return a!==void 0&&(vT.Array===a||TT[yT]===a)}});var Zn=b((Xw,up)=>{"use strict";var IT=ci(),op=ti(),ET=hr(),xT=jt(),PT=ye(),AT=PT("iterator");up.exports=function(a){if(!ET(a))return op(a,AT)||op(a,"@@iterator")||xT[IT(a)]}});var lp=b((Zw,cp)=>{"use strict";var wT=Be(),kT=pt(),RT=at(),$T=ei(),LT=Zn(),MT=TypeError;cp.exports=function(a,e){var t=arguments.length<2?LT(a):e;if(kT(t))return RT(wT(t,a));throw new MT($T(a)+" is not iterable")}});var hp=b((ek,pp)=>{"use strict";var CT=Be(),dp=at(),DT=ti();pp.exports=function(a,e,t){var r,i;dp(a);try{if(r=DT(a,"return"),!r){if(e==="throw")throw t;return t}r=CT(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return dp(r),t}});var Ga=b((tk,gp)=>{"use strict";var BT=oi(),OT=Be(),VT=at(),_T=ei(),NT=np(),FT=Oa(),fp=Zr(),qT=lp(),UT=Zn(),mp=hp(),HT=TypeError,ja=function(a,e){this.stopped=a,this.result=e},bp=ja.prototype;gp.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=BT(e,r),c,l,d,p,h,m,g,S=function(P){return c&&mp(c,"normal",P),new ja(!0,P)},T=function(P){return i?(VT(P),o?u(P[0],P[1],S):u(P[0],P[1])):o?u(P,S):u(P)};if(s)c=a.iterator;else if(n)c=a;else{if(l=UT(a),!l)throw new HT(_T(a)+" is not iterable");if(NT(l)){for(d=0,p=FT(a);p>d;d++)if(h=T(a[d]),h&&fp(bp,h))return h;return new ja(!1)}c=qT(a,l)}for(m=s?a.next:c.next;!(g=OT(m,c)).done;){try{h=T(g.value)}catch(P){mp(c,"throw",P)}if(typeof h=="object"&&h&&fp(bp,h))return h}return new ja(!1)}});var vp=b((rk,Sp)=>{"use strict";var jT=qe(),GT=Gt(),WT=ai();Sp.exports=function(a,e,t){jT?GT.f(a,e,WT(0,t)):a[e]=t}});var yp=b(()=>{"use strict";var YT=Ue(),QT=Ga(),zT=vp();YT({target:"Object",stat:!0},{fromEntries:function(e){var t={};return QT(e,function(r,i){zT(t,r,i)},{AS_ENTRIES:!0}),t}})});var Ip=b((sk,Tp)=>{"use strict";Xn();yp();var KT=ka();Tp.exports=KT.Object.fromEntries});var xp=b((nk,Ep)=>{"use strict";Ep.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 Ap=b(()=>{"use strict";Xn();var JT=xp(),XT=le(),ZT=li(),Pp=jt();for(Wa in JT)ZT(XT[Wa],Wa),Pp[Wa]=Pp.Array;var Wa});var kp=b((ck,wp)=>{"use strict";var eI=Ip();Ap();wp.exports=eI});var eo=b((lk,Rp)=>{"use strict";var tI=kp();Rp.exports=tI});var $p=b(()=>{"use strict"});var to=b((hk,Lp)=>{"use strict";var hi=le(),rI=mr(),iI=pr(),Ya=function(a){return rI.slice(0,a.length)===a};Lp.exports=function(){return Ya("Bun/")?"BUN":Ya("Cloudflare-Workers")?"CLOUDFLARE":Ya("Deno/")?"DENO":Ya("Node.js/")?"NODE":hi.Bun&&typeof Bun.version=="string"?"BUN":hi.Deno&&typeof Deno.version=="object"?"DENO":iI(hi.process)==="process"?"NODE":hi.window&&hi.document?"BROWSER":"REST"}()});var Qa=b((fk,Mp)=>{"use strict";var aI=to();Mp.exports=aI==="NODE"});var Dp=b((mk,Cp)=>{"use strict";var sI=Gt();Cp.exports=function(a,e,t){return sI.f(a,e,t)}});var Vp=b((bk,Op)=>{"use strict";var nI=dt(),oI=Dp(),uI=ye(),cI=qe(),Bp=uI("species");Op.exports=function(a){var e=nI(a);cI&&e&&!e[Bp]&&oI(e,Bp,{configurable:!0,get:function(){return this}})}});var Np=b((gk,_p)=>{"use strict";var lI=Zr(),dI=TypeError;_p.exports=function(a,e){if(lI(e,a))return a;throw new dI("Incorrect invocation")}});var io=b((Sk,Fp)=>{"use strict";var pI=Pe(),hI=ce(),ro=ri(),fI=pI(Function.toString);hI(ro.inspectSource)||(ro.inspectSource=function(a){return fI(a)});Fp.exports=ro.inspectSource});var Wp=b((vk,Gp)=>{"use strict";var mI=Pe(),bI=De(),qp=ce(),gI=ci(),SI=dt(),vI=io(),Up=function(){},Hp=SI("Reflect","construct"),ao=/^\s*(?:class|function)\b/,yI=mI(ao.exec),TI=!ao.test(Up),fi=function(e){if(!qp(e))return!1;try{return Hp(Up,[],e),!0}catch(t){return!1}},jp=function(e){if(!qp(e))return!1;switch(gI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return TI||!!yI(ao,vI(e))}catch(t){return!0}};jp.sham=!0;Gp.exports=!Hp||bI(function(){var a;return fi(fi.call)||!fi(Object)||!fi(function(){a=!0})||a})?jp:fi});var Qp=b((yk,Yp)=>{"use strict";var II=Wp(),EI=ei(),xI=TypeError;Yp.exports=function(a){if(II(a))return a;throw new xI(EI(a)+" is not a constructor")}});var so=b((Tk,Kp)=>{"use strict";var zp=at(),PI=Qp(),AI=hr(),wI=ye(),kI=wI("species");Kp.exports=function(a,e){var t=zp(a).constructor,r;return t===void 0||AI(r=zp(t)[kI])?e:PI(r)}});var Xp=b((Ik,Jp)=>{"use strict";var RI=Pe();Jp.exports=RI([].slice)});var eh=b((Ek,Zp)=>{"use strict";var $I=TypeError;Zp.exports=function(a,e){if(a<e)throw new $I("Not enough arguments");return a}});var no=b((xk,th)=>{"use strict";var LI=mr();th.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(LI)});var bo=b((Pk,lh)=>{"use strict";var Oe=le(),MI=Ln(),CI=oi(),rh=ce(),DI=Xe(),ch=De(),ih=_n(),BI=Xp(),ah=Aa(),OI=eh(),VI=no(),_I=Qa(),ho=Oe.setImmediate,fo=Oe.clearImmediate,NI=Oe.process,oo=Oe.Dispatch,FI=Oe.Function,sh=Oe.MessageChannel,qI=Oe.String,uo=0,mi={},nh="onreadystatechange",bi,Yt,co,lo;ch(function(){bi=Oe.location});var mo=function(a){if(DI(mi,a)){var e=mi[a];delete mi[a],e()}},po=function(a){return function(){mo(a)}},oh=function(a){mo(a.data)},uh=function(a){Oe.postMessage(qI(a),bi.protocol+"//"+bi.host)};(!ho||!fo)&&(ho=function(e){OI(arguments.length,1);var t=rh(e)?e:FI(e),r=BI(arguments,1);return mi[++uo]=function(){MI(t,void 0,r)},Yt(uo),uo},fo=function(e){delete mi[e]},_I?Yt=function(a){NI.nextTick(po(a))}:oo&&oo.now?Yt=function(a){oo.now(po(a))}:sh&&!VI?(co=new sh,lo=co.port2,co.port1.onmessage=oh,Yt=CI(lo.postMessage,lo)):Oe.addEventListener&&rh(Oe.postMessage)&&!Oe.importScripts&&bi&&bi.protocol!=="file:"&&!ch(uh)?(Yt=uh,Oe.addEventListener("message",oh,!1)):nh in ah("script")?Yt=function(a){ih.appendChild(ah("script"))[nh]=function(){ih.removeChild(this),mo(a)}}:Yt=function(a){setTimeout(po(a),0)});lh.exports={set:ho,clear:fo}});var hh=b((Ak,ph)=>{"use strict";var dh=le(),UI=qe(),HI=Object.getOwnPropertyDescriptor;ph.exports=function(a){if(!UI)return dh[a];var e=HI(dh,a);return e&&e.value}});var go=b((wk,mh)=>{"use strict";var fh=function(){this.head=null,this.tail=null};fh.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}}};mh.exports=fh});var gh=b((kk,bh)=>{"use strict";var jI=mr();bh.exports=/ipad|iphone|ipod/i.test(jI)&&typeof Pebble!="undefined"});var vh=b((Rk,Sh)=>{"use strict";var GI=mr();Sh.exports=/web0s(?!.*chrome)/i.test(GI)});var Ah=b(($k,Ph)=>{"use strict";var Ir=le(),WI=hh(),yh=oi(),So=bo().set,YI=go(),QI=no(),zI=gh(),KI=vh(),vo=Qa(),Th=Ir.MutationObserver||Ir.WebKitMutationObserver,Ih=Ir.document,Eh=Ir.process,za=Ir.Promise,Io=WI("queueMicrotask"),Tr,yo,To,Ka,xh;Io||(gi=new YI,Si=function(){var a,e;for(vo&&(a=Eh.domain)&&a.exit();e=gi.get();)try{e()}catch(t){throw gi.head&&Tr(),t}a&&a.enter()},!QI&&!vo&&!KI&&Th&&Ih?(yo=!0,To=Ih.createTextNode(""),new Th(Si).observe(To,{characterData:!0}),Tr=function(){To.data=yo=!yo}):!zI&&za&&za.resolve?(Ka=za.resolve(void 0),Ka.constructor=za,xh=yh(Ka.then,Ka),Tr=function(){xh(Si)}):vo?Tr=function(){Eh.nextTick(Si)}:(So=yh(So,Ir),Tr=function(){So(Si)}),Io=function(a){gi.head||Tr(),gi.add(a)});var gi,Si;Ph.exports=Io});var kh=b((Lk,wh)=>{"use strict";wh.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ja=b((Mk,Rh)=>{"use strict";Rh.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Qt=b((Ck,$h)=>{"use strict";var JI=le();$h.exports=JI.Promise});var Er=b((Dk,Dh)=>{"use strict";var XI=le(),vi=Qt(),ZI=ce(),eE=Cn(),tE=io(),rE=ye(),Lh=to(),iE=Je(),Eo=pn(),Mh=vi&&vi.prototype,aE=rE("species"),xo=!1,Ch=ZI(XI.PromiseRejectionEvent),sE=eE("Promise",function(){var a=tE(vi),e=a!==String(vi);if(!e&&Eo===66||iE&&!(Mh.catch&&Mh.finally))return!0;if(!Eo||Eo<51||!/native code/.test(a)){var t=new vi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[aE]=r,xo=t.then(function(){})instanceof r,!xo)return!0}return!e&&(Lh==="BROWSER"||Lh==="DENO")&&!Ch});Dh.exports={CONSTRUCTOR:sE,REJECTION_EVENT:Ch,SUBCLASSING:xo}});var xr=b((Bk,Oh)=>{"use strict";var Bh=pt(),nE=TypeError,oE=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new nE("Bad Promise constructor");e=r,t=i}),this.resolve=Bh(e),this.reject=Bh(t)};Oh.exports.f=function(a){return new oE(a)}});var tf=b(()=>{"use strict";var uE=Ue(),cE=Je(),ts=Qa(),Lt=le(),kr=Be(),Vh=yr(),_h=zn(),lE=li(),dE=Vp(),pE=pt(),es=ce(),hE=Fe(),fE=Np(),mE=so(),Hh=bo().set,Ro=Ah(),bE=kh(),gE=Ja(),SE=go(),jh=$n(),rs=Qt(),$o=Er(),Gh=xr(),is="Promise",Wh=$o.CONSTRUCTOR,vE=$o.REJECTION_EVENT,yE=$o.SUBCLASSING,Po=jh.getterFor(is),TE=jh.set,Pr=rs&&rs.prototype,zt=rs,Xa=Pr,Yh=Lt.TypeError,Ao=Lt.document,Lo=Lt.process,wo=Gh.f,IE=wo,EE=!!(Ao&&Ao.createEvent&&Lt.dispatchEvent),Qh="unhandledrejection",xE="rejectionhandled",Nh=0,zh=1,PE=2,Mo=1,Kh=2,Za,Fh,AE,qh,Jh=function(a){var e;return hE(a)&&es(e=a.then)?e:!1},Xh=function(a,e){var t=e.value,r=e.state===zh,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{i?(r||(e.rejection===Kh&&kE(e),e.rejection=Mo),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),l=!0)),u===a.promise?n(new Yh("Promise-chain cycle")):(c=Jh(u))?kr(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},Zh=function(a,e){a.notified||(a.notified=!0,Ro(function(){for(var t=a.reactions,r;r=t.get();)Xh(r,a);a.notified=!1,e&&!a.rejection&&wE(a)}))},ef=function(a,e,t){var r,i;EE?(r=Ao.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Lt.dispatchEvent(r)):r={promise:e,reason:t},!vE&&(i=Lt["on"+a])?i(r):a===Qh&&bE("Unhandled promise rejection",t)},wE=function(a){kr(Hh,Lt,function(){var e=a.facade,t=a.value,r=Uh(a),i;if(r&&(i=gE(function(){ts?Lo.emit("unhandledRejection",t,e):ef(Qh,e,t)}),a.rejection=ts||Uh(a)?Kh:Mo,i.error))throw i.value})},Uh=function(a){return a.rejection!==Mo&&!a.parent},kE=function(a){kr(Hh,Lt,function(){var e=a.facade;ts?Lo.emit("rejectionHandled",e):ef(xE,e,a.value)})},Ar=function(a,e,t){return function(r){a(e,r,t)}},wr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=PE,Zh(a,!0))},ko=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Yh("Promise can't be resolved itself");var r=Jh(e);r?Ro(function(){var i={done:!1};try{kr(r,e,Ar(ko,i,a),Ar(wr,i,a))}catch(s){wr(i,s,a)}}):(a.value=e,a.state=zh,Zh(a,!1))}catch(i){wr({done:!1},i,a)}}};if(Wh&&(zt=function(e){fE(this,Xa),pE(e),kr(Za,this);var t=Po(this);try{e(Ar(ko,t),Ar(wr,t))}catch(r){wr(t,r)}},Xa=zt.prototype,Za=function(e){TE(this,{type:is,done:!1,notified:!1,parent:!1,reactions:new SE,rejection:!1,state:Nh,value:void 0})},Za.prototype=Vh(Xa,"then",function(e,t){var r=Po(this),i=wo(mE(this,zt));return r.parent=!0,i.ok=es(e)?e:!0,i.fail=es(t)&&t,i.domain=ts?Lo.domain:void 0,r.state===Nh?r.reactions.add(i):Ro(function(){Xh(i,r)}),i.promise}),Fh=function(){var a=new Za,e=Po(a);this.promise=a,this.resolve=Ar(ko,e),this.reject=Ar(wr,e)},Gh.f=wo=function(a){return a===zt||a===AE?new Fh(a):IE(a)},!cE&&es(rs)&&Pr!==Object.prototype)){qh=Pr.then,yE||Vh(Pr,"then",function(e,t){var r=this;return new zt(function(i,s){kr(qh,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Pr.constructor}catch(a){}_h&&_h(Pr,Xa)}uE({global:!0,constructor:!0,wrap:!0,forced:Wh},{Promise:zt});lE(zt,is,!1,!0);dE(is)});var of=b((_k,nf)=>{"use strict";var RE=ye(),af=RE("iterator"),sf=!1;try{rf=0,Co={next:function(){return{done:!!rf++}},return:function(){sf=!0}},Co[af]=function(){return this},Array.from(Co,function(){throw 2})}catch(a){}var rf,Co;nf.exports=function(a,e){try{if(!e&&!sf)return!1}catch(i){return!1}var t=!1;try{var r={};r[af]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Do=b((Nk,uf)=>{"use strict";var $E=Qt(),LE=of(),ME=Er().CONSTRUCTOR;uf.exports=ME||!LE(function(a){$E.all(a).then(void 0,function(){})})});var cf=b(()=>{"use strict";var CE=Ue(),DE=Be(),BE=pt(),OE=xr(),VE=Ja(),_E=Ga(),NE=Do();CE({target:"Promise",stat:!0,forced:NE},{all:function(e){var t=this,r=OE.f(t),i=r.resolve,s=r.reject,n=VE(function(){var o=BE(t.resolve),u=[],c=0,l=1;_E(e,function(d){var p=c++,h=!1;l++,DE(o,t,d).then(function(m){h||(h=!0,u[p]=m,--l||i(u))},s)}),--l||i(u)});return n.error&&s(n.value),r.promise}})});var df=b(()=>{"use strict";var FE=Ue(),qE=Je(),UE=Er().CONSTRUCTOR,Oo=Qt(),HE=dt(),jE=ce(),GE=yr(),lf=Oo&&Oo.prototype;FE({target:"Promise",proto:!0,forced:UE,real:!0},{catch:function(a){return this.then(void 0,a)}});!qE&&jE(Oo)&&(Bo=HE("Promise").prototype.catch,lf.catch!==Bo&&GE(lf,"catch",Bo,{unsafe:!0}));var Bo});var pf=b(()=>{"use strict";var WE=Ue(),YE=Be(),QE=pt(),zE=xr(),KE=Ja(),JE=Ga(),XE=Do();WE({target:"Promise",stat:!0,forced:XE},{race:function(e){var t=this,r=zE.f(t),i=r.reject,s=KE(function(){var n=QE(t.resolve);JE(e,function(o){YE(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var hf=b(()=>{"use strict";var ZE=Ue(),ex=xr(),tx=Er().CONSTRUCTOR;ZE({target:"Promise",stat:!0,forced:tx},{reject:function(e){var t=ex.f(this),r=t.reject;return r(e),t.promise}})});var Vo=b((Qk,ff)=>{"use strict";var rx=at(),ix=Fe(),ax=xr();ff.exports=function(a,e){if(rx(a),ix(e)&&e.constructor===a)return e;var t=ax.f(a),r=t.resolve;return r(e),t.promise}});var gf=b(()=>{"use strict";var sx=Ue(),nx=dt(),mf=Je(),ox=Qt(),bf=Er().CONSTRUCTOR,ux=Vo(),cx=nx("Promise"),lx=mf&&!bf;sx({target:"Promise",stat:!0,forced:mf||bf},{resolve:function(e){return ux(lx&&this===cx?ox:this,e)}})});var Sf=b(()=>{"use strict";tf();cf();df();pf();hf();gf()});var If=b(()=>{"use strict";var dx=Ue(),px=Je(),as=Qt(),hx=De(),yf=dt(),Tf=ce(),fx=so(),vf=Vo(),mx=yr(),No=as&&as.prototype,bx=!!as&&hx(function(){No.finally.call({then:function(){}},function(){})});dx({target:"Promise",proto:!0,real:!0,forced:bx},{finally:function(a){var e=fx(this,yf("Promise")),t=Tf(a);return this.then(t?function(r){return vf(e,a()).then(function(){return r})}:a,t?function(r){return vf(e,a()).then(function(){throw r})}:a)}});!px&&Tf(as)&&(_o=yf("Promise").prototype.finally,No.finally!==_o&&mx(No,"finally",_o,{unsafe:!0}));var _o});var ss=b((tR,Ef)=>{"use strict";var gx=dt();Ef.exports=gx});var Pf=b((rR,xf)=>{"use strict";$p();Sf();If();var Sx=ss();xf.exports=Sx("Promise","finally")});var wf=b((iR,Af)=>{"use strict";var vx=Pf();Af.exports=vx});var ns=b((aR,kf)=>{"use strict";var yx=wf();kf.exports=yx});var _f=b(()=>{"use strict";var kx=Ue(),Rx=ii(),$x=Oa(),Lx=Ba(),Mx=rn();kx({target:"Array",proto:!0},{at:function(e){var t=Rx(this),r=$x(t),i=Lx(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});Mx("at")});var Ff=b((r$,Nf)=>{"use strict";_f();var Cx=ss();Nf.exports=Cx("Array","at")});var Uf=b((i$,qf)=>{"use strict";var Dx=Ff();qf.exports=Dx});var Ti=b((a$,Hf)=>{"use strict";var Bx=Uf();Hf.exports=Bx});var Dm=b(()=>{"use strict"});var Bm=b(()=>{"use strict"});var Vm=b((ZC,Om)=>{"use strict";var mP=Fe(),bP=pr(),gP=ye(),SP=gP("match");Om.exports=function(a){var e;return mP(a)&&((e=a[SP])!==void 0?!!e:bP(a)==="RegExp")}});var Nm=b((eD,_m)=>{"use strict";var vP=ci(),yP=String;_m.exports=function(a){if(vP(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return yP(a)}});var qm=b((tD,Fm)=>{"use strict";var TP=at();Fm.exports=function(){var a=TP(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 jm=b((rD,Hm)=>{"use strict";var IP=Be(),EP=Xe(),xP=Zr(),PP=qm(),Um=RegExp.prototype;Hm.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Um)&&!EP(a,"flags")&&xP(Um,a)?IP(PP,a):e}});var Wm=b((iD,Gm)=>{"use strict";var uu=Pe(),AP=ii(),wP=Math.floor,nu=uu("".charAt),kP=uu("".replace),ou=uu("".slice),RP=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,$P=/\$([$&'`]|\d{1,2})/g;Gm.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=$P;return i!==void 0&&(i=AP(i),u=RP),kP(s,u,function(c,l){var d;switch(nu(l,0)){case"$":return"$";case"&":return a;case"`":return ou(e,0,t);case"'":return ou(e,n);case"<":d=i[ou(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=wP(p/10);return h===0?c:h<=o?r[h-1]===void 0?nu(l,1):r[h-1]+nu(l,1):c}d=r[p-1]}return d===void 0?"":d})}});var zm=b(()=>{"use strict";var LP=Ue(),MP=Be(),lu=Pe(),Ym=Jr(),CP=ce(),DP=hr(),BP=Vm(),_r=Nm(),OP=ti(),VP=jm(),_P=Wm(),NP=ye(),FP=Je(),qP=NP("replace"),UP=TypeError,cu=lu("".indexOf),HP=lu("".replace),Qm=lu("".slice),jP=Math.max;LP({target:"String",proto:!0},{replaceAll:function(e,t){var r=Ym(this),i,s,n,o,u,c,l,d,p,h,m=0,g="";if(!DP(e)){if(i=BP(e),i&&(s=_r(Ym(VP(e))),!~cu(s,"g")))throw new UP("`.replaceAll` does not allow non-global regexes");if(n=OP(e,qP),n)return MP(n,e,r,t);if(FP&&i)return HP(_r(r),e,t)}for(o=_r(r),u=_r(e),c=CP(t),c||(t=_r(t)),l=u.length,d=jP(1,l),p=cu(o,u);p!==-1;)h=c?_r(t(u,p,o)):_P(u,o,p,[],void 0,t),g+=Qm(o,m,p)+h,m=p+l,p=p+d>o.length?-1:cu(o,u,p+d);return m<o.length&&(g+=Qm(o,m)),g}})});var Jm=b((nD,Km)=>{"use strict";Dm();Bm();zm();var GP=ss();Km.exports=GP("String","replaceAll")});var Zm=b((oD,Xm)=>{"use strict";var WP=Jm();Xm.exports=WP});var tb=b((uD,eb)=>{"use strict";var YP=Zm();eb.exports=YP});var uA={};lg(uA,{ChromecastState:()=>zr,HttpConnectionType:()=>Ea,Observable:()=>ct.Observable,PlaybackState:()=>ve,Player:()=>ba,SDK_VERSION:()=>oA,Subject:()=>ct.Subject,Subscription:()=>ct.Subscription,Surface:()=>xa,VERSION:()=>Zs,ValueSubject:()=>ct.ValueSubject,VideoFormat:()=>lt,VideoQuality:()=>ct.VideoQuality});module.exports=dg(uA);var Zs="2.0.111-dev.2c18acf4.0";var ve=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ve||{}),lt=(I=>(I.MPEG="MPEG",I.DASH="DASH",I.DASH_SEP="DASH_SEP",I.DASH_SEP_VK="DASH_SEP",I.DASH_WEBM="DASH_WEBM",I.DASH_WEBM_AV1="DASH_WEBM_AV1",I.DASH_STREAMS="DASH_STREAMS",I.DASH_WEBM_VK="DASH_WEBM",I.DASH_ONDEMAND="DASH_ONDEMAND",I.DASH_ONDEMAND_VK="DASH_ONDEMAND",I.DASH_LIVE="DASH_LIVE",I.DASH_LIVE_CMAF="DASH_LIVE_CMAF",I.DASH_LIVE_WEBM="DASH_LIVE_WEBM",I.HLS="HLS",I.HLS_ONDEMAND="HLS_ONDEMAND",I.HLS_JS="HLS",I.HLS_LIVE="HLS_LIVE",I.HLS_LIVE_CMAF="HLS_LIVE_CMAF",I.WEB_RTC_LIVE="WEB_RTC_LIVE",I))(lt||{});var zr=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(zr||{}),Ea=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Ea||{});var xa=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(xa||{});var q=require("@vkontakte/videoplayer-shared");var Zu=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Pa=class{constructor(e){this.connection$=new q.ValueSubject(void 0);this.castState$=new q.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new q.Subject;this.realCastState$=new q.ValueSubject("NOT_AVAILABLE");this.subscription=new q.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 r=(0,q.isNonNullable)((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Zu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:q.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 r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,q.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,q.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,q.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),r=cast.framework.CastContext.getInstance();this.subscription.add((0,q.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,q.assertNever)(i.sessionState)}})).add((0,q.merge)((0,q.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,q.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,q.map)(i=>i.castState)),(0,q.observableFrom)([r.getCastState()])).pipe((0,q.filterChanged)(),(0,q.map)(pg),(0,q.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=(0,q.isNonNullable)(this.connection$.getValue());if(s&&!n){let c=r.getCurrentSession();(0,q.assertNonNullable)(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,q.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(i==="CONNECTED"?(0,q.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:q.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},pg=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,q.assertNever)(a)}};var xb=ze(eo(),1);var Mf=ze(ns(),1);var Fo=require("@vkontakte/videoplayer-shared");var Se=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:(0,Fo.assertNever)(t)}return a},qo=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:(0,Fo.assertNever)(e)}};var w=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var st=require("@vkontakte/videoplayer-shared"),j=class{constructor(e){this.transitionStarted$=new st.Subject;this.transitionEnded$=new st.Subject;this.transitionUpdated$=new st.Subject;this.forceChanged$=new st.Subject;this.stateChangeStarted$=(0,st.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,st.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||(0,st.isNonNullable)(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Rf=require("@vkontakte/videoplayer-shared"),$f=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,Rf.assertNever)(a)}};var $=require("@vkontakte/videoplayer-shared");var Tx=5,Ix=5,Ex=500,Lf=7e3,yi=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(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(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)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next($f(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)(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe((0,$.map)(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new $.Subject;e.add(i.pipe((0,$.debounce)(Ex)).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)>Tx)&&i.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),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Ix&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=(0,$.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,$.observableFrom)(["init"])).pipe((0,$.debounce)(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),w(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"),w(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"&&w(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var c;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let l=t[e];(0,$.assertNonNullable)(l);let d=(0,$.getHighestQuality)(Object.keys(l));(0,$.assertNonNullable)(d);let p=l[d];(0,$.assertNonNullable)(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];(0,$.assertNonNullable)(l),r=l.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];(0,$.assertNonNullable)(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,$.assertNonNullable)(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,$.assertNonNullable)(l),r=Se(l.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:$.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:r,i);n.contentUrl=r,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 r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add((0,$.timeout)(Lf).subscribe(()=>s(`timeout(${Lf})`)))});(0,Mf.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:$.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Go=require("@vkontakte/videoplayer-shared");var Cf=require("@vkontakte/videoplayer-shared"),Df=a=>{try{a.pause(),a.playbackRate=0,(0,Cf.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var os=require("@vkontakte/videoplayer-shared"),Uo=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)}},Ho=window.WeakMap?new WeakMap:new Uo,jo=window.WeakMap?new WeakMap:new Map,xx=(a,e=20)=>{let t=0;return(0,os.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ae=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?(0,Go.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),Ho.set(t,r);let i=new os.Subscription;return i.add(xx(t,e)),jo.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},we=a=>{let e=jo.get(a);e==null||e.unsubscribe(),jo.delete(a);let t=Ho.get(a);Ho.delete(a),t?(0,Go.clearVideoElement)(a):Df(a)};var L=require("@vkontakte/videoplayer-shared");var Mt=require("@vkontakte/videoplayer-shared"),us=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Mt.isNullable)(i),c=new Mt.Subscription;return i&&c.add(i.subscribe(l=>{let d=a.getState();r(l,d)&&a.setState(l)},s)),r(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(l=>{t(l.to),u&&a.setState(l.to)},s)),c},nt=(a,e,t)=>us(e,()=>a.loop,r=>{(0,Mt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),ke=(a,e,t,r)=>us(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,Mt.isNonNullable)(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),He=(a,e,t,r)=>us(e,()=>a.playbackRate,i=>{(0,Mt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Ct=us;var Px=a=>["__",a.language,a.label].join("|"),Ax=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Wo=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,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:L.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ct(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:i})),this.subscription.add(Ct(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:i})),this.subscription.add(Ct(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Ct(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 r=this.current$.getValue();r&&this.select(r)})),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(r=>this.htmlTextTrackToITextTrack(r))),(0,L.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[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:r})=>r==="showing")),(0,L.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,L.filterChanged)()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var c,l,d,p,h;let u=(l=(c=o.target)==null?void 0:c.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,L.fromEvent)(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;(0,L.isNonNullable)(t.align)&&(i.align=t.align),(0,L.isNonNullable)(t.position)&&(i.position=t.position),(0,L.isNonNullable)(t.size)&&(i.size=t.size),(0,L.isNonNullable)(t.line)&&(i.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;let{language:t,label:r}=e,i=e.id?e.id:Px(e),s=this.externalTracks.has(i),n=i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(i))==null?void 0:o.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(i))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(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)||!Ax(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"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},je=Wo;var mt=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 Bf=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},Yo=a=>{let e=Bf(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Of=a=>{let e=Bf(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var D=require("@vkontakte/videoplayer-shared");var wx=3,Vf=(a,e,t=wx)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Re=a=>{let e=I=>(0,D.fromEvent)(a,I).pipe((0,D.mapTo)(void 0)),r=(0,D.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>(0,D.fromEvent)(a,I))).pipe((0,D.map)(I=>I.type==="ended"?a.readyState<2:a.readyState<3),(0,D.filterChanged)()),i=(0,D.merge)((0,D.fromEvent)(a,"progress"),(0,D.fromEvent)(a,"timeupdate")).pipe((0,D.map)(()=>Vf(a.buffered,a.currentTime))),s=D.clientChecker.isSafari?(0,D.combine)({play:e("play").pipe((0,D.once)()),playing:e("playing")}).pipe((0,D.mapTo)(void 0)):e("playing"),n=(0,D.fromEvent)(a,"volumechange").pipe((0,D.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,D.fromEvent)(a,"ratechange").pipe((0,D.map)(()=>a.playbackRate)),u=(0,D.fromEvent)(a,"error").pipe((0,D.filter)(()=>!!(a.error||a.played.length)),(0,D.map)(()=>{var E;let I=a.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:D.ErrorCategory.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),c=(0,D.fromEvent)(a,"timeupdate").pipe((0,D.map)(()=>a.currentTime)),l=new D.Subject,d=.3,p;c.subscribe(I=>{a.loop&&(0,D.isNonNullable)(p)&&(0,D.isNonNullable)(I)&&p>=a.duration-d&&I<=d&&l.next(p),p=I});let h=e("pause").pipe((0,D.filter)(()=>!a.error&&p!==a.duration)),m=(0,D.fromEvent)(a,"enterpictureinpicture"),g=(0,D.fromEvent)(a,"leavepictureinpicture"),S=new D.ValueSubject(Of(a));m.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let T=new D.ValueSubject(Yo(a));return(0,D.fromEvent)(a,"fullscreenchange").pipe((0,D.map)(()=>Yo(a))).subscribe(T),{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,D.fromEvent)(a,"durationchange").pipe((0,D.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:T}};var bt=require("@vkontakte/videoplayer-shared"),Dt=a=>{switch(a){case"mobile":return bt.VideoQuality.Q_144P;case"lowest":return bt.VideoQuality.Q_240P;case"low":return bt.VideoQuality.Q_360P;case"sd":case"medium":return bt.VideoQuality.Q_480P;case"hd":case"high":return bt.VideoQuality.Q_720P;case"fullhd":case"full":return bt.VideoQuality.Q_1080P;case"quadhd":case"quad":return bt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return bt.VideoQuality.Q_2160P}};var Kt=ze(Ti(),1),B=require("@vkontakte/videoplayer-shared");var Qo=!1,gt={},jf=a=>{Qo=a},Gf=()=>{gt={}},Wf=a=>{a(gt)},Ii=(a,e)=>{var t;Qo&&(gt.meta=(t=gt.meta)!=null?t:{},gt.meta[a]=e)},Te=class{constructor(e){this.name=e}next(e){var r,i;if(!Qo)return;gt.series=(r=gt.series)!=null?r:{};let t=(i=gt.series[this.name])!=null?i:[];t.push([Date.now(),e]),gt.series[this.name]=t}};var Ox=new Te("best_bitrate"),Qf=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var zo=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ei=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,B.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},zf='Assertion "ABR Tracks is empty array" failed',cs=(a,e,t,r)=>{var u;let i=[...e].sort(zo(1)),s=[...t].sort(zo(1)),n=s.filter(c=>(0,B.isNonNullable)(c.bitrate)&&(0,B.isNonNullable)(a.bitrate)?a.bitrate/c.bitrate>r:!0),o=(u=(0,Kt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Kt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Kt.default)(n,-1):(0,Kt.default)(s,0)},Yf=a=>"quality"in a,Kf=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&(0,B.now)()-r.history[t.id]<=a.trackCooldown&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!i&&r.recordSelection(t),i&&(r!=null&&r.last)){let s=r.last;r==null||r.recordSwitch(s);let n=Yf(s)?"video":"audio",o=Yf(s)?s.quality:s.bitrate;return e({message:`
6
+ "use strict";var ig=Object.create;var Qr=Object.defineProperty,ag=Object.defineProperties,sg=Object.getOwnPropertyDescriptor,ng=Object.getOwnPropertyDescriptors,og=Object.getOwnPropertyNames,Ia=Object.getOwnPropertySymbols,ug=Object.getPrototypeOf,Js=Object.prototype.hasOwnProperty,Ku=Object.prototype.propertyIsEnumerable;var cg=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var it=Math.pow,zu=(a,e,t)=>e in a?Qr(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,C=(a,e)=>{for(var t in e||(e={}))Js.call(e,t)&&zu(a,t,e[t]);if(Ia)for(var t of Ia(e))Ku.call(e,t)&&zu(a,t,e[t]);return a},z=(a,e)=>ag(a,ng(e));var Ju=(a,e)=>{var t={};for(var r in a)Js.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&Ia)for(var r of Ia(a))e.indexOf(r)<0&&Ku.call(a,r)&&(t[r]=a[r]);return t};var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),lg=(a,e)=>{for(var t in e)Qr(a,t,{get:e[t],enumerable:!0})},Xu=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of og(e))!Js.call(a,i)&&i!==t&&Qr(a,i,{get:()=>e[i],enumerable:!(r=sg(e,i))||r.enumerable});return a};var ze=(a,e,t)=>(t=a!=null?ig(ug(a)):{},Xu(e||!a||!a.__esModule?Qr(t,"default",{value:a,enumerable:!0}):t,a)),dg=a=>Xu(Qr({},"__esModule",{value:!0}),a);var O=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(c){i(c)}},n=u=>{try{o(t.throw(u))}catch(c){i(c)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),Xs=function(a,e){this[0]=a,this[1]=e},me=(a,e,t)=>{var r=(n,o,u,c)=>{try{var l=t[n](o),d=(o=l.value)instanceof Xs,p=l.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,c):u({value:h,done:p})).catch(h=>r("throw",h,u,c))}catch(h){c(h)}},i=n=>s[n]=o=>new Promise((u,c)=>r(n,o,u,c)),s={};return t=t.apply(a,e),s[cg("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var De=b((IA,ec)=>{"use strict";ec.exports=function(a){try{return!!a()}catch(e){return!0}}});var Kr=b((EA,tc)=>{"use strict";var hg=De();tc.exports=!hg(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Pe=b((xA,ac)=>{"use strict";var rc=Kr(),ic=Function.prototype,en=ic.call,fg=rc&&ic.bind.bind(en,en);ac.exports=rc?fg:function(a){return function(){return en.apply(a,arguments)}}});var pr=b((PA,nc)=>{"use strict";var sc=Pe(),mg=sc({}.toString),bg=sc("".slice);nc.exports=function(a){return bg(mg(a),8,-1)}});var uc=b((AA,oc)=>{"use strict";var gg=Pe(),Sg=De(),vg=pr(),tn=Object,yg=gg("".split);oc.exports=Sg(function(){return!tn("z").propertyIsEnumerable(0)})?function(a){return vg(a)==="String"?yg(a,""):tn(a)}:tn});var hr=b((wA,cc)=>{"use strict";cc.exports=function(a){return a==null}});var Jr=b((kA,lc)=>{"use strict";var Tg=hr(),Ig=TypeError;lc.exports=function(a){if(Tg(a))throw new Ig("Can't call method on "+a);return a}});var fr=b((RA,dc)=>{"use strict";var Eg=uc(),xg=Jr();dc.exports=function(a){return Eg(xg(a))}});var rn=b(($A,pc)=>{"use strict";pc.exports=function(){}});var jt=b((LA,hc)=>{"use strict";hc.exports={}});var le=b((an,fc)=>{"use strict";var Xr=function(a){return a&&a.Math===Math&&a};fc.exports=Xr(typeof globalThis=="object"&&globalThis)||Xr(typeof window=="object"&&window)||Xr(typeof self=="object"&&self)||Xr(typeof global=="object"&&global)||Xr(typeof an=="object"&&an)||function(){return this}()||Function("return this")()});var ce=b((MA,mc)=>{"use strict";var sn=typeof document=="object"&&document.all;mc.exports=typeof sn=="undefined"&&sn!==void 0?function(a){return typeof a=="function"||a===sn}:function(a){return typeof a=="function"}});var Sc=b((CA,gc)=>{"use strict";var Pg=le(),Ag=ce(),bc=Pg.WeakMap;gc.exports=Ag(bc)&&/native code/.test(String(bc))});var Fe=b((DA,vc)=>{"use strict";var wg=ce();vc.exports=function(a){return typeof a=="object"?a!==null:wg(a)}});var qe=b((BA,yc)=>{"use strict";var kg=De();yc.exports=!kg(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Aa=b((OA,Ic)=>{"use strict";var Rg=le(),Tc=Fe(),nn=Rg.document,$g=Tc(nn)&&Tc(nn.createElement);Ic.exports=function(a){return $g?nn.createElement(a):{}}});var on=b((VA,Ec)=>{"use strict";var Lg=qe(),Mg=De(),Cg=Aa();Ec.exports=!Lg&&!Mg(function(){return Object.defineProperty(Cg("div"),"a",{get:function(){return 7}}).a!==7})});var un=b((_A,xc)=>{"use strict";var Dg=qe(),Bg=De();xc.exports=Dg&&Bg(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var at=b((NA,Pc)=>{"use strict";var Og=Fe(),Vg=String,_g=TypeError;Pc.exports=function(a){if(Og(a))return a;throw new _g(Vg(a)+" is not an object")}});var Be=b((FA,Ac)=>{"use strict";var Ng=Kr(),wa=Function.prototype.call;Ac.exports=Ng?wa.bind(wa):function(){return wa.apply(wa,arguments)}});var ka=b((qA,wc)=>{"use strict";wc.exports={}});var dt=b((UA,Rc)=>{"use strict";var cn=ka(),ln=le(),Fg=ce(),kc=function(a){return Fg(a)?a:void 0};Rc.exports=function(a,e){return arguments.length<2?kc(cn[a])||kc(ln[a]):cn[a]&&cn[a][e]||ln[a]&&ln[a][e]}});var Zr=b((HA,$c)=>{"use strict";var qg=Pe();$c.exports=qg({}.isPrototypeOf)});var mr=b((jA,Cc)=>{"use strict";var Ug=le(),Lc=Ug.navigator,Mc=Lc&&Lc.userAgent;Cc.exports=Mc?String(Mc):""});var pn=b((GA,Nc)=>{"use strict";var _c=le(),dn=mr(),Dc=_c.process,Bc=_c.Deno,Oc=Dc&&Dc.versions||Bc&&Bc.version,Vc=Oc&&Oc.v8,Ke,Ra;Vc&&(Ke=Vc.split("."),Ra=Ke[0]>0&&Ke[0]<4?1:+(Ke[0]+Ke[1]));!Ra&&dn&&(Ke=dn.match(/Edge\/(\d+)/),(!Ke||Ke[1]>=74)&&(Ke=dn.match(/Chrome\/(\d+)/),Ke&&(Ra=+Ke[1])));Nc.exports=Ra});var hn=b((WA,qc)=>{"use strict";var Fc=pn(),Hg=De(),jg=le(),Gg=jg.String;qc.exports=!!Object.getOwnPropertySymbols&&!Hg(function(){var a=Symbol("symbol detection");return!Gg(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Fc&&Fc<41})});var fn=b((YA,Uc)=>{"use strict";var Wg=hn();Uc.exports=Wg&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var mn=b((QA,Hc)=>{"use strict";var Yg=dt(),Qg=ce(),zg=Zr(),Kg=fn(),Jg=Object;Hc.exports=Kg?function(a){return typeof a=="symbol"}:function(a){var e=Yg("Symbol");return Qg(e)&&zg(e.prototype,Jg(a))}});var ei=b((zA,jc)=>{"use strict";var Xg=String;jc.exports=function(a){try{return Xg(a)}catch(e){return"Object"}}});var pt=b((KA,Gc)=>{"use strict";var Zg=ce(),eS=ei(),tS=TypeError;Gc.exports=function(a){if(Zg(a))return a;throw new tS(eS(a)+" is not a function")}});var ti=b((JA,Wc)=>{"use strict";var rS=pt(),iS=hr();Wc.exports=function(a,e){var t=a[e];return iS(t)?void 0:rS(t)}});var Qc=b((XA,Yc)=>{"use strict";var bn=Be(),gn=ce(),Sn=Fe(),aS=TypeError;Yc.exports=function(a,e){var t,r;if(e==="string"&&gn(t=a.toString)&&!Sn(r=bn(t,a))||gn(t=a.valueOf)&&!Sn(r=bn(t,a))||e!=="string"&&gn(t=a.toString)&&!Sn(r=bn(t,a)))return r;throw new aS("Can't convert object to primitive value")}});var Je=b((ZA,zc)=>{"use strict";zc.exports=!0});var Xc=b((ew,Jc)=>{"use strict";var Kc=le(),sS=Object.defineProperty;Jc.exports=function(a,e){try{sS(Kc,a,{value:e,configurable:!0,writable:!0})}catch(t){Kc[a]=e}return e}});var ri=b((tw,tl)=>{"use strict";var nS=Je(),oS=le(),uS=Xc(),Zc="__core-js_shared__",el=tl.exports=oS[Zc]||uS(Zc,{});(el.versions||(el.versions=[])).push({version:"3.38.0",mode:nS?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var vn=b((rw,il)=>{"use strict";var rl=ri();il.exports=function(a,e){return rl[a]||(rl[a]=e||{})}});var ii=b((iw,al)=>{"use strict";var cS=Jr(),lS=Object;al.exports=function(a){return lS(cS(a))}});var Xe=b((aw,sl)=>{"use strict";var dS=Pe(),pS=ii(),hS=dS({}.hasOwnProperty);sl.exports=Object.hasOwn||function(e,t){return hS(pS(e),t)}});var yn=b((sw,nl)=>{"use strict";var fS=Pe(),mS=0,bS=Math.random(),gS=fS(1 .toString);nl.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+gS(++mS+bS,36)}});var ye=b((nw,ul)=>{"use strict";var SS=le(),vS=vn(),ol=Xe(),yS=yn(),TS=hn(),IS=fn(),br=SS.Symbol,Tn=vS("wks"),ES=IS?br.for||br:br&&br.withoutSetter||yS;ul.exports=function(a){return ol(Tn,a)||(Tn[a]=TS&&ol(br,a)?br[a]:ES("Symbol."+a)),Tn[a]}});var pl=b((ow,dl)=>{"use strict";var xS=Be(),cl=Fe(),ll=mn(),PS=ti(),AS=Qc(),wS=ye(),kS=TypeError,RS=wS("toPrimitive");dl.exports=function(a,e){if(!cl(a)||ll(a))return a;var t=PS(a,RS),r;if(t){if(e===void 0&&(e="default"),r=xS(t,a,e),!cl(r)||ll(r))return r;throw new kS("Can't convert object to primitive value")}return e===void 0&&(e="number"),AS(a,e)}});var In=b((uw,hl)=>{"use strict";var $S=pl(),LS=mn();hl.exports=function(a){var e=$S(a,"string");return LS(e)?e:e+""}});var Gt=b(ml=>{"use strict";var MS=qe(),CS=on(),DS=un(),$a=at(),fl=In(),BS=TypeError,En=Object.defineProperty,OS=Object.getOwnPropertyDescriptor,xn="enumerable",Pn="configurable",An="writable";ml.f=MS?DS?function(e,t,r){if($a(e),t=fl(t),$a(r),typeof e=="function"&&t==="prototype"&&"value"in r&&An in r&&!r[An]){var i=OS(e,t);i&&i[An]&&(e[t]=r.value,r={configurable:Pn in r?r[Pn]:i[Pn],enumerable:xn in r?r[xn]:i[xn],writable:!1})}return En(e,t,r)}:En:function(e,t,r){if($a(e),t=fl(t),$a(r),CS)try{return En(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new BS("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var ai=b((lw,bl)=>{"use strict";bl.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var gr=b((dw,gl)=>{"use strict";var VS=qe(),_S=Gt(),NS=ai();gl.exports=VS?function(a,e,t){return _S.f(a,e,NS(1,t))}:function(a,e,t){return a[e]=t,a}});var La=b((pw,vl)=>{"use strict";var FS=vn(),qS=yn(),Sl=FS("keys");vl.exports=function(a){return Sl[a]||(Sl[a]=qS(a))}});var Ma=b((hw,yl)=>{"use strict";yl.exports={}});var $n=b((fw,El)=>{"use strict";var US=Sc(),Il=le(),HS=Fe(),jS=gr(),wn=Xe(),kn=ri(),GS=La(),WS=Ma(),Tl="Object already initialized",Rn=Il.TypeError,YS=Il.WeakMap,Ca,si,Da,QS=function(a){return Da(a)?si(a):Ca(a,{})},zS=function(a){return function(e){var t;if(!HS(e)||(t=si(e)).type!==a)throw new Rn("Incompatible receiver, "+a+" required");return t}};US||kn.state?(Ze=kn.state||(kn.state=new YS),Ze.get=Ze.get,Ze.has=Ze.has,Ze.set=Ze.set,Ca=function(a,e){if(Ze.has(a))throw new Rn(Tl);return e.facade=a,Ze.set(a,e),e},si=function(a){return Ze.get(a)||{}},Da=function(a){return Ze.has(a)}):(Wt=GS("state"),WS[Wt]=!0,Ca=function(a,e){if(wn(a,Wt))throw new Rn(Tl);return e.facade=a,jS(a,Wt,e),e},si=function(a){return wn(a,Wt)?a[Wt]:{}},Da=function(a){return wn(a,Wt)});var Ze,Wt;El.exports={set:Ca,get:si,has:Da,enforce:QS,getterFor:zS}});var Ln=b((mw,wl)=>{"use strict";var KS=Kr(),Al=Function.prototype,xl=Al.apply,Pl=Al.call;wl.exports=typeof Reflect=="object"&&Reflect.apply||(KS?Pl.bind(xl):function(){return Pl.apply(xl,arguments)})});var Mn=b((bw,kl)=>{"use strict";var JS=pr(),XS=Pe();kl.exports=function(a){if(JS(a)==="Function")return XS(a)}});var Ml=b(Ll=>{"use strict";var Rl={}.propertyIsEnumerable,$l=Object.getOwnPropertyDescriptor,ZS=$l&&!Rl.call({1:2},1);Ll.f=ZS?function(e){var t=$l(this,e);return!!t&&t.enumerable}:Rl});var Bl=b(Dl=>{"use strict";var ev=qe(),tv=Be(),rv=Ml(),iv=ai(),av=fr(),sv=In(),nv=Xe(),ov=on(),Cl=Object.getOwnPropertyDescriptor;Dl.f=ev?Cl:function(e,t){if(e=av(e),t=sv(t),ov)try{return Cl(e,t)}catch(r){}if(nv(e,t))return iv(!tv(rv.f,e,t),e[t])}});var Cn=b((vw,Ol)=>{"use strict";var uv=De(),cv=ce(),lv=/#|\.prototype\./,ni=function(a,e){var t=pv[dv(a)];return t===fv?!0:t===hv?!1:cv(e)?uv(e):!!e},dv=ni.normalize=function(a){return String(a).replace(lv,".").toLowerCase()},pv=ni.data={},hv=ni.NATIVE="N",fv=ni.POLYFILL="P";Ol.exports=ni});var oi=b((yw,_l)=>{"use strict";var Vl=Mn(),mv=pt(),bv=Kr(),gv=Vl(Vl.bind);_l.exports=function(a,e){return mv(a),e===void 0?a:bv?gv(a,e):function(){return a.apply(e,arguments)}}});var Ue=b((Tw,Fl)=>{"use strict";var ui=le(),Sv=Ln(),vv=Mn(),yv=ce(),Tv=Bl().f,Iv=Cn(),Sr=ka(),Ev=oi(),vr=gr(),Nl=Xe();ri();var xv=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return Sv(a,this,arguments)};return e.prototype=a.prototype,e};Fl.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?ui:i?ui[t]:ui[t]&&ui[t].prototype,o=r?Sr:Sr[t]||vr(Sr,t,{})[t],u=o.prototype,c,l,d,p,h,m,g,S,T;for(p in e)c=Iv(r?p:t+(i?".":"#")+p,a.forced),l=!c&&n&&Nl(n,p),m=o[p],l&&(a.dontCallGetSet?(T=Tv(n,p),g=T&&T.value):g=n[p]),h=l&&g?g:e[p],!(!c&&!s&&typeof m==typeof h)&&(a.bind&&l?S=Ev(h,ui):a.wrap&&l?S=xv(h):s&&yv(h)?S=vv(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&vr(S,"sham",!0),vr(o,p,S),s&&(d=t+"Prototype",Nl(Sr,d)||vr(Sr,d,{}),vr(Sr[d],p,h),a.real&&u&&(c||!u[p])&&vr(u,p,h)))}});var Hl=b((Iw,Ul)=>{"use strict";var Dn=qe(),Pv=Xe(),ql=Function.prototype,Av=Dn&&Object.getOwnPropertyDescriptor,Bn=Pv(ql,"name"),wv=Bn&&function(){}.name==="something",kv=Bn&&(!Dn||Dn&&Av(ql,"name").configurable);Ul.exports={EXISTS:Bn,PROPER:wv,CONFIGURABLE:kv}});var Gl=b((Ew,jl)=>{"use strict";var Rv=Math.ceil,$v=Math.floor;jl.exports=Math.trunc||function(e){var t=+e;return(t>0?$v:Rv)(t)}});var Ba=b((xw,Wl)=>{"use strict";var Lv=Gl();Wl.exports=function(a){var e=+a;return e!==e||e===0?0:Lv(e)}});var Ql=b((Pw,Yl)=>{"use strict";var Mv=Ba(),Cv=Math.max,Dv=Math.min;Yl.exports=function(a,e){var t=Mv(a);return t<0?Cv(t+e,0):Dv(t,e)}});var Kl=b((Aw,zl)=>{"use strict";var Bv=Ba(),Ov=Math.min;zl.exports=function(a){var e=Bv(a);return e>0?Ov(e,9007199254740991):0}});var Oa=b((ww,Jl)=>{"use strict";var Vv=Kl();Jl.exports=function(a){return Vv(a.length)}});var ed=b((kw,Zl)=>{"use strict";var _v=fr(),Nv=Ql(),Fv=Oa(),Xl=function(a){return function(e,t,r){var i=_v(e),s=Fv(i);if(s===0)return!a&&-1;var n=Nv(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Zl.exports={includes:Xl(!0),indexOf:Xl(!1)}});var id=b((Rw,rd)=>{"use strict";var qv=Pe(),On=Xe(),Uv=fr(),Hv=ed().indexOf,jv=Ma(),td=qv([].push);rd.exports=function(a,e){var t=Uv(a),r=0,i=[],s;for(s in t)!On(jv,s)&&On(t,s)&&td(i,s);for(;e.length>r;)On(t,s=e[r++])&&(~Hv(i,s)||td(i,s));return i}});var Vn=b(($w,ad)=>{"use strict";ad.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var nd=b((Lw,sd)=>{"use strict";var Gv=id(),Wv=Vn();sd.exports=Object.keys||function(e){return Gv(e,Wv)}});var ud=b(od=>{"use strict";var Yv=qe(),Qv=un(),zv=Gt(),Kv=at(),Jv=fr(),Xv=nd();od.f=Yv&&!Qv?Object.defineProperties:function(e,t){Kv(e);for(var r=Jv(t),i=Xv(t),s=i.length,n=0,o;s>n;)zv.f(e,o=i[n++],r[o]);return e}});var _n=b((Cw,cd)=>{"use strict";var Zv=dt();cd.exports=Zv("document","documentElement")});var Un=b((Dw,bd)=>{"use strict";var ey=at(),ty=ud(),ld=Vn(),ry=Ma(),iy=_n(),ay=Aa(),sy=La(),dd=">",pd="<",Fn="prototype",qn="script",fd=sy("IE_PROTO"),Nn=function(){},md=function(a){return pd+qn+dd+a+pd+"/"+qn+dd},hd=function(a){a.write(md("")),a.close();var e=a.parentWindow.Object;return a=null,e},ny=function(){var a=ay("iframe"),e="java"+qn+":",t;return a.style.display="none",iy.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(md("document.F=Object")),t.close(),t.F},Va,_a=function(){try{Va=new ActiveXObject("htmlfile")}catch(e){}_a=typeof document!="undefined"?document.domain&&Va?hd(Va):ny():hd(Va);for(var a=ld.length;a--;)delete _a[Fn][ld[a]];return _a()};ry[fd]=!0;bd.exports=Object.create||function(e,t){var r;return e!==null?(Nn[Fn]=ey(e),r=new Nn,Nn[Fn]=null,r[fd]=e):r=_a(),t===void 0?r:ty.f(r,t)}});var Sd=b((Bw,gd)=>{"use strict";var oy=De();gd.exports=!oy(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var jn=b((Ow,yd)=>{"use strict";var uy=Xe(),cy=ce(),ly=ii(),dy=La(),py=Sd(),vd=dy("IE_PROTO"),Hn=Object,hy=Hn.prototype;yd.exports=py?Hn.getPrototypeOf:function(a){var e=ly(a);if(uy(e,vd))return e[vd];var t=e.constructor;return cy(t)&&e instanceof t?t.prototype:e instanceof Hn?hy:null}});var yr=b((Vw,Td)=>{"use strict";var fy=gr();Td.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:fy(a,e,t),a}});var Qn=b((_w,xd)=>{"use strict";var my=De(),by=ce(),gy=Fe(),Sy=Un(),Id=jn(),vy=yr(),yy=ye(),Ty=Je(),Yn=yy("iterator"),Ed=!1,ht,Gn,Wn;[].keys&&(Wn=[].keys(),"next"in Wn?(Gn=Id(Id(Wn)),Gn!==Object.prototype&&(ht=Gn)):Ed=!0);var Iy=!gy(ht)||my(function(){var a={};return ht[Yn].call(a)!==a});Iy?ht={}:Ty&&(ht=Sy(ht));by(ht[Yn])||vy(ht,Yn,function(){return this});xd.exports={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:Ed}});var Na=b((Nw,Ad)=>{"use strict";var Ey=ye(),xy=Ey("toStringTag"),Pd={};Pd[xy]="z";Ad.exports=String(Pd)==="[object z]"});var ci=b((Fw,wd)=>{"use strict";var Py=Na(),Ay=ce(),Fa=pr(),wy=ye(),ky=wy("toStringTag"),Ry=Object,$y=Fa(function(){return arguments}())==="Arguments",Ly=function(a,e){try{return a[e]}catch(t){}};wd.exports=Py?Fa:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=Ly(e=Ry(a),ky))=="string"?t:$y?Fa(e):(r=Fa(e))==="Object"&&Ay(e.callee)?"Arguments":r}});var Rd=b((qw,kd)=>{"use strict";var My=Na(),Cy=ci();kd.exports=My?{}.toString:function(){return"[object "+Cy(this)+"]"}});var li=b((Uw,Ld)=>{"use strict";var Dy=Na(),By=Gt().f,Oy=gr(),Vy=Xe(),_y=Rd(),Ny=ye(),$d=Ny("toStringTag");Ld.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(Vy(i,$d)||By(i,$d,{configurable:!0,value:e}),r&&!Dy&&Oy(i,"toString",_y))}});var Cd=b((Hw,Md)=>{"use strict";var Fy=Qn().IteratorPrototype,qy=Un(),Uy=ai(),Hy=li(),jy=jt(),Gy=function(){return this};Md.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=qy(Fy,{next:Uy(+!r,t)}),Hy(a,i,!1,!0),jy[i]=Gy,a}});var Bd=b((jw,Dd)=>{"use strict";var Wy=Pe(),Yy=pt();Dd.exports=function(a,e,t){try{return Wy(Yy(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Vd=b((Gw,Od)=>{"use strict";var Qy=Fe();Od.exports=function(a){return Qy(a)||a===null}});var Nd=b((Ww,_d)=>{"use strict";var zy=Vd(),Ky=String,Jy=TypeError;_d.exports=function(a){if(zy(a))return a;throw new Jy("Can't set "+Ky(a)+" as a prototype")}});var zn=b((Yw,Fd)=>{"use strict";var Xy=Bd(),Zy=Fe(),eT=Jr(),tT=Nd();Fd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Xy(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return eT(i),tT(s),Zy(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Jd=b((Qw,Kd)=>{"use strict";var rT=Ue(),iT=Be(),qa=Je(),Qd=Hl(),aT=ce(),sT=Cd(),qd=jn(),Ud=zn(),nT=li(),oT=gr(),Kn=yr(),uT=ye(),Hd=jt(),zd=Qn(),cT=Qd.PROPER,lT=Qd.CONFIGURABLE,jd=zd.IteratorPrototype,Ua=zd.BUGGY_SAFARI_ITERATORS,di=uT("iterator"),Gd="keys",pi="values",Wd="entries",Yd=function(){return this};Kd.exports=function(a,e,t,r,i,s,n){sT(t,e,r);var o=function(T){if(T===i&&p)return p;if(!Ua&&T&&T in l)return l[T];switch(T){case Gd:return function(){return new t(this,T)};case pi:return function(){return new t(this,T)};case Wd:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[di]||l["@@iterator"]||i&&l[i],p=!Ua&&d||o(i),h=e==="Array"&&l.entries||d,m,g,S;if(h&&(m=qd(h.call(new a)),m!==Object.prototype&&m.next&&(!qa&&qd(m)!==jd&&(Ud?Ud(m,jd):aT(m[di])||Kn(m,di,Yd)),nT(m,u,!0,!0),qa&&(Hd[u]=Yd))),cT&&i===pi&&d&&d.name!==pi&&(!qa&&lT?oT(l,"name",pi):(c=!0,p=function(){return iT(d,this)})),i)if(g={values:o(pi),keys:s?p:o(Gd),entries:o(Wd)},n)for(S in g)(Ua||c||!(S in l))&&Kn(l,S,g[S]);else rT({target:e,proto:!0,forced:Ua||c},g);return(!qa||n)&&l[di]!==p&&Kn(l,di,p,{name:i}),Hd[e]=p,g}});var Zd=b((zw,Xd)=>{"use strict";Xd.exports=function(a,e){return{value:a,done:e}}});var Xn=b((Kw,ap)=>{"use strict";var dT=fr(),Jn=rn(),ep=jt(),rp=$n(),pT=Gt().f,hT=Jd(),Ha=Zd(),fT=Je(),mT=qe(),ip="Array Iterator",bT=rp.set,gT=rp.getterFor(ip);ap.exports=hT(Array,"Array",function(a,e){bT(this,{type:ip,target:dT(a),index:0,kind:e})},function(){var a=gT(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ha(void 0,!0);switch(a.kind){case"keys":return Ha(t,!1);case"values":return Ha(e[t],!1)}return Ha([t,e[t]],!1)},"values");var tp=ep.Arguments=ep.Array;Jn("keys");Jn("values");Jn("entries");if(!fT&&mT&&tp.name!=="values")try{pT(tp,"name",{value:"values"})}catch(a){}});var np=b((Jw,sp)=>{"use strict";var ST=ye(),vT=jt(),yT=ST("iterator"),TT=Array.prototype;sp.exports=function(a){return a!==void 0&&(vT.Array===a||TT[yT]===a)}});var Zn=b((Xw,up)=>{"use strict";var IT=ci(),op=ti(),ET=hr(),xT=jt(),PT=ye(),AT=PT("iterator");up.exports=function(a){if(!ET(a))return op(a,AT)||op(a,"@@iterator")||xT[IT(a)]}});var lp=b((Zw,cp)=>{"use strict";var wT=Be(),kT=pt(),RT=at(),$T=ei(),LT=Zn(),MT=TypeError;cp.exports=function(a,e){var t=arguments.length<2?LT(a):e;if(kT(t))return RT(wT(t,a));throw new MT($T(a)+" is not iterable")}});var hp=b((ek,pp)=>{"use strict";var CT=Be(),dp=at(),DT=ti();pp.exports=function(a,e,t){var r,i;dp(a);try{if(r=DT(a,"return"),!r){if(e==="throw")throw t;return t}r=CT(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return dp(r),t}});var Ga=b((tk,gp)=>{"use strict";var BT=oi(),OT=Be(),VT=at(),_T=ei(),NT=np(),FT=Oa(),fp=Zr(),qT=lp(),UT=Zn(),mp=hp(),HT=TypeError,ja=function(a,e){this.stopped=a,this.result=e},bp=ja.prototype;gp.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=BT(e,r),c,l,d,p,h,m,g,S=function(P){return c&&mp(c,"normal",P),new ja(!0,P)},T=function(P){return i?(VT(P),o?u(P[0],P[1],S):u(P[0],P[1])):o?u(P,S):u(P)};if(s)c=a.iterator;else if(n)c=a;else{if(l=UT(a),!l)throw new HT(_T(a)+" is not iterable");if(NT(l)){for(d=0,p=FT(a);p>d;d++)if(h=T(a[d]),h&&fp(bp,h))return h;return new ja(!1)}c=qT(a,l)}for(m=s?a.next:c.next;!(g=OT(m,c)).done;){try{h=T(g.value)}catch(P){mp(c,"throw",P)}if(typeof h=="object"&&h&&fp(bp,h))return h}return new ja(!1)}});var vp=b((rk,Sp)=>{"use strict";var jT=qe(),GT=Gt(),WT=ai();Sp.exports=function(a,e,t){jT?GT.f(a,e,WT(0,t)):a[e]=t}});var yp=b(()=>{"use strict";var YT=Ue(),QT=Ga(),zT=vp();YT({target:"Object",stat:!0},{fromEntries:function(e){var t={};return QT(e,function(r,i){zT(t,r,i)},{AS_ENTRIES:!0}),t}})});var Ip=b((sk,Tp)=>{"use strict";Xn();yp();var KT=ka();Tp.exports=KT.Object.fromEntries});var xp=b((nk,Ep)=>{"use strict";Ep.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 Ap=b(()=>{"use strict";Xn();var JT=xp(),XT=le(),ZT=li(),Pp=jt();for(Wa in JT)ZT(XT[Wa],Wa),Pp[Wa]=Pp.Array;var Wa});var kp=b((ck,wp)=>{"use strict";var eI=Ip();Ap();wp.exports=eI});var eo=b((lk,Rp)=>{"use strict";var tI=kp();Rp.exports=tI});var $p=b(()=>{"use strict"});var to=b((hk,Lp)=>{"use strict";var hi=le(),rI=mr(),iI=pr(),Ya=function(a){return rI.slice(0,a.length)===a};Lp.exports=function(){return Ya("Bun/")?"BUN":Ya("Cloudflare-Workers")?"CLOUDFLARE":Ya("Deno/")?"DENO":Ya("Node.js/")?"NODE":hi.Bun&&typeof Bun.version=="string"?"BUN":hi.Deno&&typeof Deno.version=="object"?"DENO":iI(hi.process)==="process"?"NODE":hi.window&&hi.document?"BROWSER":"REST"}()});var Qa=b((fk,Mp)=>{"use strict";var aI=to();Mp.exports=aI==="NODE"});var Dp=b((mk,Cp)=>{"use strict";var sI=Gt();Cp.exports=function(a,e,t){return sI.f(a,e,t)}});var Vp=b((bk,Op)=>{"use strict";var nI=dt(),oI=Dp(),uI=ye(),cI=qe(),Bp=uI("species");Op.exports=function(a){var e=nI(a);cI&&e&&!e[Bp]&&oI(e,Bp,{configurable:!0,get:function(){return this}})}});var Np=b((gk,_p)=>{"use strict";var lI=Zr(),dI=TypeError;_p.exports=function(a,e){if(lI(e,a))return a;throw new dI("Incorrect invocation")}});var io=b((Sk,Fp)=>{"use strict";var pI=Pe(),hI=ce(),ro=ri(),fI=pI(Function.toString);hI(ro.inspectSource)||(ro.inspectSource=function(a){return fI(a)});Fp.exports=ro.inspectSource});var Wp=b((vk,Gp)=>{"use strict";var mI=Pe(),bI=De(),qp=ce(),gI=ci(),SI=dt(),vI=io(),Up=function(){},Hp=SI("Reflect","construct"),ao=/^\s*(?:class|function)\b/,yI=mI(ao.exec),TI=!ao.test(Up),fi=function(e){if(!qp(e))return!1;try{return Hp(Up,[],e),!0}catch(t){return!1}},jp=function(e){if(!qp(e))return!1;switch(gI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return TI||!!yI(ao,vI(e))}catch(t){return!0}};jp.sham=!0;Gp.exports=!Hp||bI(function(){var a;return fi(fi.call)||!fi(Object)||!fi(function(){a=!0})||a})?jp:fi});var Qp=b((yk,Yp)=>{"use strict";var II=Wp(),EI=ei(),xI=TypeError;Yp.exports=function(a){if(II(a))return a;throw new xI(EI(a)+" is not a constructor")}});var so=b((Tk,Kp)=>{"use strict";var zp=at(),PI=Qp(),AI=hr(),wI=ye(),kI=wI("species");Kp.exports=function(a,e){var t=zp(a).constructor,r;return t===void 0||AI(r=zp(t)[kI])?e:PI(r)}});var Xp=b((Ik,Jp)=>{"use strict";var RI=Pe();Jp.exports=RI([].slice)});var eh=b((Ek,Zp)=>{"use strict";var $I=TypeError;Zp.exports=function(a,e){if(a<e)throw new $I("Not enough arguments");return a}});var no=b((xk,th)=>{"use strict";var LI=mr();th.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(LI)});var bo=b((Pk,lh)=>{"use strict";var Oe=le(),MI=Ln(),CI=oi(),rh=ce(),DI=Xe(),ch=De(),ih=_n(),BI=Xp(),ah=Aa(),OI=eh(),VI=no(),_I=Qa(),ho=Oe.setImmediate,fo=Oe.clearImmediate,NI=Oe.process,oo=Oe.Dispatch,FI=Oe.Function,sh=Oe.MessageChannel,qI=Oe.String,uo=0,mi={},nh="onreadystatechange",bi,Yt,co,lo;ch(function(){bi=Oe.location});var mo=function(a){if(DI(mi,a)){var e=mi[a];delete mi[a],e()}},po=function(a){return function(){mo(a)}},oh=function(a){mo(a.data)},uh=function(a){Oe.postMessage(qI(a),bi.protocol+"//"+bi.host)};(!ho||!fo)&&(ho=function(e){OI(arguments.length,1);var t=rh(e)?e:FI(e),r=BI(arguments,1);return mi[++uo]=function(){MI(t,void 0,r)},Yt(uo),uo},fo=function(e){delete mi[e]},_I?Yt=function(a){NI.nextTick(po(a))}:oo&&oo.now?Yt=function(a){oo.now(po(a))}:sh&&!VI?(co=new sh,lo=co.port2,co.port1.onmessage=oh,Yt=CI(lo.postMessage,lo)):Oe.addEventListener&&rh(Oe.postMessage)&&!Oe.importScripts&&bi&&bi.protocol!=="file:"&&!ch(uh)?(Yt=uh,Oe.addEventListener("message",oh,!1)):nh in ah("script")?Yt=function(a){ih.appendChild(ah("script"))[nh]=function(){ih.removeChild(this),mo(a)}}:Yt=function(a){setTimeout(po(a),0)});lh.exports={set:ho,clear:fo}});var hh=b((Ak,ph)=>{"use strict";var dh=le(),UI=qe(),HI=Object.getOwnPropertyDescriptor;ph.exports=function(a){if(!UI)return dh[a];var e=HI(dh,a);return e&&e.value}});var go=b((wk,mh)=>{"use strict";var fh=function(){this.head=null,this.tail=null};fh.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}}};mh.exports=fh});var gh=b((kk,bh)=>{"use strict";var jI=mr();bh.exports=/ipad|iphone|ipod/i.test(jI)&&typeof Pebble!="undefined"});var vh=b((Rk,Sh)=>{"use strict";var GI=mr();Sh.exports=/web0s(?!.*chrome)/i.test(GI)});var Ah=b(($k,Ph)=>{"use strict";var Ir=le(),WI=hh(),yh=oi(),So=bo().set,YI=go(),QI=no(),zI=gh(),KI=vh(),vo=Qa(),Th=Ir.MutationObserver||Ir.WebKitMutationObserver,Ih=Ir.document,Eh=Ir.process,za=Ir.Promise,Io=WI("queueMicrotask"),Tr,yo,To,Ka,xh;Io||(gi=new YI,Si=function(){var a,e;for(vo&&(a=Eh.domain)&&a.exit();e=gi.get();)try{e()}catch(t){throw gi.head&&Tr(),t}a&&a.enter()},!QI&&!vo&&!KI&&Th&&Ih?(yo=!0,To=Ih.createTextNode(""),new Th(Si).observe(To,{characterData:!0}),Tr=function(){To.data=yo=!yo}):!zI&&za&&za.resolve?(Ka=za.resolve(void 0),Ka.constructor=za,xh=yh(Ka.then,Ka),Tr=function(){xh(Si)}):vo?Tr=function(){Eh.nextTick(Si)}:(So=yh(So,Ir),Tr=function(){So(Si)}),Io=function(a){gi.head||Tr(),gi.add(a)});var gi,Si;Ph.exports=Io});var kh=b((Lk,wh)=>{"use strict";wh.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ja=b((Mk,Rh)=>{"use strict";Rh.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Qt=b((Ck,$h)=>{"use strict";var JI=le();$h.exports=JI.Promise});var Er=b((Dk,Dh)=>{"use strict";var XI=le(),vi=Qt(),ZI=ce(),eE=Cn(),tE=io(),rE=ye(),Lh=to(),iE=Je(),Eo=pn(),Mh=vi&&vi.prototype,aE=rE("species"),xo=!1,Ch=ZI(XI.PromiseRejectionEvent),sE=eE("Promise",function(){var a=tE(vi),e=a!==String(vi);if(!e&&Eo===66||iE&&!(Mh.catch&&Mh.finally))return!0;if(!Eo||Eo<51||!/native code/.test(a)){var t=new vi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[aE]=r,xo=t.then(function(){})instanceof r,!xo)return!0}return!e&&(Lh==="BROWSER"||Lh==="DENO")&&!Ch});Dh.exports={CONSTRUCTOR:sE,REJECTION_EVENT:Ch,SUBCLASSING:xo}});var xr=b((Bk,Oh)=>{"use strict";var Bh=pt(),nE=TypeError,oE=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new nE("Bad Promise constructor");e=r,t=i}),this.resolve=Bh(e),this.reject=Bh(t)};Oh.exports.f=function(a){return new oE(a)}});var tf=b(()=>{"use strict";var uE=Ue(),cE=Je(),ts=Qa(),Lt=le(),kr=Be(),Vh=yr(),_h=zn(),lE=li(),dE=Vp(),pE=pt(),es=ce(),hE=Fe(),fE=Np(),mE=so(),Hh=bo().set,Ro=Ah(),bE=kh(),gE=Ja(),SE=go(),jh=$n(),rs=Qt(),$o=Er(),Gh=xr(),is="Promise",Wh=$o.CONSTRUCTOR,vE=$o.REJECTION_EVENT,yE=$o.SUBCLASSING,Po=jh.getterFor(is),TE=jh.set,Pr=rs&&rs.prototype,zt=rs,Xa=Pr,Yh=Lt.TypeError,Ao=Lt.document,Lo=Lt.process,wo=Gh.f,IE=wo,EE=!!(Ao&&Ao.createEvent&&Lt.dispatchEvent),Qh="unhandledrejection",xE="rejectionhandled",Nh=0,zh=1,PE=2,Mo=1,Kh=2,Za,Fh,AE,qh,Jh=function(a){var e;return hE(a)&&es(e=a.then)?e:!1},Xh=function(a,e){var t=e.value,r=e.state===zh,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{i?(r||(e.rejection===Kh&&kE(e),e.rejection=Mo),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),l=!0)),u===a.promise?n(new Yh("Promise-chain cycle")):(c=Jh(u))?kr(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},Zh=function(a,e){a.notified||(a.notified=!0,Ro(function(){for(var t=a.reactions,r;r=t.get();)Xh(r,a);a.notified=!1,e&&!a.rejection&&wE(a)}))},ef=function(a,e,t){var r,i;EE?(r=Ao.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Lt.dispatchEvent(r)):r={promise:e,reason:t},!vE&&(i=Lt["on"+a])?i(r):a===Qh&&bE("Unhandled promise rejection",t)},wE=function(a){kr(Hh,Lt,function(){var e=a.facade,t=a.value,r=Uh(a),i;if(r&&(i=gE(function(){ts?Lo.emit("unhandledRejection",t,e):ef(Qh,e,t)}),a.rejection=ts||Uh(a)?Kh:Mo,i.error))throw i.value})},Uh=function(a){return a.rejection!==Mo&&!a.parent},kE=function(a){kr(Hh,Lt,function(){var e=a.facade;ts?Lo.emit("rejectionHandled",e):ef(xE,e,a.value)})},Ar=function(a,e,t){return function(r){a(e,r,t)}},wr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=PE,Zh(a,!0))},ko=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Yh("Promise can't be resolved itself");var r=Jh(e);r?Ro(function(){var i={done:!1};try{kr(r,e,Ar(ko,i,a),Ar(wr,i,a))}catch(s){wr(i,s,a)}}):(a.value=e,a.state=zh,Zh(a,!1))}catch(i){wr({done:!1},i,a)}}};if(Wh&&(zt=function(e){fE(this,Xa),pE(e),kr(Za,this);var t=Po(this);try{e(Ar(ko,t),Ar(wr,t))}catch(r){wr(t,r)}},Xa=zt.prototype,Za=function(e){TE(this,{type:is,done:!1,notified:!1,parent:!1,reactions:new SE,rejection:!1,state:Nh,value:void 0})},Za.prototype=Vh(Xa,"then",function(e,t){var r=Po(this),i=wo(mE(this,zt));return r.parent=!0,i.ok=es(e)?e:!0,i.fail=es(t)&&t,i.domain=ts?Lo.domain:void 0,r.state===Nh?r.reactions.add(i):Ro(function(){Xh(i,r)}),i.promise}),Fh=function(){var a=new Za,e=Po(a);this.promise=a,this.resolve=Ar(ko,e),this.reject=Ar(wr,e)},Gh.f=wo=function(a){return a===zt||a===AE?new Fh(a):IE(a)},!cE&&es(rs)&&Pr!==Object.prototype)){qh=Pr.then,yE||Vh(Pr,"then",function(e,t){var r=this;return new zt(function(i,s){kr(qh,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Pr.constructor}catch(a){}_h&&_h(Pr,Xa)}uE({global:!0,constructor:!0,wrap:!0,forced:Wh},{Promise:zt});lE(zt,is,!1,!0);dE(is)});var of=b((_k,nf)=>{"use strict";var RE=ye(),af=RE("iterator"),sf=!1;try{rf=0,Co={next:function(){return{done:!!rf++}},return:function(){sf=!0}},Co[af]=function(){return this},Array.from(Co,function(){throw 2})}catch(a){}var rf,Co;nf.exports=function(a,e){try{if(!e&&!sf)return!1}catch(i){return!1}var t=!1;try{var r={};r[af]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Do=b((Nk,uf)=>{"use strict";var $E=Qt(),LE=of(),ME=Er().CONSTRUCTOR;uf.exports=ME||!LE(function(a){$E.all(a).then(void 0,function(){})})});var cf=b(()=>{"use strict";var CE=Ue(),DE=Be(),BE=pt(),OE=xr(),VE=Ja(),_E=Ga(),NE=Do();CE({target:"Promise",stat:!0,forced:NE},{all:function(e){var t=this,r=OE.f(t),i=r.resolve,s=r.reject,n=VE(function(){var o=BE(t.resolve),u=[],c=0,l=1;_E(e,function(d){var p=c++,h=!1;l++,DE(o,t,d).then(function(m){h||(h=!0,u[p]=m,--l||i(u))},s)}),--l||i(u)});return n.error&&s(n.value),r.promise}})});var df=b(()=>{"use strict";var FE=Ue(),qE=Je(),UE=Er().CONSTRUCTOR,Oo=Qt(),HE=dt(),jE=ce(),GE=yr(),lf=Oo&&Oo.prototype;FE({target:"Promise",proto:!0,forced:UE,real:!0},{catch:function(a){return this.then(void 0,a)}});!qE&&jE(Oo)&&(Bo=HE("Promise").prototype.catch,lf.catch!==Bo&&GE(lf,"catch",Bo,{unsafe:!0}));var Bo});var pf=b(()=>{"use strict";var WE=Ue(),YE=Be(),QE=pt(),zE=xr(),KE=Ja(),JE=Ga(),XE=Do();WE({target:"Promise",stat:!0,forced:XE},{race:function(e){var t=this,r=zE.f(t),i=r.reject,s=KE(function(){var n=QE(t.resolve);JE(e,function(o){YE(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var hf=b(()=>{"use strict";var ZE=Ue(),ex=xr(),tx=Er().CONSTRUCTOR;ZE({target:"Promise",stat:!0,forced:tx},{reject:function(e){var t=ex.f(this),r=t.reject;return r(e),t.promise}})});var Vo=b((Qk,ff)=>{"use strict";var rx=at(),ix=Fe(),ax=xr();ff.exports=function(a,e){if(rx(a),ix(e)&&e.constructor===a)return e;var t=ax.f(a),r=t.resolve;return r(e),t.promise}});var gf=b(()=>{"use strict";var sx=Ue(),nx=dt(),mf=Je(),ox=Qt(),bf=Er().CONSTRUCTOR,ux=Vo(),cx=nx("Promise"),lx=mf&&!bf;sx({target:"Promise",stat:!0,forced:mf||bf},{resolve:function(e){return ux(lx&&this===cx?ox:this,e)}})});var Sf=b(()=>{"use strict";tf();cf();df();pf();hf();gf()});var If=b(()=>{"use strict";var dx=Ue(),px=Je(),as=Qt(),hx=De(),yf=dt(),Tf=ce(),fx=so(),vf=Vo(),mx=yr(),No=as&&as.prototype,bx=!!as&&hx(function(){No.finally.call({then:function(){}},function(){})});dx({target:"Promise",proto:!0,real:!0,forced:bx},{finally:function(a){var e=fx(this,yf("Promise")),t=Tf(a);return this.then(t?function(r){return vf(e,a()).then(function(){return r})}:a,t?function(r){return vf(e,a()).then(function(){throw r})}:a)}});!px&&Tf(as)&&(_o=yf("Promise").prototype.finally,No.finally!==_o&&mx(No,"finally",_o,{unsafe:!0}));var _o});var ss=b((tR,Ef)=>{"use strict";var gx=dt();Ef.exports=gx});var Pf=b((rR,xf)=>{"use strict";$p();Sf();If();var Sx=ss();xf.exports=Sx("Promise","finally")});var wf=b((iR,Af)=>{"use strict";var vx=Pf();Af.exports=vx});var ns=b((aR,kf)=>{"use strict";var yx=wf();kf.exports=yx});var _f=b(()=>{"use strict";var kx=Ue(),Rx=ii(),$x=Oa(),Lx=Ba(),Mx=rn();kx({target:"Array",proto:!0},{at:function(e){var t=Rx(this),r=$x(t),i=Lx(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});Mx("at")});var Ff=b((r$,Nf)=>{"use strict";_f();var Cx=ss();Nf.exports=Cx("Array","at")});var Uf=b((i$,qf)=>{"use strict";var Dx=Ff();qf.exports=Dx});var Ti=b((a$,Hf)=>{"use strict";var Bx=Uf();Hf.exports=Bx});var Dm=b(()=>{"use strict"});var Bm=b(()=>{"use strict"});var Vm=b((ZC,Om)=>{"use strict";var mP=Fe(),bP=pr(),gP=ye(),SP=gP("match");Om.exports=function(a){var e;return mP(a)&&((e=a[SP])!==void 0?!!e:bP(a)==="RegExp")}});var Nm=b((eD,_m)=>{"use strict";var vP=ci(),yP=String;_m.exports=function(a){if(vP(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return yP(a)}});var qm=b((tD,Fm)=>{"use strict";var TP=at();Fm.exports=function(){var a=TP(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 jm=b((rD,Hm)=>{"use strict";var IP=Be(),EP=Xe(),xP=Zr(),PP=qm(),Um=RegExp.prototype;Hm.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Um)&&!EP(a,"flags")&&xP(Um,a)?IP(PP,a):e}});var Wm=b((iD,Gm)=>{"use strict";var uu=Pe(),AP=ii(),wP=Math.floor,nu=uu("".charAt),kP=uu("".replace),ou=uu("".slice),RP=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,$P=/\$([$&'`]|\d{1,2})/g;Gm.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=$P;return i!==void 0&&(i=AP(i),u=RP),kP(s,u,function(c,l){var d;switch(nu(l,0)){case"$":return"$";case"&":return a;case"`":return ou(e,0,t);case"'":return ou(e,n);case"<":d=i[ou(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=wP(p/10);return h===0?c:h<=o?r[h-1]===void 0?nu(l,1):r[h-1]+nu(l,1):c}d=r[p-1]}return d===void 0?"":d})}});var zm=b(()=>{"use strict";var LP=Ue(),MP=Be(),lu=Pe(),Ym=Jr(),CP=ce(),DP=hr(),BP=Vm(),_r=Nm(),OP=ti(),VP=jm(),_P=Wm(),NP=ye(),FP=Je(),qP=NP("replace"),UP=TypeError,cu=lu("".indexOf),HP=lu("".replace),Qm=lu("".slice),jP=Math.max;LP({target:"String",proto:!0},{replaceAll:function(e,t){var r=Ym(this),i,s,n,o,u,c,l,d,p,h,m=0,g="";if(!DP(e)){if(i=BP(e),i&&(s=_r(Ym(VP(e))),!~cu(s,"g")))throw new UP("`.replaceAll` does not allow non-global regexes");if(n=OP(e,qP),n)return MP(n,e,r,t);if(FP&&i)return HP(_r(r),e,t)}for(o=_r(r),u=_r(e),c=CP(t),c||(t=_r(t)),l=u.length,d=jP(1,l),p=cu(o,u);p!==-1;)h=c?_r(t(u,p,o)):_P(u,o,p,[],void 0,t),g+=Qm(o,m,p)+h,m=p+l,p=p+d>o.length?-1:cu(o,u,p+d);return m<o.length&&(g+=Qm(o,m)),g}})});var Jm=b((nD,Km)=>{"use strict";Dm();Bm();zm();var GP=ss();Km.exports=GP("String","replaceAll")});var Zm=b((oD,Xm)=>{"use strict";var WP=Jm();Xm.exports=WP});var tb=b((uD,eb)=>{"use strict";var YP=Zm();eb.exports=YP});var uA={};lg(uA,{ChromecastState:()=>zr,HttpConnectionType:()=>Ea,Observable:()=>ct.Observable,PlaybackState:()=>ve,Player:()=>ba,SDK_VERSION:()=>oA,Subject:()=>ct.Subject,Subscription:()=>ct.Subscription,Surface:()=>xa,VERSION:()=>Zs,ValueSubject:()=>ct.ValueSubject,VideoFormat:()=>lt,VideoQuality:()=>ct.VideoQuality});module.exports=dg(uA);var Zs="2.0.111-dev.974e99b3.0";var ve=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ve||{}),lt=(I=>(I.MPEG="MPEG",I.DASH="DASH",I.DASH_SEP="DASH_SEP",I.DASH_SEP_VK="DASH_SEP",I.DASH_WEBM="DASH_WEBM",I.DASH_WEBM_AV1="DASH_WEBM_AV1",I.DASH_STREAMS="DASH_STREAMS",I.DASH_WEBM_VK="DASH_WEBM",I.DASH_ONDEMAND="DASH_ONDEMAND",I.DASH_ONDEMAND_VK="DASH_ONDEMAND",I.DASH_LIVE="DASH_LIVE",I.DASH_LIVE_CMAF="DASH_LIVE_CMAF",I.DASH_LIVE_WEBM="DASH_LIVE_WEBM",I.HLS="HLS",I.HLS_ONDEMAND="HLS_ONDEMAND",I.HLS_JS="HLS",I.HLS_LIVE="HLS_LIVE",I.HLS_LIVE_CMAF="HLS_LIVE_CMAF",I.WEB_RTC_LIVE="WEB_RTC_LIVE",I))(lt||{});var zr=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(zr||{}),Ea=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Ea||{});var xa=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(xa||{});var q=require("@vkontakte/videoplayer-shared");var Zu=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Pa=class{constructor(e){this.connection$=new q.ValueSubject(void 0);this.castState$=new q.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new q.Subject;this.realCastState$=new q.ValueSubject("NOT_AVAILABLE");this.subscription=new q.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 r=(0,q.isNonNullable)((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Zu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:q.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 r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,q.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,q.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,q.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),r=cast.framework.CastContext.getInstance();this.subscription.add((0,q.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,q.assertNever)(i.sessionState)}})).add((0,q.merge)((0,q.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,q.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,q.map)(i=>i.castState)),(0,q.observableFrom)([r.getCastState()])).pipe((0,q.filterChanged)(),(0,q.map)(pg),(0,q.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=(0,q.isNonNullable)(this.connection$.getValue());if(s&&!n){let c=r.getCurrentSession();(0,q.assertNonNullable)(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,q.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(i==="CONNECTED"?(0,q.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:q.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},pg=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,q.assertNever)(a)}};var xb=ze(eo(),1);var Mf=ze(ns(),1);var Fo=require("@vkontakte/videoplayer-shared");var Se=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:(0,Fo.assertNever)(t)}return a},qo=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:(0,Fo.assertNever)(e)}};var w=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var st=require("@vkontakte/videoplayer-shared"),j=class{constructor(e){this.transitionStarted$=new st.Subject;this.transitionEnded$=new st.Subject;this.transitionUpdated$=new st.Subject;this.forceChanged$=new st.Subject;this.stateChangeStarted$=(0,st.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,st.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||(0,st.isNonNullable)(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Rf=require("@vkontakte/videoplayer-shared"),$f=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,Rf.assertNever)(a)}};var $=require("@vkontakte/videoplayer-shared");var Tx=5,Ix=5,Ex=500,Lf=7e3,yi=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(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(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)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next($f(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)(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe((0,$.map)(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new $.Subject;e.add(i.pipe((0,$.debounce)(Ex)).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)>Tx)&&i.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),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Ix&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=(0,$.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,$.observableFrom)(["init"])).pipe((0,$.debounce)(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),w(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"),w(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"&&w(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var c;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let l=t[e];(0,$.assertNonNullable)(l);let d=(0,$.getHighestQuality)(Object.keys(l));(0,$.assertNonNullable)(d);let p=l[d];(0,$.assertNonNullable)(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];(0,$.assertNonNullable)(l),r=l.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];(0,$.assertNonNullable)(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,$.assertNonNullable)(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,$.assertNonNullable)(l),r=Se(l.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:$.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:r,i);n.contentUrl=r,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 r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add((0,$.timeout)(Lf).subscribe(()=>s(`timeout(${Lf})`)))});(0,Mf.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:$.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Go=require("@vkontakte/videoplayer-shared");var Cf=require("@vkontakte/videoplayer-shared"),Df=a=>{try{a.pause(),a.playbackRate=0,(0,Cf.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var os=require("@vkontakte/videoplayer-shared"),Uo=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)}},Ho=window.WeakMap?new WeakMap:new Uo,jo=window.WeakMap?new WeakMap:new Map,xx=(a,e=20)=>{let t=0;return(0,os.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ae=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?(0,Go.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),Ho.set(t,r);let i=new os.Subscription;return i.add(xx(t,e)),jo.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},we=a=>{let e=jo.get(a);e==null||e.unsubscribe(),jo.delete(a);let t=Ho.get(a);Ho.delete(a),t?(0,Go.clearVideoElement)(a):Df(a)};var L=require("@vkontakte/videoplayer-shared");var Mt=require("@vkontakte/videoplayer-shared"),us=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Mt.isNullable)(i),c=new Mt.Subscription;return i&&c.add(i.subscribe(l=>{let d=a.getState();r(l,d)&&a.setState(l)},s)),r(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(l=>{t(l.to),u&&a.setState(l.to)},s)),c},nt=(a,e,t)=>us(e,()=>a.loop,r=>{(0,Mt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),ke=(a,e,t,r)=>us(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,Mt.isNonNullable)(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),He=(a,e,t,r)=>us(e,()=>a.playbackRate,i=>{(0,Mt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Ct=us;var Px=a=>["__",a.language,a.label].join("|"),Ax=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Wo=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,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:L.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ct(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:i})),this.subscription.add(Ct(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:i})),this.subscription.add(Ct(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Ct(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 r=this.current$.getValue();r&&this.select(r)})),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(r=>this.htmlTextTrackToITextTrack(r))),(0,L.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[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:r})=>r==="showing")),(0,L.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,L.filterChanged)()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var c,l,d,p,h;let u=(l=(c=o.target)==null?void 0:c.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,L.fromEvent)(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;(0,L.isNonNullable)(t.align)&&(i.align=t.align),(0,L.isNonNullable)(t.position)&&(i.position=t.position),(0,L.isNonNullable)(t.size)&&(i.size=t.size),(0,L.isNonNullable)(t.line)&&(i.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;let{language:t,label:r}=e,i=e.id?e.id:Px(e),s=this.externalTracks.has(i),n=i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(i))==null?void 0:o.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(i))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(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)||!Ax(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"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},je=Wo;var mt=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 Bf=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},Yo=a=>{let e=Bf(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Of=a=>{let e=Bf(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var D=require("@vkontakte/videoplayer-shared");var wx=3,Vf=(a,e,t=wx)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Re=a=>{let e=I=>(0,D.fromEvent)(a,I).pipe((0,D.mapTo)(void 0)),r=(0,D.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>(0,D.fromEvent)(a,I))).pipe((0,D.map)(I=>I.type==="ended"?a.readyState<2:a.readyState<3),(0,D.filterChanged)()),i=(0,D.merge)((0,D.fromEvent)(a,"progress"),(0,D.fromEvent)(a,"timeupdate")).pipe((0,D.map)(()=>Vf(a.buffered,a.currentTime))),s=D.clientChecker.isSafari?(0,D.combine)({play:e("play").pipe((0,D.once)()),playing:e("playing")}).pipe((0,D.mapTo)(void 0)):e("playing"),n=(0,D.fromEvent)(a,"volumechange").pipe((0,D.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,D.fromEvent)(a,"ratechange").pipe((0,D.map)(()=>a.playbackRate)),u=(0,D.fromEvent)(a,"error").pipe((0,D.filter)(()=>!!(a.error||a.played.length)),(0,D.map)(()=>{var E;let I=a.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:D.ErrorCategory.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),c=(0,D.fromEvent)(a,"timeupdate").pipe((0,D.map)(()=>a.currentTime)),l=new D.Subject,d=.3,p;c.subscribe(I=>{a.loop&&(0,D.isNonNullable)(p)&&(0,D.isNonNullable)(I)&&p>=a.duration-d&&I<=d&&l.next(p),p=I});let h=e("pause").pipe((0,D.filter)(()=>!a.error&&p!==a.duration)),m=(0,D.fromEvent)(a,"enterpictureinpicture"),g=(0,D.fromEvent)(a,"leavepictureinpicture"),S=new D.ValueSubject(Of(a));m.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let T=new D.ValueSubject(Yo(a));return(0,D.fromEvent)(a,"fullscreenchange").pipe((0,D.map)(()=>Yo(a))).subscribe(T),{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,D.fromEvent)(a,"durationchange").pipe((0,D.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:T}};var bt=require("@vkontakte/videoplayer-shared"),Dt=a=>{switch(a){case"mobile":return bt.VideoQuality.Q_144P;case"lowest":return bt.VideoQuality.Q_240P;case"low":return bt.VideoQuality.Q_360P;case"sd":case"medium":return bt.VideoQuality.Q_480P;case"hd":case"high":return bt.VideoQuality.Q_720P;case"fullhd":case"full":return bt.VideoQuality.Q_1080P;case"quadhd":case"quad":return bt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return bt.VideoQuality.Q_2160P}};var Kt=ze(Ti(),1),B=require("@vkontakte/videoplayer-shared");var Qo=!1,gt={},jf=a=>{Qo=a},Gf=()=>{gt={}},Wf=a=>{a(gt)},Ii=(a,e)=>{var t;Qo&&(gt.meta=(t=gt.meta)!=null?t:{},gt.meta[a]=e)},Te=class{constructor(e){this.name=e}next(e){var r,i;if(!Qo)return;gt.series=(r=gt.series)!=null?r:{};let t=(i=gt.series[this.name])!=null?i:[];t.push([Date.now(),e]),gt.series[this.name]=t}};var Ox=new Te("best_bitrate"),Qf=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var zo=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ei=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,B.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},zf='Assertion "ABR Tracks is empty array" failed',cs=(a,e,t,r)=>{var u;let i=[...e].sort(zo(1)),s=[...t].sort(zo(1)),n=s.filter(c=>(0,B.isNonNullable)(c.bitrate)&&(0,B.isNonNullable)(a.bitrate)?a.bitrate/c.bitrate>r:!0),o=(u=(0,Kt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Kt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Kt.default)(n,-1):(0,Kt.default)(s,0)},Yf=a=>"quality"in a,Kf=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&(0,B.now)()-r.history[t.id]<=a.trackCooldown&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!i&&r.recordSelection(t),i&&(r!=null&&r.last)){let s=r.last;r==null||r.recordSwitch(s);let n=Yf(s)?"video":"audio",o=Yf(s)?s.quality:s.bitrate;return e({message:`
7
7
  [last ${n} selected] ${o}
8
8
  `}),s}return r==null||r.recordSwitch(t),t},Bt=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:c,visible:l,droppedVideoMaxQualityLimit:d,abrLogger:p})=>{var te,Z,F,ee,K;(0,B.assertNotEmptyArray)(a,zf);let h=r.usePixelRatio&&(te=window.devicePixelRatio)!=null?te:1,m=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*r.containerSizeFactor,height:e.height*h*r.containerSizeFactor},g=m&&(0,B.videoSizeToQuality)(m),S=r.considerPlaybackRate&&(0,B.isNonNullable)(o)?o:1,T=a.filter(M=>!(0,B.isInvariantQuality)(M.quality)).sort((M,k)=>(0,B.isHigher)(M.quality,k.quality)?-1:1),P=(Z=(0,Kt.default)(T,-1))==null?void 0:Z.quality,I=(F=(0,Kt.default)(T,0))==null?void 0:F.quality,E=(0,B.isNullable)(i)||(0,B.isNonNullable)(i.min)&&(0,B.isNonNullable)(i.max)&&(0,B.isLower)(i.max,i.min)||(0,B.isNonNullable)(i.min)&&I&&(0,B.isHigher)(i.min,I)||(0,B.isNonNullable)(i.max)&&P&&(0,B.isLower)(i.max,P),A=S*Qf(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),_={},Q=T.filter(M=>{if(!(g?(0,B.isLower)(M.quality,g):!0))return _[M.quality]="FitsContainer",!1;if(!((0,B.isNonNullable)(t)&&isFinite(t)&&(0,B.isNonNullable)(M.bitrate)?t-s>=M.bitrate*A:!0))return _[M.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&(0,B.isNonNullable)(r.minBufferToSwitchUp)&&u&&!(0,B.isInvariantQuality)(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&(0,B.isHigher)(M.quality,u.quality))return _[M.quality]="Buffer",!1;if(!!d&&(0,B.isHigherOrEqual)(M.quality,d))return _[M.quality]="DroppedFramesLimit",!1;let pe=E||((0,B.isNullable)(i.max)||(0,B.isLowerOrEqual)(M.quality,i.max))&&((0,B.isNullable)(i.min)||(0,B.isHigherOrEqual)(M.quality,i.min)),Ie=(0,B.isNonNullable)(l)&&!l?(0,B.isLowerOrEqual)(M.quality,r.backgroundVideoQualityLimit):!0;return!pe||!Ie?(_[M.quality]="FitsQualityLimits",!1):!0})[0];Q&&Q.bitrate&&Ox.next(Q.bitrate);let W=(ee=Q!=null?Q:T[Math.ceil((T.length-1)/2)])!=null?ee:a[0];return W.quality!==((K=c==null?void 0:c.last)==null?void 0:K.quality)&&p({message:`
9
9
  [VIDEO TRACKS ABR]
@@ -55,7 +55,7 @@
55
55
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
56
56
 
57
57
  [selected audio track] ${h==null?void 0:h.id}
58
- `}),h&&Kf(i,u,h,o)};var be=a=>new URL(a).hostname;var V=require("@vkontakte/videoplayer-shared");var Xf=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"))},$e=a=>O(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!Xf(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return Xf(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});var Ve=require("@vkontakte/videoplayer-shared");var ot=require("@vkontakte/videoplayer-shared");function ge(){return(0,ot.now)()}function Ko(a){return ge()-a}function Jo(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let c=n.indexOf("?")>-1?"&":"?";return u&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Zf(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Rr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,c=0,l,d,p=!1,h="arraybuffer",m=7e3,g=2e3,S=()=>{if(u)return;(0,ot.assertNonNullable)(l);let F=Ko(l),ee;if(F<g){ee=g-F,setTimeout(S,ee);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new i,_()},T=F=>(s=F,Z),P=F=>(d=F,Z),I=()=>(h="json",Z),E=()=>{if(!u){if(--c>=0){S(),r&&r();return}u=!0,d&&d(),t&&t()}},A=F=>(p=F,Z),_=()=>{l=ge(),n=new i,n.open("get",a);let F=0,ee,K=0,M=()=>((0,ot.assertNonNullable)(l),Math.max(l,Math.max(ee||0,K||0)));if(s&&n.addEventListener("progress",k=>{let Y=ge();s.updateChunk&&k.loaded>F&&(s.updateChunk(M(),k.loaded-F),F=k.loaded,ee=Y)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;(0,ot.assertNonNullable)(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let Y=n.response.byteLength-F;Y&&s.updateChunk&&s.updateChunk(M(),Y)}n.responseType==="json"&&!Object.values(n.response).length?E():(d&&d(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),p){let k=()=>{(0,ot.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=ge(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),Z},Z={withBitrateReporting:T,withParallel:A,withJSONResponse:I,withRetryCount:F=>(c=F,Z),withRetryInterval:(F,ee)=>((0,ot.isNonNullable)(F)&&(g=F),(0,ot.isNonNullable)(ee)&&(m=ee),Z),withTimeout:F=>(o=F,Z),withFinally:P,send:_,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return Z}var xi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Pi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ge(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ge()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Rr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ge()}_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=ge();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var ls=1e4,Xo=3;var _x=6e4,Nx=10,Fx=1,qx=500,Ai=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new xi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Jo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Jo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Ve.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Zf(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Pi(Xo,ls,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,c=null,l=!1,d=()=>{let E=s&&(!l||l===this.rep);return E||t("Not running!"),E},p=(E,A,_)=>{u&&u.abort(),u=Rr(this.urlResolver.resolve(E,!1),A,_,()=>this._retryCallback()).withTimeout(ls).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Xo).withFinally(()=>{u=null}).send()},h=(E,A,_)=>{(0,Ve.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),A,_,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{let A=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${A}=>${E}`),r.playbackRate=E)},g=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let _=ge()-1e4,ae=0;for(let W=0;W<this.bufferStates.length;W++){let te=this.bufferStates[W];E=Math.min(E,te.buf),te.ts<_&&ae++}this.bufferStates.splice(0,ae),t(`update playback rate; minBuffer=${E} drop=${ae} jitter=${this.sourceJitter}`);let Q=E-Fx;this.sourceJitter>=0?Q-=this.sourceJitter/2:this.sourceJitter-=1,Q>3?m(1.15):Q>1?m(1.1):Q>.3?m(1.05):m(1)}},T=E=>{let A,_=()=>A&&A.start?A.start.length:0,ae=k=>A.start[k]/1e3,Q=k=>A.dur[k]/1e3,W=k=>A.fragIndex+k,te=(k,Y)=>({chunkIdx:W(k),startTS:ae(k),dur:Q(k),discontinuity:Y}),Z=()=>{let k=0;if(A&&A.dur){let Y=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,se=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ue=Y;this.sourceJitter>1&&(ue+=this.sourceJitter-1);let pe=A.dur.length-1;for(;pe>=0&&(ue-=A.dur[pe],!(ue<=0));--pe);k=Math.min(pe,A.dur.length-1-se),k=Math.max(k,0)}return te(k,!0)},F=k=>{let Y=_();if(!(Y<=0)){if((0,Ve.isNonNullable)(k)){for(let se=0;se<Y;se++)if(ae(se)>k)return te(se)}return Z()}},ee=k=>{let Y=_(),se=k?k.chunkIdx+1:0,ue=se-A.fragIndex;if(!(Y<=0)){if(!k||ue<0||ue-Y>Nx)return t(`Resync: offset=${ue} bChunks=${Y} chunk=`+JSON.stringify(k)),Z();if(!(ue>=Y))return te(se-A.fragIndex,!1)}},K=(k,Y,se)=>{c&&c.abort(),c=Rr(this.urlResolver.resolve(k,!0,this.lowLatency),Y,se,()=>this._retryCallback()).withTimeout(ls).withRetryCount(Xo).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(k,Y)=>{K(E,se=>{if(!d())return;A=se;let ue=!!A.lowLatency;ue!==this.lowLatency&&g(ue);let pe=0;for(let Ie=0;Ie<A.dur.length;++Ie)pe+=A.dur[Ie];pe>0&&((0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(pe/A.dur.length)),i({name:"index",zeroTime:A.zeroTime,shiftDuration:A.shiftDuration}),this.sourceJitter=A.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,A.jitter/1e3)):1,k(F(Y))},()=>this._handleNetworkError())},nextChunk:ee}},P=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),(0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:E=>{let{videoElement:A,logger:_}=this.params,ae=T(e.jidxUrl),Q,W,te,Z,F=0,ee,K,M,k=()=>{ee&&(clearTimeout(ee),ee=void 0);let R=Math.max(qx,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=F+R,Ce=ge(),Ne=Math.min(1e4,Ee-Ce);F=Ce;let kt=()=>{c||d()&&ae.seek(()=>{d()&&(F=ge(),Y(),k())})};Ne>0?ee=window.setTimeout(()=>{this.paused?k():kt()},Ne):kt()},Y=()=>{let R;for(;R=ae.nextChunk(Z);)Z=R,Vt(R);let Ee=ae.nextChunk(te);if(Ee){if(te&&Ee.discontinuity){_("Detected discontinuity; restarting playback"),this.paused?k():(P(),this._initPlayerWith(e));return}Ie(Ee)}else k()},se=(R,Ee)=>{if(!d()||!this.sourceBuffer)return;let Ce,Ne,kt,or=Rt=>{window.setTimeout(()=>{d()&&se(R,Ee)},Rt)};if(this.sourceBuffer.updating)_("Source buffer is updating; delaying appendBuffer"),or(100);else{let Rt=ge(),_t=A.currentTime;!this.paused&&A.buffered.length>1&&K===_t&&Rt-M>500&&(_("Stall suspected; trying to fix"),this._fixupStall()),K!==_t&&(K=_t,M=Rt);let ur=this._getBufferSizeSec();if(ur>30)_(`Buffered ${ur} seconds; delaying appendBuffer`),or(2e3);else try{this.sourceBuffer.appendBuffer(R),this.videoPlayStarted?(this.bufferStates.push({ts:Rt,buf:ur}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(Hr){if(Hr.name==="QuotaExceededError")_("QuotaExceededError; delaying appendBuffer"),kt=this.sourceBuffer.buffered.length,kt!==0&&(Ce=this.sourceBuffer.buffered.start(0),Ne=_t,Ne-Ce>4&&this.sourceBuffer.remove(Ce,Ne-3)),or(1e3);else throw Hr}}},ue=()=>{W&&Q&&(_([`Appending chunk, sz=${W.byteLength}:`,JSON.stringify(te)]),se(W,function(){W=null,Y()}))},pe=R=>e.fragUrlTemplate.replace("%%id%%",R.chunkIdx),Ie=R=>{d()&&h(pe(R),(Ee,Ce)=>{if(d()){if(Ce/=1e3,W=Ee,te=R,n=R.startTS,Ce){let Ne=Math.min(10,R.dur/Ce);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ne:Ne}ue()}},()=>this._handleNetworkError())},Vt=R=>{d()&&((0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(pe(R),!1)))},wt=R=>{d()&&(e.cachedHeader=R,se(R,()=>{Q=!0,ue()}))};s=!0,ae.seek(R=>{if(d()){if(F=ge(),!R){k();return}Z=R,!(0,Ve.isNullable)(E)||R.startTS>E?Ie(R):(te=R,Y())}},E),e.cachedHeader?wt(e.cachedHeader):p(e.headerUrl,wt,()=>this._handleNetworkError())},stop:P,getTimestampSec:()=>n},l}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,Ve.isNonNullable)(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Ve.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ve.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=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=ge();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&&Ko(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&c(),h},notifySwitch:d=>{let p=ge();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Rr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ls).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;$e(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,c)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},_x))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var oe=require("@vkontakte/videoplayer-shared"),Zo=class{constructor(){this.onDroopedVideoFramesLimit$=new oe.Subject;this.subscription=new oe.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new oe.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,oe.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,oe.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,oe.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,oe.interval)(this.droppedFramesChecker.checkTime).pipe((0,oe.filter)(()=>this.playing),(0,oe.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,oe.debounce)(this.droppedFramesChecker.checkTime)),r=(0,oe.merge)(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,oe.isLower)(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ds=Zo;var ps=require("@vkontakte/videoplayer-shared"),em=require("@vkontakte/videoplayer-shared");var wi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Ux=(a,e)=>new ps.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||wi()))},C(C({},r),e));i.observe(a);let s=(0,em.fromEvent)(document,"visibilitychange").pipe((0,ps.map)(n=>!document.hidden||wi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ge=Ux;var Hx=["paused","playing","ready"],jx=["paused","playing","ready"],ki=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new j("stopped");this.representations$=new V.ValueSubject([]);this.textTracksManager=new je;this.droppedFramesManager=new ds;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new mt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:V.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=(r=Dt(u.name))!=null?r:(0,V.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p=C({},u.video);if(!l)continue;let h={id:c,quality:l,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,V.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(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(jx.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Hx.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Se(this.params.source.url,u))}return;default:return(0,V.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:V.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,V.merge)(this.videoState.stateChangeStarted$.pipe((0,V.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,V.map)(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(be(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Re(this.video);this.subscription.add(this.representations$.pipe((0,V.map)(i=>i.map(({track:s})=>s)),(0,V.filter)(i=>!!i.length),(0,V.once)()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,V.filterChanged)(),(0,V.map)(i=>-i/1e3)).subscribe(this.params.output.duration$)).add((0,V.combine)({zeroTime:this.zeroTime$.pipe((0,V.filter)(V.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(nt(this.video,this.params.desiredState.isLooped,t)).add(ke(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(He(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ge(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&(0,V.videoQualityToHeight)(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,V.assertNever)(i.to)}},t)).add((0,V.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,V.observableFrom)(["init"])).pipe((0,V.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),we(this.video)}createLiveDashPlayer(){let e=new Ai({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(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&(0,V.isNonNullable)(t)?t:Bt(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=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let g=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;(0,V.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;(0,V.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(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Se(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var tm=ki;var St=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var U=require("@vkontakte/videoplayer-shared");var hs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},$r=class extends hs{constructor(){super(),this.listeners||hs.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)}},Ri=class{constructor(){Object.defineProperty(this,"signal",{value:new $r,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ri.prototype[Symbol.toStringTag]="AbortController",$r.prototype[Symbol.toStringTag]="AbortSignal");function fs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function eu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!fs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(c,l){let d;l&&l.signal&&(d=l.signal,delete l.signal);let p=new t(c,l);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,c)=>{let l=s&&s.prototype.isPrototypeOf(u)?u.signal:c?c.signal:void 0;if(l){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(l.aborted)return Promise.reject(d);let p=new Promise((h,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 $i=fs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),rm=$i?eu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,vt=$i?rm.fetch:window.fetch,IL=$i?rm.Request:window.Request,yt=$i?Ri:window.AbortController,EL=$i?$r:window.AbortSignal;var mm=ze(Ti(),1);var Tt=()=>window.ManagedMediaSource||window.MediaSource,ms=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},im=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},am=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ut=require("@vkontakte/videoplayer-shared");var We=document.createElement("video"),Yx='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Qx='video/mp4; codecs="hev1.1.6.L93.B0"',bm='video/webm; codecs="vp09.00.10.08"',gm='video/webm; codecs="av01.0.00M.08"',zx='audio/mp4; codecs="mp4a.40.2"',Kx='audio/webm; codecs="opus"',sm,nm,Jt={mms:ms(),mse:im(),hls:!!((sm=We.canPlayType)!=null&&sm.call(We,"application/x-mpegurl")||(nm=We.canPlayType)!=null&&nm.call(We,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},om,um,Le={mp4:!!((om=We.canPlayType)!=null&&om.call(We,"video/mp4")),webm:!!((um=We.canPlayType)!=null&&um.call(We,"video/webm")),cmaf:!0},gs,cm,Ss,lm,vs,dm,ys,pm,Ts,hm,Is,fm,Me={h264:!!((cm=(gs=Tt())==null?void 0:gs.isTypeSupported)!=null&&cm.call(gs,Yx)),h265:!!((lm=(Ss=Tt())==null?void 0:Ss.isTypeSupported)!=null&&lm.call(Ss,Qx)),vp9:!!((dm=(vs=Tt())==null?void 0:vs.isTypeSupported)!=null&&dm.call(vs,bm)),av1:!!((pm=(ys=Tt())==null?void 0:ys.isTypeSupported)!=null&&pm.call(ys,gm)),aac:!!((hm=(Ts=Tt())==null?void 0:Ts.isTypeSupported)!=null&&hm.call(Ts,zx)),opus:!!((fm=(Is=Tt())==null?void 0:Is.isTypeSupported)!=null&&fm.call(Is,Kx))},Lr=(Me.h264||Me.h265)&&Me.aac,Xt,Jx=()=>O(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(z(C({},a),{video:z(C({},a.video),{contentType:gm})})),window.navigator.mediaCapabilities.decodingInfo(z(C({},a),{video:z(C({},a.video),{contentType:bm})}))]);Xt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{Jx()}catch(a){console.error(a)}var Mr=Jt.hls&&Le.mp4,Sm=()=>Object.keys(Me).filter(a=>Me[a]),vm=(a,e=!1,t=!1)=>{let r=Jt.mse||Jt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&Le.mp4&&Lr;case"DASH_WEBM":return r&&Le.webm&&Me.vp9&&Me.opus;case"DASH_WEBM_AV1":return r&&Le.webm&&Me.av1&&Me.opus;case"DASH_STREAMS":return r&&(Le.mp4&&Lr||Le.webm&&(Me.vp9||Me.av1)&&(Me.opus||Me.aac));case"DASH_LIVE":return Jt.mse&&Le.mp4&&Lr;case"DASH_LIVE_CMAF":return r&&Le.mp4&&Lr&&Le.cmaf;case"DASH_ONDEMAND":return r&&Le.mp4&&Lr;case"HLS":case"HLS_ONDEMAND":return Mr||e&&Jt.mse&&Le.mp4&&Lr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Mr;case"MPEG":return Le.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Jt.webrtc&&Jt.ws&&Me.h264&&(Le.mp4||Le.webm);default:return(0,ut.assertNever)(i)}})},bs=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Xt?Xt[t].smooth?[t,e]:Xt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Xt?Xt[t].powerEfficient?[t,e]:Xt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,ut.assertNever)(a)}return[e,t]},ym=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...bs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ut.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...bs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...bs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...bs(a),...i,"HLS","HLS_ONDEMAND"];default:(0,ut.assertNever)(e)}return Mr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Tm=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=ut.clientChecker.isMac&&ut.clientChecker.isSafari;if(ut.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,ut.assertNever)(a)}else Mr&&!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"]},tu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Im=a=>{if(a.size!==0){if(a.size===1)return a.values().next().value.split(".").at(0);for(let e of a){let t=(0,mm.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};var Cr=require("@vkontakte/videoplayer-shared"),Em=a=>{if(!a)return{id:"EmptyResponse",category:Cr.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Cr.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:Cr.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:Cr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Cr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Dr=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared");var Fr=ze(Ti(),1);var Xx=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},Zx=a=>window.clearTimeout(a),xm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ru=xm?Xx:window.requestIdleCallback,OL=xm?Zx:window.cancelIdleCallback;var lb=ze(ns(),1);var Ye=require("@vkontakte/videoplayer-shared");var eP=16,Pm=!1;try{Pm=Ye.clientChecker.isSafari&&!!Ye.clientChecker.macVersion&&Ye.clientChecker.macVersion<=eP}catch(a){console.error(a)}var iu=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)}append(e,t){return O(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return O(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return O(this,null,function*(){return new Promise(t=>{let r;Pm&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category: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)}}},Am=iu;var au=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var x=require("@vkontakte/videoplayer-shared");var re=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Br=class extends re{};var Li=class extends re{};var Mi=class extends re{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var Ci=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends re{constructor(e,t){super(e,t),this.data=this.content}};var de=class extends re{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Zt=class extends de{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}};var Oi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends de{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ni=class extends de{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Fi=class extends de{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var qi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends de{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Hi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends de{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Wi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yi=class extends de{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Qi=class extends de{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var zi=class extends de{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var rP={ftyp:Mi,moov:Ci,moof:Di,mdat:Bi,sidx:Zt,trak:Oi,mdia:qi,mfhd:Gi,tkhd:Ui,traf:Wi,tfhd:Yi,tfdt:Qi,trun:zi,minf:Hi,sv3d:Vi,st3d:_i,prhd:Ni,proj:ji,equi:Fi,uuid:Li,unknown:Br},er=class a{constructor(e={}){this.options=C({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=rP[e];return r?new r(t,new a):new Br(t,new a)}};var Or=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var aP=new TextDecoder("ascii"),sP=a=>aP.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",nP=a=>{let e=new Zt(a,new er),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},oP=(a,e)=>{let r=new er().parse(a),i=new Or(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,d)},uP=(a,e)=>{let r=new er().parse(a),s=new Or(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),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},cP=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new er().parse(a),i=new Or(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},wm={validateData:sP,parseInit:cP,getIndexRange:()=>{},parseSegments:nP,parseFeedableSegmentChunk:oP,getSegmentEndTime:uP};var It=require("@vkontakte/videoplayer-shared");var Rm=require("@vkontakte/videoplayer-shared");var km={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"}},$m=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Ki(a,t),i=r in km,s=i?km[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,l=Ki(u),d=c*it(2,(o-1)*8)+l,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Ki=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*it(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*it(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*it(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},et=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ki(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:(0,Rm.assertNever)(e)}},tr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=$m(r);if(!e(i))return;i.type==="master"&&tr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Lm=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=$m(a);return tr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=et(o,n):s===17026?t=et(o,n):s===17029&&(r=et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Mm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],lP=[231,22612,22743,167,171,163,160,175],dP=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,c,l=!1,d=0;return tr(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let S=et(m,h);c=Ki(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?r=et(m,h):p===17545?i=et(m,h):p===21420&&c===475249515?u=et(m,h):p===374648427?tr(m,({tag:S,type:T,value:P})=>S===30321?(l=et(P,T)===1,!1):!0):s&&n&&Mm.includes(p)&&(o=!0),!o}),(0,It.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,It.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,It.assertNonNullable)(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},pP=a=>{if((0,It.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},hP=(a,e)=>{let t=!1,r=!1,i=o=>(0,It.isNonNullable)(o.time)&&(0,It.isNonNullable)(o.position),s=[],n;return tr(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=et(c,u));break;case 183:break;case 241:n&&(n.position=et(c,u));break;default:t&&Mm.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:l}=o,d=s[u+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},fP=a=>{let e=0,t=!1;try{tr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):lP.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Cm={validateData:Lm,parseInit:dP,getIndexRange:pP,parseSegments:hP,parseFeedableSegmentChunk:fP};var Vr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Cm;case"mp4":return wm}}throw new ReferenceError(`Unsupported mime type ${a}`)};var pu=ze(tb(),1);var du=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var Nr=require("@vkontakte/videoplayer-shared");var rb=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var ib=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},rr=(a,e)=>{let t=a;t=(0,pu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,pu.default)(t,n,(o,u)=>(0,Nr.isNullable)(s)?o:(0,Nr.isNullable)(u)?s:s.padStart(parseInt(u,10),"0"))}return t},sb=(a,e)=>{var E,A,_,ae,Q,W,te,Z,F,ee,K,M,k,Y,se,ue,pe,Ie,Vt,wt,R,Ee,Ce,Ne,kt,or,Rt,_t,ur,Hr,Pu,Au,wu,ku,Ru,$u,Lu,Mu,Cu,Du,Bu,Ou,Vu,_u,Nu,Fu,qu,Uu,Hu,ju;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(_=(A=(E=s.querySelector("BaseURL"))==null?void 0:E.textContent)==null?void 0:A.trim())!=null?_:"",u=n.children,c=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=l?new Date(l).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],S=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=ib(h);else if(m){let xe=ib(m);(0,Nr.isNonNullable)(xe)&&(p=xe)}else S&&(p=parseInt(S,10));let T=0,P=(Q=(ae=s.getAttribute("profiles"))==null?void 0:ae.split(","))!=null?Q:[];for(let xe of u){let Ob=(W=xe.getAttribute("id"))!=null?W:"id"+(T++).toString(10),jr=(te=xe.getAttribute("mimeType"))!=null?te:"",_s=(Z=xe.getAttribute("codecs"))!=null?Z:"",Ns=(F=xe.getAttribute("contentType"))!=null?F:jr==null?void 0:jr.split("/")[0],Vb=(K=(ee=xe.getAttribute("profiles"))==null?void 0:ee.split(","))!=null?K:[],_b=(M=xe.getAttribute("lang"))!=null?M:void 0,Nb=(se=(Y=(k=xe.querySelector("Label"))==null?void 0:k.textContent)==null?void 0:Y.trim())!=null?se:void 0,Fb=xe.querySelectorAll("Representation"),qb=xe.querySelector("SegmentTemplate"),Ub=(pe=(ue=xe.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?pe:void 0,Gr=Ns,fe={id:Ob,language:_b,isDefault:Ub==="main",label:Nb,codecs:_s,hdr:Gr==="video"&&du(_s),mime:jr,representations:[]};for(let he of Fb){let Hb=(Ie=he.getAttribute("lang"))!=null?Ie:void 0,jb=(Vt=he.getAttribute("label"))!=null?Vt:void 0,Gb=(Ee=(R=(wt=he.querySelector("BaseURL"))==null?void 0:wt.textContent)==null?void 0:R.trim())!=null?Ee:"",Fs=new URL(Gb||o,e).toString(),cr=(Ce=he.getAttribute("mimeType"))!=null?Ce:jr,ga=(kt=(Ne=he.getAttribute("codecs"))!=null?Ne:_s)!=null?kt:"",qs;if(Ns==="text"){let Nt=he.getAttribute("id")||"",Us=Nt.includes("_auto");qs={id:Nt,isAuto:Us,kind:"text",url:Fs}}else{let Nt=(Rt=(or=he.getAttribute("contentType"))!=null?or:cr==null?void 0:cr.split("/")[0])!=null?Rt:Ns,Us=(ur=(_t=xe.getAttribute("profiles"))==null?void 0:_t.split(","))!=null?ur:[],Wb=parseInt((Hr=he.getAttribute("width"))!=null?Hr:"",10),Gu=parseInt((Pu=he.getAttribute("height"))!=null?Pu:"",10),Wu=parseInt((Au=he.getAttribute("bandwidth"))!=null?Au:"",10)/1e3,Yu=(wu=he.getAttribute("frameRate"))!=null?wu:"",Yb=(ku=he.getAttribute("quality"))!=null?ku:void 0,Qb=Yu?rb(Yu):void 0,zb=(Ru=he.getAttribute("id"))!=null?Ru:"id"+(T++).toString(10),Kb=Nt==="video"?`${Gu}p`:Nt==="audio"?`${Wu}Kbps`:ga,Jb=`${zb}@${Kb}`,Xb=[...P,...Vb,...Us],Hs,Zb=he.querySelector("SegmentBase"),Ft=($u=he.querySelector("SegmentTemplate"))!=null?$u:qb;if(Zb){let qt=(Mu=(Lu=he.querySelector("SegmentBase Initialization"))==null?void 0:Lu.getAttribute("range"))!=null?Mu:"",[Ut,Gs]=qt.split("-").map(lr=>parseInt(lr,10)),$t={from:Ut,to:Gs},Wr=(Cu=he.querySelector("SegmentBase"))==null?void 0:Cu.getAttribute("indexRange"),[Ws,Sa]=Wr?Wr.split("-").map(lr=>parseInt(lr,10)):[],Yr=Wr?{from:Ws,to:Sa}:void 0;Hs={type:"byteRange",url:Fs,initRange:$t,indexRange:Yr}}else if(Ft){let qt={representationId:(Du=he.getAttribute("id"))!=null?Du:void 0,bandwidth:(Bu=he.getAttribute("bandwidth"))!=null?Bu:void 0},Ut=parseInt((Ou=Ft.getAttribute("timescale"))!=null?Ou:"",10),Gs=(Vu=Ft.getAttribute("initialization"))!=null?Vu:"",$t=Ft.getAttribute("media"),Wr=(Nu=parseInt((_u=Ft.getAttribute("startNumber"))!=null?_u:"",10))!=null?Nu:1,Ws=rr(Gs,qt);if(!$t)throw new ReferenceError("No media attribute in SegmentTemplate");let Sa=(Fu=Ft.querySelectorAll("SegmentTimeline S"))!=null?Fu:[],Yr=[],lr=0,Ys="",Qs=0;if(Sa.length){let va=Wr,Qe=0;for(let dr of Sa){let rt=parseInt((qu=dr.getAttribute("d"))!=null?qu:"",10),Ht=parseInt((Uu=dr.getAttribute("r"))!=null?Uu:"",10)||0,ya=parseInt((Hu=dr.getAttribute("t"))!=null?Hu:"",10);Qe=Number.isFinite(ya)?ya:Qe;let zs=rt/Ut*1e3,Ks=Qe/Ut*1e3;for(let Ta=0;Ta<Ht+1;Ta++){let tg=rr($t,z(C({},qt),{segmentNumber:va.toString(10),segmentTime:(Qe+Ta*rt).toString(10)})),Qu=(Ks!=null?Ks:0)+Ta*zs,rg=Qu+zs;va++,Yr.push({time:{from:Qu,to:rg},url:tg})}Qe+=(Ht+1)*rt,lr+=(Ht+1)*zs}Qs=Qe/Ut*1e3,Ys=rr($t,z(C({},qt),{segmentNumber:va.toString(10),segmentTime:Qe.toString(10)}))}else if((0,Nr.isNonNullable)(p)){let Qe=parseInt((ju=Ft.getAttribute("duration"))!=null?ju:"",10)/Ut*1e3,dr=Math.ceil(p/Qe),rt=0;for(let Ht=1;Ht<dr;Ht++){let ya=rr($t,z(C({},qt),{segmentNumber:Ht.toString(10),segmentTime:rt.toString(10)}));Yr.push({time:{from:rt,to:rt+Qe},url:ya}),rt+=Qe}Qs=rt,Ys=rr($t,z(C({},qt),{segmentNumber:dr.toString(10),segmentTime:rt.toString(10)}))}let eg={time:{from:Qs,to:1/0},url:Ys};Hs={type:"template",baseUrl:Fs,segmentTemplateUrl:$t,initUrl:Ws,totalSegmentsDurationMs:lr,segments:Yr,nextSegmentBeyondManifest:eg,timescale:Ut}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Nt||!cr)continue;let js={video:"video",audio:"audio",text:"text"}[Nt];if(!js)continue;Gr||(Gr=js),qs={id:Jb,kind:js,segmentReference:Hs,profiles:Xb,duration:p,bitrate:Wu,mime:cr,codecs:ga,width:Wb,height:Gu,fps:Qb,quality:Yb}}fe.language||(fe.language=Hb),fe.label||(fe.label=jb),fe.mime||(fe.mime=cr),fe.codecs||(fe.codecs=ga),fe.hdr||(fe.hdr=Gr==="video"&&du(ga)),fe.representations.push(qs)}Gr&&i[Gr].push(fe)}return{dynamic:c,liveAvailabilityStartTime:d,duration:p,streams:i}};var Ji=ze(Ti(),1);var nb=require("@vkontakte/videoplayer-shared"),ob=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?Dt(s):void 0)!=null?o:(0,nb.videoSizeToQuality)({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},ub=({id:a,bitrate:e})=>({id:a,bitrate:e}),Es=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Ji.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Ji.default)(t,-1)},cb=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),fu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Ji.default)(r.split("."),0),isDefault:i}),mu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Ji.default)(i.split("."),0)}),xs=a=>"url"in a,Et=a=>a.type==="template",Xi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Zi=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new x.ValueSubject(0);this.onLastSegment$=new x.ValueSubject(!1);this.fullyBuffered$=new x.ValueSubject(!1);this.playingRepresentation$=new x.ValueSubject(void 0);this.playingRepresentationInit$=new x.ValueSubject(void 0);this.error$=new x.Subject;this.gaps=[];this.subscription=new x.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new yt;this.destroyAbortController=new yt;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,x.abortable)(this.destroyAbortController.signal,function(e){return me(this,null,function*(){let t=this.representations.get(e);(0,x.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 Am(this.sourceBuffer),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.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,au(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=St(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,c<l)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,x.assertNonNullable)(r,"No init buffer for starting representation"),(0,x.assertNonNullable)(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=(0,x.abortable)(this.destroyAbortController.signal,function(e,t=!1){return me(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,x.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,x.isNullable)(s)||(0,x.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,x.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,x.isNonNullable)(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),yield new Xs(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,x.abortable)(this.destroyAbortController.signal,function(e){return me(this,null,function*(){var u,c;let t=(u=e==null?void 0:e.flatMap(l=>l.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let d=t.find(m=>m.id===l);d&&this.representations.set(l,d);let p=this.representations.get(l);if(!p||!Et(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(c=this.switchingToRepresentationId)!=null?c:this.downloadingRepresentationId,i=this.representations.get(r);(0,x.assertNonNullable)(i);let s=this.segments.get(r);(0,x.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,x.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,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.dynamic),this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new yt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;if((0,x.isNullable)(e)||(0,x.isNullable)(this.downloadingRepresentationId)||(0,x.isNullable)(this.playingRepresentationId)||(0,x.isNullable)(this.sourceBuffer)||!(0,x.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,x.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((c=i==null?void 0:i.time.to)!=null?c:0)-((l=i==null?void 0:i.time.from)!=null?l:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=St(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&au(this.sourceBuffer.buffered)>=this.bufferLimit){let d=St(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let p=(0,Fr.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&St(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Fr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;(0,x.isNonNullable)(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!Et(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>z(C({},p),{status:"none",size:void 0})),c=(i=this.segments.get(o.id))!=null?i:[],l=(n=(s=(0,Fr.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,x.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Et(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),c=rr(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let g=p<=r&&h>=r,S=p>r||g||m===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),P=this.preloadOnly&&p<=r+T||h<=r+T;return(d==="none"||d==="partially_ejected"&&S&&P&&this.sourceBuffer&&!(Dr(this.sourceBuffer.buffered,p)&&Dr(this.sourceBuffer.buffered,h)))&&S&&P});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=c||o<=l);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return O(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return O(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,x.abortable)(o,function(){return me(this,null,function*(){let l=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!l)return;let d=new DataView(l);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=Vr(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&c?yield Promise.all(c):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Xi(l)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return O(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,x.abortable)(n,function(){return me(this,null,function*(){let u=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),(0,x.fromEvent)(window,"online").pipe((0,x.once)()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Xi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(Et(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Fr.default)(e,0).byte.from,to:(0,Fr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Et(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,l)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return O(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Vr(o.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(c.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,c=e.byteLength;for(let l of this.activeSegments){let{segment:d}=l,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:c;if(l.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let g=p?d.byte.from-r:0,S=p?d.byte.to-r:e.byteLength,T=g<i,P=S<=i;if(d.status==="downloading"&&T&&P){d.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+g,h),E=this.getCurrentPosition();(0,x.isNonNullable)(E)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-E,this.bufferAccumulation.accumulated.push({segmentView:I,segmentProgress:l}),this.activeSegments.delete(l));let A=({segmentView:_,segmentProgress:ae})=>this.sourceBufferTaskQueue.append(_,s).then(Q=>Q&&!s.aborted?this.onSegmentFullyAppended(ae,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(A),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||(0,x.isNullable)(E))&&(A({segmentView:I,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&!P&&(l.loadedBytes=Math.min(h,i-g),l.loadedBytes>l.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+g+l.feedingBytes,l.loadedBytes-l.feedingBytes),E=l.loadedBytes===h?I:Vr(o.mime).parseFeedableSegmentChunk(I);E!=null&&E.byteLength&&(d.status="partially_fed",l.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,s).then(A=>{if(s.aborted)n();else if(A)l.fedBytes+=E.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return O(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let c of this.activeSegments){let{segment:l}=c;if(c.representationId!==t)continue;if(s.aborted){n();continue}let d=l.byte.from-r,p=l.byte.to-r,h=p-d+1,m=d<i,g=p<=i;if(m){if(l.status==="downloading"&&g){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?this.onSegmentFullyAppended(c,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(c.loadedBytes=Math.min(h,i-d),c.loadedBytes>c.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+c.feedingBytes,c.loadedBytes-c.feedingBytes),T=c.loadedBytes===h?S:Vr(u.mime).parseFeedableSegmentChunk(S);T!=null&&T.byteLength&&(l.status="partially_fed",c.feedingBytes+=T.byteLength,(yield this.sourceBufferTaskQueue.append(T,s))&&!s.aborted?(c.fedBytes+=T.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t)):n())}}}})}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",xs(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&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,x.assertNonNullable)(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(s=>this.sourceBuffer&&(Math.round(s.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(s.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=ru(()=>(0,lb.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return O(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,x.abortable)(this.destroyAbortController.signal,function(){return me(this,null,function*(){let o=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Vr(e.mime),i)).then(o=>O(this,null,function*(){if(!o)return;let{init:u,dataView:c,segments:l}=o,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d);let p=l;this.isLive&&Et(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:x.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return O(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return O(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return O(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.isNullable)(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((l,d)=>l.from-d.from);let c=[u[0]];for(let l=1;l<u.length;l++){let{from:d,to:p}=u[l],h=c[c.length-1];h.to>=d?h.to=Math.max(h.to,p):c.push(u[l])}return c},o=u=>{var l;if(s>=t)return i;i.push(C({},u.time)),i=n(i);let c=xs(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let l=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let p={time:{from:c,to:l},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>=e+u&&l.status==="fed"&&o(l)}return i.length?(yield Promise.all(i.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1})}pruneBufferOld(e,t,r=!1){return O(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.isNullable)(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=c=>{var d;s=Math.min(s,c.time.from),n=Math.max(n,c.time.to);let l=xs(c)?(d=c.size)!=null?d:0:c.byte.to-c.byte.from;i+=l};for(let c of this.segments.values())for(let l of c){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;l.status==="fed"&&u(l)}if(o=isFinite(s)&&isFinite(n),!o){i=0,s=1/0,n=-1/0;for(let c of this.segments.values())for(let l of c){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;l.status==="fed"&&u(l)}}if(o=isFinite(s)&&isFinite(n),!o)for(let c=0;c<this.sourceBuffer.buffered.length;c++){let l=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)){s=l,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){i=0,s=1/0,n=-1/0;let c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>e+c&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=ru(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:x.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,x.isNullable)(this.sourceBuffer)||(0,x.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=10;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),c=e.filter(l=>n>=l.from&&n<l.to-t||o>l.from+t&&o<=l.to);u||(c.length===1?i.status="partially_ejected":this.gaps.some(l=>l.from===i.time.from||l.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var ea=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var db=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};var J=require("@vkontakte/videoplayer-shared");var Ps=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new J.ValueSubject(void 0);this.lastConnectionReused$=new J.ValueSubject(void 0);this.lastRequestFirstBytes$=new J.ValueSubject(void 0);this.abortAllController=new yt;this.subscription=new J.Subscription;this.fetchManifest=(0,J.abortable)(this.abortAllController.signal,function(e){return me(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ea(r));let i=yield vt(r,{signal:this.abortAllController.signal}).catch(ta);return i?(t.log("success",(0,J.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",(0,J.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,J.abortable)(this.abortAllController.signal,function(c){return me(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var F,ee;let l=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let K=new URL(l,location.href);K.searchParams.append("bytes",`${r.from}-${r.to}`),l=K.toString();break}default:(0,J.assertNever)(t)}this.requestQuic&&(l=ea(l));let h=this.abortAllController.signal,m;if(n){let K=new yt;if(m=(0,J.merge)((0,J.fromEvent)(this.abortAllController.signal,"abort"),(0,J.fromEvent)(n,"abort")).subscribe(()=>{try{K.abort()}catch(M){ta(M)}}),this.abortAllController.signal.aborted||n.aborted)try{K.abort()}catch(M){ta(M)}h=K.signal}let g=(0,J.now)();p.log("startRequest",(0,J.flattenObject)({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:g}));let S=yield vt(l,{priority:s,headers:d,signal:h}).catch(ta),T=(0,J.now)();if(!S)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((F=this.throughputEstimator)==null||F.addRawRtt(T-g),!S.ok||!S.body){m==null||m.unsubscribe();let K=`Fetch error ${S.status}: ${S.statusText}`;return p.error("error",{message:K}),p.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!i&&!o){m==null||m.unsubscribe();let K=(0,J.now)(),M={requestStartedAt:g,requestEndedAt:K,duration:K-g};return p.log("endRequest",(0,J.flattenObject)(M)),p.end(),S.arrayBuffer()}let[P,I]=S.body.tee(),E=P.getReader();o&&((ee=this.throughputEstimator)==null||ee.trackStream(I,u));let A=0,_=new Uint8Array(0),ae=!1,Q=K=>{m==null||m.unsubscribe(),ae=!0,ta(K)},W=(0,J.abortable)(h,function(k){return me(this,arguments,function*({done:K,value:M}){if(A===0&&this.lastRequestFirstBytes$.next((0,J.now)()-g),h.aborted){m==null||m.unsubscribe();return}if(!K&&M){let Y=new Uint8Array(_.length+M.length);Y.set(_),Y.set(M,_.length),_=Y,A+=M.byteLength,i==null||i(new DataView(_.buffer),A),yield E==null?void 0:E.read().then(W,Q)}})}.bind(this));yield E==null?void 0:E.read().then(W,Q),m==null||m.unsubscribe();let te=(0,J.now)(),Z={failed:ae,requestStartedAt:g,requestEndedAt:te,duration:te-g};return ae?(p.error("endRequest",(0,J.flattenObject)(Z)),p.end(),null):(p.log("endRequest",(0,J.flattenObject)(Z)),p.end(),_.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,J.abortable)(this.abortAllController.signal,function(e,t,r){return me(this,null,function*(){var T;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,i),o=Math.max(l,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(T=e.indexRange)!=null?T: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 P=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!P)return null;g=new DataView(P)}let S=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,J.abortable)(this.abortAllController.signal,function(e,t){return me(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>z(C({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=db(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return O(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,J.assertNever)(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ta=a=>{if(!Xi(a))throw a};var ir=(a,e,t)=>t*e+(1-t)*a,bu=(a,e)=>a.reduce((t,r)=>t+r,0)/e,pb=(a,e,t,r)=>{let i=0,s=t,n=bu(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};var ra=require("@vkontakte/videoplayer-shared");var Ot=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new ra.ValueSubject(e.initial),this.debounced$=new ra.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Te(`raw_${t}`),this.smoothedSeries$=new Te(`smoothed_${t}`),this.reportedSeries$=new Te(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=it(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,ra.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 As=class extends Ot{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ir(this.slow,e,this.params.emaAlphaSlow),this.fast=ir(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ws=class extends Ot{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=bu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ir(this.emaSmoothed,e,this.params.emaAlpha);let r=pb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var ks=class extends Ot{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?ir(this.smoothed,t,this.params.emaAlpha):t}};var ar=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new As({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ws({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ks(C({initial:e,label:"liveEdgeDelay"},t))}};var gu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var fb=["timeupdate","progress","play","seeked","stalled","waiting"];var Rs=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.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.timeInWaiting=0;this.isActiveLowLatency$=new v.ValueSubject(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new yt;this.initManifest=(0,v.abortable)(this.destroyController.signal,function(e,t,r){return me(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Se(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,function(){return me(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t;try{t=sb(e!=null?e:"",this.manifestUrlString)}catch(u){let c=(n=Em(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 r=(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=Tt())==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 i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let l=t.streams[u].filter(({mime:h,codecs:m})=>r(u,h,m)),d=new Set(l.map(({codecs:h})=>h)),p=Im(d);if(p&&(i[u]=l.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=i.video.some(S=>S.hdr),g=i.video.some(S=>!S.hdr);v.clientChecker.isHDR&&h&&m?i.video=i.video.filter(S=>S.hdr):g&&(i.video=i.video.filter(S=>!S.hdr))}}let s=z(C({},t),{streams:i});return this.tracer.log("updateManifestEnd",(0,v.flattenObject)(s)),s})}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,function(e,t,r){return me(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",(0,v.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=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?am():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ms())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Zi("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 Zi("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,v.interval)(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=qo(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add((0,v.merge)(...fb.filter(p=>p!=="waiting").map(p=>(0,v.fromEvent)(this.element,p))).pipe((0,v.map)(p=>this.element?St(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.filter)(p=>!!p),(0,v.tap)(p=>{var h;(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=>gu(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,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,P=h-g,I=1;Math.abs(P)>S&&(I=1+Math.sign(P)*T),gu(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let m=0;if(h){let T=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var E,A;return(A=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?A:T}))-T}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(g=>O(this,[g],function*({liveLoadBufferLength:h,bufferLength:m}){if((0,v.assertNonNullable)(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,T=qo(this.manifestUrlString,2),P=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(P,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,A=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,_=isFinite(h)?h:m,ae=this.isActiveLowLatency$.getValue(),Q=P<=this.tuning.live.activeLiveDelay&&T===0;this.isActiveLowLatency$.next(ae&&Q);let W="none";if(ae?W="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&Q?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(te=>te.proceedLowLatencyLive()),W="active_low_latency"):T!==0&&_<I?W="live_forward_buffering":_<I+A&&(W="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),W==="live_forward_buffering"||W==="live_with_target_offset"){let te=p-(I+E),Z=this.normolizeLiveOffset(Math.trunc(T+te/S)),F=Math.abs(Z-T),ee;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?ee=T:Z>0&&F>this.tuning.dashCmafLive.offsetCalculationError?ee=Z:ee=0,this.manifestUrlString=Se(this.manifestUrlString,ee,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.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),Et(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,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Ps({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=ar.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,C({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return O(this,null,function*(){var r,i,s,n;(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=Se(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio))})}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...fb.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,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Dr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var n,o;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s=z(C({},s),{liveLastSeekOffset:this.liveLastSeekOffset});else{let u=this.element.currentTime*1e3;(n=this.videoBufferManager)==null||n.maintain(u),(o=this.audioBufferManager)==null||o.maintain(u),s=z(C({},s),{position:u})}this.tracer.log("stallIntervalCallback",(0,v.flattenObject)(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return O(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u,c;(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Dr(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(c=this.audioBufferManager)==null||c.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,v.flattenObject)({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,v.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return O(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=z(C({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,v.flattenObject)(t)))}}};var $s=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ls=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/it(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=C({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*it(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var mb=`attribute vec2 a_vertex;
58
+ `}),h&&Kf(i,u,h,o)};var be=a=>new URL(a).hostname;var V=require("@vkontakte/videoplayer-shared");var Xf=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"))},$e=a=>O(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!Xf(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return Xf(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});var Ve=require("@vkontakte/videoplayer-shared");var ot=require("@vkontakte/videoplayer-shared");function ge(){return(0,ot.now)()}function Ko(a){return ge()-a}function Jo(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let c=n.indexOf("?")>-1?"&":"?";return u&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Zf(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Rr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,c=0,l,d,p=!1,h="arraybuffer",m=7e3,g=2e3,S=()=>{if(u)return;(0,ot.assertNonNullable)(l);let F=Ko(l),ee;if(F<g){ee=g-F,setTimeout(S,ee);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new i,_()},T=F=>(s=F,Z),P=F=>(d=F,Z),I=()=>(h="json",Z),E=()=>{if(!u){if(--c>=0){S(),r&&r();return}u=!0,d&&d(),t&&t()}},A=F=>(p=F,Z),_=()=>{l=ge(),n=new i,n.open("get",a);let F=0,ee,K=0,M=()=>((0,ot.assertNonNullable)(l),Math.max(l,Math.max(ee||0,K||0)));if(s&&n.addEventListener("progress",k=>{let Y=ge();s.updateChunk&&k.loaded>F&&(s.updateChunk(M(),k.loaded-F),F=k.loaded,ee=Y)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;(0,ot.assertNonNullable)(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let Y=n.response.byteLength-F;Y&&s.updateChunk&&s.updateChunk(M(),Y)}n.responseType==="json"&&!Object.values(n.response).length?E():(d&&d(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),p){let k=()=>{(0,ot.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=ge(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),Z},Z={withBitrateReporting:T,withParallel:A,withJSONResponse:I,withRetryCount:F=>(c=F,Z),withRetryInterval:(F,ee)=>((0,ot.isNonNullable)(F)&&(g=F),(0,ot.isNonNullable)(ee)&&(m=ee),Z),withTimeout:F=>(o=F,Z),withFinally:P,send:_,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return Z}var xi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Pi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ge(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ge()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Rr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ge()}_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=ge();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var ls=1e4,Xo=3;var _x=6e4,Nx=10,Fx=1,qx=500,Ai=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new xi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Jo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Jo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Ve.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Zf(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Pi(Xo,ls,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,c=null,l=!1,d=()=>{let E=s&&(!l||l===this.rep);return E||t("Not running!"),E},p=(E,A,_)=>{u&&u.abort(),u=Rr(this.urlResolver.resolve(E,!1),A,_,()=>this._retryCallback()).withTimeout(ls).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Xo).withFinally(()=>{u=null}).send()},h=(E,A,_)=>{(0,Ve.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),A,_,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{let A=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${A}=>${E}`),r.playbackRate=E)},g=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let _=ge()-1e4,ae=0;for(let W=0;W<this.bufferStates.length;W++){let te=this.bufferStates[W];E=Math.min(E,te.buf),te.ts<_&&ae++}this.bufferStates.splice(0,ae),t(`update playback rate; minBuffer=${E} drop=${ae} jitter=${this.sourceJitter}`);let Q=E-Fx;this.sourceJitter>=0?Q-=this.sourceJitter/2:this.sourceJitter-=1,Q>3?m(1.15):Q>1?m(1.1):Q>.3?m(1.05):m(1)}},T=E=>{let A,_=()=>A&&A.start?A.start.length:0,ae=k=>A.start[k]/1e3,Q=k=>A.dur[k]/1e3,W=k=>A.fragIndex+k,te=(k,Y)=>({chunkIdx:W(k),startTS:ae(k),dur:Q(k),discontinuity:Y}),Z=()=>{let k=0;if(A&&A.dur){let Y=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,se=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ue=Y;this.sourceJitter>1&&(ue+=this.sourceJitter-1);let pe=A.dur.length-1;for(;pe>=0&&(ue-=A.dur[pe],!(ue<=0));--pe);k=Math.min(pe,A.dur.length-1-se),k=Math.max(k,0)}return te(k,!0)},F=k=>{let Y=_();if(!(Y<=0)){if((0,Ve.isNonNullable)(k)){for(let se=0;se<Y;se++)if(ae(se)>k)return te(se)}return Z()}},ee=k=>{let Y=_(),se=k?k.chunkIdx+1:0,ue=se-A.fragIndex;if(!(Y<=0)){if(!k||ue<0||ue-Y>Nx)return t(`Resync: offset=${ue} bChunks=${Y} chunk=`+JSON.stringify(k)),Z();if(!(ue>=Y))return te(se-A.fragIndex,!1)}},K=(k,Y,se)=>{c&&c.abort(),c=Rr(this.urlResolver.resolve(k,!0,this.lowLatency),Y,se,()=>this._retryCallback()).withTimeout(ls).withRetryCount(Xo).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(k,Y)=>{K(E,se=>{if(!d())return;A=se;let ue=!!A.lowLatency;ue!==this.lowLatency&&g(ue);let pe=0;for(let Ie=0;Ie<A.dur.length;++Ie)pe+=A.dur[Ie];pe>0&&((0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(pe/A.dur.length)),i({name:"index",zeroTime:A.zeroTime,shiftDuration:A.shiftDuration}),this.sourceJitter=A.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,A.jitter/1e3)):1,k(F(Y))},()=>this._handleNetworkError())},nextChunk:ee}},P=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),(0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:E=>{let{videoElement:A,logger:_}=this.params,ae=T(e.jidxUrl),Q,W,te,Z,F=0,ee,K,M,k=()=>{ee&&(clearTimeout(ee),ee=void 0);let R=Math.max(qx,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=F+R,Ce=ge(),Ne=Math.min(1e4,Ee-Ce);F=Ce;let kt=()=>{c||d()&&ae.seek(()=>{d()&&(F=ge(),Y(),k())})};Ne>0?ee=window.setTimeout(()=>{this.paused?k():kt()},Ne):kt()},Y=()=>{let R;for(;R=ae.nextChunk(Z);)Z=R,Vt(R);let Ee=ae.nextChunk(te);if(Ee){if(te&&Ee.discontinuity){_("Detected discontinuity; restarting playback"),this.paused?k():(P(),this._initPlayerWith(e));return}Ie(Ee)}else k()},se=(R,Ee)=>{if(!d()||!this.sourceBuffer)return;let Ce,Ne,kt,or=Rt=>{window.setTimeout(()=>{d()&&se(R,Ee)},Rt)};if(this.sourceBuffer.updating)_("Source buffer is updating; delaying appendBuffer"),or(100);else{let Rt=ge(),_t=A.currentTime;!this.paused&&A.buffered.length>1&&K===_t&&Rt-M>500&&(_("Stall suspected; trying to fix"),this._fixupStall()),K!==_t&&(K=_t,M=Rt);let ur=this._getBufferSizeSec();if(ur>30)_(`Buffered ${ur} seconds; delaying appendBuffer`),or(2e3);else try{this.sourceBuffer.appendBuffer(R),this.videoPlayStarted?(this.bufferStates.push({ts:Rt,buf:ur}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(Hr){if(Hr.name==="QuotaExceededError")_("QuotaExceededError; delaying appendBuffer"),kt=this.sourceBuffer.buffered.length,kt!==0&&(Ce=this.sourceBuffer.buffered.start(0),Ne=_t,Ne-Ce>4&&this.sourceBuffer.remove(Ce,Ne-3)),or(1e3);else throw Hr}}},ue=()=>{W&&Q&&(_([`Appending chunk, sz=${W.byteLength}:`,JSON.stringify(te)]),se(W,function(){W=null,Y()}))},pe=R=>e.fragUrlTemplate.replace("%%id%%",R.chunkIdx),Ie=R=>{d()&&h(pe(R),(Ee,Ce)=>{if(d()){if(Ce/=1e3,W=Ee,te=R,n=R.startTS,Ce){let Ne=Math.min(10,R.dur/Ce);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ne:Ne}ue()}},()=>this._handleNetworkError())},Vt=R=>{d()&&((0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(pe(R),!1)))},wt=R=>{d()&&(e.cachedHeader=R,se(R,()=>{Q=!0,ue()}))};s=!0,ae.seek(R=>{if(d()){if(F=ge(),!R){k();return}Z=R,!(0,Ve.isNullable)(E)||R.startTS>E?Ie(R):(te=R,Y())}},E),e.cachedHeader?wt(e.cachedHeader):p(e.headerUrl,wt,()=>this._handleNetworkError())},stop:P,getTimestampSec:()=>n},l}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,Ve.isNonNullable)(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Ve.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ve.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=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=ge();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&&Ko(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&c(),h},notifySwitch:d=>{let p=ge();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Rr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ls).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;$e(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,c)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},_x))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var oe=require("@vkontakte/videoplayer-shared"),Zo=class{constructor(){this.onDroopedVideoFramesLimit$=new oe.Subject;this.subscription=new oe.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new oe.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,oe.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,oe.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,oe.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,oe.interval)(this.droppedFramesChecker.checkTime).pipe((0,oe.filter)(()=>this.playing),(0,oe.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,oe.debounce)(this.droppedFramesChecker.checkTime)),r=(0,oe.merge)(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,oe.isLower)(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ds=Zo;var ps=require("@vkontakte/videoplayer-shared"),em=require("@vkontakte/videoplayer-shared");var wi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Ux=(a,e)=>new ps.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||wi()))},C(C({},r),e));i.observe(a);let s=(0,em.fromEvent)(document,"visibilitychange").pipe((0,ps.map)(n=>!document.hidden||wi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ge=Ux;var Hx=["paused","playing","ready"],jx=["paused","playing","ready"],ki=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new j("stopped");this.representations$=new V.ValueSubject([]);this.textTracksManager=new je;this.droppedFramesManager=new ds;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new mt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:V.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=(r=Dt(u.name))!=null?r:(0,V.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p=C({},u.video);if(!l)continue;let h={id:c,quality:l,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,V.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(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(jx.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Hx.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Se(this.params.source.url,u))}return;default:return(0,V.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:V.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,V.merge)(this.videoState.stateChangeStarted$.pipe((0,V.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,V.map)(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(be(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Re(this.video);this.subscription.add(this.representations$.pipe((0,V.map)(i=>i.map(({track:s})=>s)),(0,V.filter)(i=>!!i.length),(0,V.once)()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,V.filterChanged)(),(0,V.map)(i=>-i/1e3)).subscribe(this.params.output.duration$)).add((0,V.combine)({zeroTime:this.zeroTime$.pipe((0,V.filter)(V.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(nt(this.video,this.params.desiredState.isLooped,t)).add(ke(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(He(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ge(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&(0,V.videoQualityToHeight)(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,V.assertNever)(i.to)}},t)).add((0,V.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,V.observableFrom)(["init"])).pipe((0,V.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),we(this.video)}createLiveDashPlayer(){let e=new Ai({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(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&(0,V.isNonNullable)(t)?t:Bt(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=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let g=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;(0,V.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;(0,V.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(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Se(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var tm=ki;var St=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var U=require("@vkontakte/videoplayer-shared");var hs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},$r=class extends hs{constructor(){super(),this.listeners||hs.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)}},Ri=class{constructor(){Object.defineProperty(this,"signal",{value:new $r,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ri.prototype[Symbol.toStringTag]="AbortController",$r.prototype[Symbol.toStringTag]="AbortSignal");function fs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function eu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!fs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(c,l){let d;l&&l.signal&&(d=l.signal,delete l.signal);let p=new t(c,l);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,c)=>{let l=s&&s.prototype.isPrototypeOf(u)?u.signal:c?c.signal:void 0;if(l){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(l.aborted)return Promise.reject(d);let p=new Promise((h,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 $i=fs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),rm=$i?eu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,vt=$i?rm.fetch:window.fetch,IL=$i?rm.Request:window.Request,yt=$i?Ri:window.AbortController,EL=$i?$r:window.AbortSignal;var mm=ze(Ti(),1);var Tt=()=>window.ManagedMediaSource||window.MediaSource,ms=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},im=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},am=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ut=require("@vkontakte/videoplayer-shared");var We=document.createElement("video"),Yx='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Qx='video/mp4; codecs="hev1.1.6.L93.B0"',bm='video/webm; codecs="vp09.00.10.08"',gm='video/webm; codecs="av01.0.00M.08"',zx='audio/mp4; codecs="mp4a.40.2"',Kx='audio/webm; codecs="opus"',sm,nm,Jt={mms:ms(),mse:im(),hls:!!((sm=We.canPlayType)!=null&&sm.call(We,"application/x-mpegurl")||(nm=We.canPlayType)!=null&&nm.call(We,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},om,um,Le={mp4:!!((om=We.canPlayType)!=null&&om.call(We,"video/mp4")),webm:!!((um=We.canPlayType)!=null&&um.call(We,"video/webm")),cmaf:!0},gs,cm,Ss,lm,vs,dm,ys,pm,Ts,hm,Is,fm,Me={h264:!!((cm=(gs=Tt())==null?void 0:gs.isTypeSupported)!=null&&cm.call(gs,Yx)),h265:!!((lm=(Ss=Tt())==null?void 0:Ss.isTypeSupported)!=null&&lm.call(Ss,Qx)),vp9:!!((dm=(vs=Tt())==null?void 0:vs.isTypeSupported)!=null&&dm.call(vs,bm)),av1:!!((pm=(ys=Tt())==null?void 0:ys.isTypeSupported)!=null&&pm.call(ys,gm)),aac:!!((hm=(Ts=Tt())==null?void 0:Ts.isTypeSupported)!=null&&hm.call(Ts,zx)),opus:!!((fm=(Is=Tt())==null?void 0:Is.isTypeSupported)!=null&&fm.call(Is,Kx))},Lr=(Me.h264||Me.h265)&&Me.aac,Xt,Jx=()=>O(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(z(C({},a),{video:z(C({},a.video),{contentType:gm})})),window.navigator.mediaCapabilities.decodingInfo(z(C({},a),{video:z(C({},a.video),{contentType:bm})}))]);Xt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{Jx()}catch(a){console.error(a)}var Mr=Jt.hls&&Le.mp4,Sm=()=>Object.keys(Me).filter(a=>Me[a]),vm=(a,e=!1,t=!1)=>{let r=Jt.mse||Jt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&Le.mp4&&Lr;case"DASH_WEBM":return r&&Le.webm&&Me.vp9&&Me.opus;case"DASH_WEBM_AV1":return r&&Le.webm&&Me.av1&&Me.opus;case"DASH_STREAMS":return r&&(Le.mp4&&Lr||Le.webm&&(Me.vp9||Me.av1)&&(Me.opus||Me.aac));case"DASH_LIVE":return Jt.mse&&Le.mp4&&Lr;case"DASH_LIVE_CMAF":return r&&Le.mp4&&Lr&&Le.cmaf;case"DASH_ONDEMAND":return r&&Le.mp4&&Lr;case"HLS":case"HLS_ONDEMAND":return Mr||e&&Jt.mse&&Le.mp4&&Lr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Mr;case"MPEG":return Le.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Jt.webrtc&&Jt.ws&&Me.h264&&(Le.mp4||Le.webm);default:return(0,ut.assertNever)(i)}})},bs=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Xt?Xt[t].smooth?[t,e]:Xt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Xt?Xt[t].powerEfficient?[t,e]:Xt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,ut.assertNever)(a)}return[e,t]},ym=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...bs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ut.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...bs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...bs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...bs(a),...i,"HLS","HLS_ONDEMAND"];default:(0,ut.assertNever)(e)}return Mr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Tm=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=ut.clientChecker.isMac&&ut.clientChecker.isSafari;if(ut.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,ut.assertNever)(a)}else Mr&&!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"]},tu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Im=a=>{if(a.size!==0){if(a.size===1)return a.values().next().value.split(".").at(0);for(let e of a){let t=(0,mm.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};var Cr=require("@vkontakte/videoplayer-shared"),Em=a=>{if(!a)return{id:"EmptyResponse",category:Cr.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Cr.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:Cr.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:Cr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Cr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Dr=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared");var Fr=ze(Ti(),1);var Xx=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},Zx=a=>window.clearTimeout(a),xm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ru=xm?Xx:window.requestIdleCallback,OL=xm?Zx:window.cancelIdleCallback;var lb=ze(ns(),1);var Ye=require("@vkontakte/videoplayer-shared");var eP=16,Pm=!1;try{Pm=Ye.clientChecker.isSafari&&!!Ye.clientChecker.macVersion&&Ye.clientChecker.macVersion<=eP}catch(a){console.error(a)}var iu=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)}append(e,t){return O(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return O(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return O(this,null,function*(){return new Promise(t=>{let r;Pm&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category: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)}}},Am=iu;var au=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var x=require("@vkontakte/videoplayer-shared");var re=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Br=class extends re{};var Li=class extends re{};var Mi=class extends re{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var Ci=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends re{constructor(e,t){super(e,t),this.data=this.content}};var de=class extends re{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Zt=class extends de{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}};var Oi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends de{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ni=class extends de{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Fi=class extends de{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var qi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends de{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Hi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends de{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Wi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yi=class extends de{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Qi=class extends de{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var zi=class extends de{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var rP={ftyp:Mi,moov:Ci,moof:Di,mdat:Bi,sidx:Zt,trak:Oi,mdia:qi,mfhd:Gi,tkhd:Ui,traf:Wi,tfhd:Yi,tfdt:Qi,trun:zi,minf:Hi,sv3d:Vi,st3d:_i,prhd:Ni,proj:ji,equi:Fi,uuid:Li,unknown:Br},er=class a{constructor(e={}){this.options=C({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=rP[e];return r?new r(t,new a):new Br(t,new a)}};var Or=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var aP=new TextDecoder("ascii"),sP=a=>aP.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",nP=a=>{let e=new Zt(a,new er),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},oP=(a,e)=>{let r=new er().parse(a),i=new Or(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,d)},uP=(a,e)=>{let r=new er().parse(a),s=new Or(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),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},cP=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new er().parse(a),i=new Or(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},wm={validateData:sP,parseInit:cP,getIndexRange:()=>{},parseSegments:nP,parseFeedableSegmentChunk:oP,getSegmentEndTime:uP};var It=require("@vkontakte/videoplayer-shared");var Rm=require("@vkontakte/videoplayer-shared");var km={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"}},$m=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Ki(a,t),i=r in km,s=i?km[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,l=Ki(u),d=c*it(2,(o-1)*8)+l,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Ki=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*it(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*it(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*it(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},et=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ki(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:(0,Rm.assertNever)(e)}},tr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=$m(r);if(!e(i))return;i.type==="master"&&tr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Lm=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=$m(a);return tr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=et(o,n):s===17026?t=et(o,n):s===17029&&(r=et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Mm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],lP=[231,22612,22743,167,171,163,160,175],dP=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,c,l=!1,d=0;return tr(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let S=et(m,h);c=Ki(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?r=et(m,h):p===17545?i=et(m,h):p===21420&&c===475249515?u=et(m,h):p===374648427?tr(m,({tag:S,type:T,value:P})=>S===30321?(l=et(P,T)===1,!1):!0):s&&n&&Mm.includes(p)&&(o=!0),!o}),(0,It.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,It.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,It.assertNonNullable)(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},pP=a=>{if((0,It.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},hP=(a,e)=>{let t=!1,r=!1,i=o=>(0,It.isNonNullable)(o.time)&&(0,It.isNonNullable)(o.position),s=[],n;return tr(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=et(c,u));break;case 183:break;case 241:n&&(n.position=et(c,u));break;default:t&&Mm.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:l}=o,d=s[u+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},fP=a=>{let e=0,t=!1;try{tr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):lP.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Cm={validateData:Lm,parseInit:dP,getIndexRange:pP,parseSegments:hP,parseFeedableSegmentChunk:fP};var Vr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Cm;case"mp4":return wm}}throw new ReferenceError(`Unsupported mime type ${a}`)};var pu=ze(tb(),1);var du=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var Nr=require("@vkontakte/videoplayer-shared");var rb=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var ib=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},rr=(a,e)=>{let t=a;t=(0,pu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,pu.default)(t,n,(o,u)=>(0,Nr.isNullable)(s)?o:(0,Nr.isNullable)(u)?s:s.padStart(parseInt(u,10),"0"))}return t},sb=(a,e)=>{var E,A,_,ae,Q,W,te,Z,F,ee,K,M,k,Y,se,ue,pe,Ie,Vt,wt,R,Ee,Ce,Ne,kt,or,Rt,_t,ur,Hr,Pu,Au,wu,ku,Ru,$u,Lu,Mu,Cu,Du,Bu,Ou,Vu,_u,Nu,Fu,qu,Uu,Hu,ju;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(_=(A=(E=s.querySelector("BaseURL"))==null?void 0:E.textContent)==null?void 0:A.trim())!=null?_:"",u=n.children,c=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=l?new Date(l).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],S=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=ib(h);else if(m){let xe=ib(m);(0,Nr.isNonNullable)(xe)&&(p=xe)}else S&&(p=parseInt(S,10));let T=0,P=(Q=(ae=s.getAttribute("profiles"))==null?void 0:ae.split(","))!=null?Q:[];for(let xe of u){let Ob=(W=xe.getAttribute("id"))!=null?W:"id"+(T++).toString(10),jr=(te=xe.getAttribute("mimeType"))!=null?te:"",_s=(Z=xe.getAttribute("codecs"))!=null?Z:"",Ns=(F=xe.getAttribute("contentType"))!=null?F:jr==null?void 0:jr.split("/")[0],Vb=(K=(ee=xe.getAttribute("profiles"))==null?void 0:ee.split(","))!=null?K:[],_b=(M=xe.getAttribute("lang"))!=null?M:void 0,Nb=(se=(Y=(k=xe.querySelector("Label"))==null?void 0:k.textContent)==null?void 0:Y.trim())!=null?se:void 0,Fb=xe.querySelectorAll("Representation"),qb=xe.querySelector("SegmentTemplate"),Ub=(pe=(ue=xe.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?pe:void 0,Gr=Ns,fe={id:Ob,language:_b,isDefault:Ub==="main",label:Nb,codecs:_s,hdr:Gr==="video"&&du(_s),mime:jr,representations:[]};for(let he of Fb){let Hb=(Ie=he.getAttribute("lang"))!=null?Ie:void 0,jb=(Vt=he.getAttribute("label"))!=null?Vt:void 0,Gb=(Ee=(R=(wt=he.querySelector("BaseURL"))==null?void 0:wt.textContent)==null?void 0:R.trim())!=null?Ee:"",Fs=new URL(Gb||o,e).toString(),cr=(Ce=he.getAttribute("mimeType"))!=null?Ce:jr,ga=(kt=(Ne=he.getAttribute("codecs"))!=null?Ne:_s)!=null?kt:"",qs;if(Ns==="text"){let Nt=he.getAttribute("id")||"",Us=Nt.includes("_auto");qs={id:Nt,isAuto:Us,kind:"text",url:Fs}}else{let Nt=(Rt=(or=he.getAttribute("contentType"))!=null?or:cr==null?void 0:cr.split("/")[0])!=null?Rt:Ns,Us=(ur=(_t=xe.getAttribute("profiles"))==null?void 0:_t.split(","))!=null?ur:[],Wb=parseInt((Hr=he.getAttribute("width"))!=null?Hr:"",10),Gu=parseInt((Pu=he.getAttribute("height"))!=null?Pu:"",10),Wu=parseInt((Au=he.getAttribute("bandwidth"))!=null?Au:"",10)/1e3,Yu=(wu=he.getAttribute("frameRate"))!=null?wu:"",Yb=(ku=he.getAttribute("quality"))!=null?ku:void 0,Qb=Yu?rb(Yu):void 0,zb=(Ru=he.getAttribute("id"))!=null?Ru:"id"+(T++).toString(10),Kb=Nt==="video"?`${Gu}p`:Nt==="audio"?`${Wu}Kbps`:ga,Jb=`${zb}@${Kb}`,Xb=[...P,...Vb,...Us],Hs,Zb=he.querySelector("SegmentBase"),Ft=($u=he.querySelector("SegmentTemplate"))!=null?$u:qb;if(Zb){let qt=(Mu=(Lu=he.querySelector("SegmentBase Initialization"))==null?void 0:Lu.getAttribute("range"))!=null?Mu:"",[Ut,Gs]=qt.split("-").map(lr=>parseInt(lr,10)),$t={from:Ut,to:Gs},Wr=(Cu=he.querySelector("SegmentBase"))==null?void 0:Cu.getAttribute("indexRange"),[Ws,Sa]=Wr?Wr.split("-").map(lr=>parseInt(lr,10)):[],Yr=Wr?{from:Ws,to:Sa}:void 0;Hs={type:"byteRange",url:Fs,initRange:$t,indexRange:Yr}}else if(Ft){let qt={representationId:(Du=he.getAttribute("id"))!=null?Du:void 0,bandwidth:(Bu=he.getAttribute("bandwidth"))!=null?Bu:void 0},Ut=parseInt((Ou=Ft.getAttribute("timescale"))!=null?Ou:"",10),Gs=(Vu=Ft.getAttribute("initialization"))!=null?Vu:"",$t=Ft.getAttribute("media"),Wr=(Nu=parseInt((_u=Ft.getAttribute("startNumber"))!=null?_u:"",10))!=null?Nu:1,Ws=rr(Gs,qt);if(!$t)throw new ReferenceError("No media attribute in SegmentTemplate");let Sa=(Fu=Ft.querySelectorAll("SegmentTimeline S"))!=null?Fu:[],Yr=[],lr=0,Ys="",Qs=0;if(Sa.length){let va=Wr,Qe=0;for(let dr of Sa){let rt=parseInt((qu=dr.getAttribute("d"))!=null?qu:"",10),Ht=parseInt((Uu=dr.getAttribute("r"))!=null?Uu:"",10)||0,ya=parseInt((Hu=dr.getAttribute("t"))!=null?Hu:"",10);Qe=Number.isFinite(ya)?ya:Qe;let zs=rt/Ut*1e3,Ks=Qe/Ut*1e3;for(let Ta=0;Ta<Ht+1;Ta++){let tg=rr($t,z(C({},qt),{segmentNumber:va.toString(10),segmentTime:(Qe+Ta*rt).toString(10)})),Qu=(Ks!=null?Ks:0)+Ta*zs,rg=Qu+zs;va++,Yr.push({time:{from:Qu,to:rg},url:tg})}Qe+=(Ht+1)*rt,lr+=(Ht+1)*zs}Qs=Qe/Ut*1e3,Ys=rr($t,z(C({},qt),{segmentNumber:va.toString(10),segmentTime:Qe.toString(10)}))}else if((0,Nr.isNonNullable)(p)){let Qe=parseInt((ju=Ft.getAttribute("duration"))!=null?ju:"",10)/Ut*1e3,dr=Math.ceil(p/Qe),rt=0;for(let Ht=1;Ht<dr;Ht++){let ya=rr($t,z(C({},qt),{segmentNumber:Ht.toString(10),segmentTime:rt.toString(10)}));Yr.push({time:{from:rt,to:rt+Qe},url:ya}),rt+=Qe}Qs=rt,Ys=rr($t,z(C({},qt),{segmentNumber:dr.toString(10),segmentTime:rt.toString(10)}))}let eg={time:{from:Qs,to:1/0},url:Ys};Hs={type:"template",baseUrl:Fs,segmentTemplateUrl:$t,initUrl:Ws,totalSegmentsDurationMs:lr,segments:Yr,nextSegmentBeyondManifest:eg,timescale:Ut}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Nt||!cr)continue;let js={video:"video",audio:"audio",text:"text"}[Nt];if(!js)continue;Gr||(Gr=js),qs={id:Jb,kind:js,segmentReference:Hs,profiles:Xb,duration:p,bitrate:Wu,mime:cr,codecs:ga,width:Wb,height:Gu,fps:Qb,quality:Yb}}fe.language||(fe.language=Hb),fe.label||(fe.label=jb),fe.mime||(fe.mime=cr),fe.codecs||(fe.codecs=ga),fe.hdr||(fe.hdr=Gr==="video"&&du(ga)),fe.representations.push(qs)}Gr&&i[Gr].push(fe)}return{dynamic:c,liveAvailabilityStartTime:d,duration:p,streams:i}};var Ji=ze(Ti(),1);var nb=require("@vkontakte/videoplayer-shared"),ob=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?Dt(s):void 0)!=null?o:(0,nb.videoSizeToQuality)({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},ub=({id:a,bitrate:e})=>({id:a,bitrate:e}),Es=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Ji.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Ji.default)(t,-1)},cb=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),fu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Ji.default)(r.split("."),0),isDefault:i}),mu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Ji.default)(i.split("."),0)}),xs=a=>"url"in a,Et=a=>a.type==="template",Xi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Zi=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new x.ValueSubject(0);this.onLastSegment$=new x.ValueSubject(!1);this.fullyBuffered$=new x.ValueSubject(!1);this.playingRepresentation$=new x.ValueSubject(void 0);this.playingRepresentationInit$=new x.ValueSubject(void 0);this.error$=new x.Subject;this.gaps=[];this.subscription=new x.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new yt;this.destroyAbortController=new yt;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,x.abortable)(this.destroyAbortController.signal,function(e){return me(this,null,function*(){let t=this.representations.get(e);(0,x.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 Am(this.sourceBuffer),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.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,au(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=St(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,c<l)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,x.assertNonNullable)(r,"No init buffer for starting representation"),(0,x.assertNonNullable)(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=(0,x.abortable)(this.destroyAbortController.signal,function(e,t=!1){return me(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,x.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,x.isNullable)(s)||(0,x.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,x.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,x.isNonNullable)(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),yield new Xs(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,x.abortable)(this.destroyAbortController.signal,function(e){return me(this,null,function*(){var u,c;let t=(u=e==null?void 0:e.flatMap(l=>l.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let d=t.find(m=>m.id===l);d&&this.representations.set(l,d);let p=this.representations.get(l);if(!p||!Et(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(c=this.switchingToRepresentationId)!=null?c:this.downloadingRepresentationId,i=this.representations.get(r);(0,x.assertNonNullable)(i);let s=this.segments.get(r);(0,x.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,x.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,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.dynamic),this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new yt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;if((0,x.isNullable)(e)||(0,x.isNullable)(this.downloadingRepresentationId)||(0,x.isNullable)(this.playingRepresentationId)||(0,x.isNullable)(this.sourceBuffer)||!(0,x.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,x.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((c=i==null?void 0:i.time.to)!=null?c:0)-((l=i==null?void 0:i.time.from)!=null?l:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=St(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&au(this.sourceBuffer.buffered)>=this.bufferLimit){let d=St(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let p=(0,Fr.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&St(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Fr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;(0,x.isNonNullable)(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!Et(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>z(C({},p),{status:"none",size:void 0})),c=(i=this.segments.get(o.id))!=null?i:[],l=(n=(s=(0,Fr.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,x.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Et(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),c=rr(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let g=p<=r&&h>=r,S=p>r||g||m===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),P=this.preloadOnly&&p<=r+T||h<=r+T;return(d==="none"||d==="partially_ejected"&&S&&P&&this.sourceBuffer&&!(Dr(this.sourceBuffer.buffered,p)&&Dr(this.sourceBuffer.buffered,h)))&&S&&P});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=c||o<=l);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return O(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return O(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,x.abortable)(o,function(){return me(this,null,function*(){let l=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!l)return;let d=new DataView(l);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=Vr(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&c?yield Promise.all(c):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Xi(l)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return O(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,x.abortable)(n,function(){return me(this,null,function*(){let u=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),(0,x.fromEvent)(window,"online").pipe((0,x.once)()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Xi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(Et(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Fr.default)(e,0).byte.from,to:(0,Fr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Et(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,l)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return O(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Vr(o.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(c.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,c=e.byteLength;for(let l of this.activeSegments){let{segment:d}=l,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:c;if(l.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let g=p?d.byte.from-r:0,S=p?d.byte.to-r:e.byteLength,T=g<i,P=S<=i;if(d.status==="downloading"&&T&&P){d.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+g,h),E=this.getCurrentPosition();(0,x.isNonNullable)(E)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-E,this.bufferAccumulation.accumulated.push({segmentView:I,segmentProgress:l}),this.activeSegments.delete(l));let A=({segmentView:_,segmentProgress:ae})=>this.sourceBufferTaskQueue.append(_,s).then(Q=>Q&&!s.aborted?this.onSegmentFullyAppended(ae,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(A),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||(0,x.isNullable)(E))&&(A({segmentView:I,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&!P&&(l.loadedBytes=Math.min(h,i-g),l.loadedBytes>l.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+g+l.feedingBytes,l.loadedBytes-l.feedingBytes),E=l.loadedBytes===h?I:Vr(o.mime).parseFeedableSegmentChunk(I);E!=null&&E.byteLength&&(d.status="partially_fed",l.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,s).then(A=>{if(s.aborted)n();else if(A)l.fedBytes+=E.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return O(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let c of this.activeSegments){let{segment:l}=c;if(c.representationId!==t)continue;if(s.aborted){n();continue}let d=l.byte.from-r,p=l.byte.to-r,h=p-d+1,m=d<i,g=p<=i;if(m){if(l.status==="downloading"&&g){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?this.onSegmentFullyAppended(c,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(c.loadedBytes=Math.min(h,i-d),c.loadedBytes>c.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+c.feedingBytes,c.loadedBytes-c.feedingBytes),T=c.loadedBytes===h?S:Vr(u.mime).parseFeedableSegmentChunk(S);T!=null&&T.byteLength&&(l.status="partially_fed",c.feedingBytes+=T.byteLength,(yield this.sourceBufferTaskQueue.append(T,s))&&!s.aborted?(c.fedBytes+=T.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t)):n())}}}})}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",xs(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&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,x.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[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=ru(()=>(0,lb.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return O(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,x.abortable)(this.destroyAbortController.signal,function(){return me(this,null,function*(){let o=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Vr(e.mime),i)).then(o=>O(this,null,function*(){if(!o)return;let{init:u,dataView:c,segments:l}=o,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d);let p=l;this.isLive&&Et(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:x.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return O(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return O(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return O(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.isNullable)(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((l,d)=>l.from-d.from);let c=[u[0]];for(let l=1;l<u.length;l++){let{from:d,to:p}=u[l],h=c[c.length-1];h.to>=d?h.to=Math.max(h.to,p):c.push(u[l])}return c},o=u=>{var l;if(s>=t)return i;i.push(C({},u.time)),i=n(i);let c=xs(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let l=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let p={time:{from:c,to:l},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>=e+u&&l.status==="fed"&&o(l)}return i.length?(yield Promise.all(i.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1})}pruneBufferOld(e,t,r=!1){return O(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.isNullable)(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=c=>{var d;s=Math.min(s,c.time.from),n=Math.max(n,c.time.to);let l=xs(c)?(d=c.size)!=null?d:0:c.byte.to-c.byte.from;i+=l};for(let c of this.segments.values())for(let l of c){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;l.status==="fed"&&u(l)}if(o=isFinite(s)&&isFinite(n),!o){i=0,s=1/0,n=-1/0;for(let c of this.segments.values())for(let l of c){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;l.status==="fed"&&u(l)}}if(o=isFinite(s)&&isFinite(n),!o)for(let c=0;c<this.sourceBuffer.buffered.length;c++){let l=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)){s=l,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){i=0,s=1/0,n=-1/0;let c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>e+c&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){(0,x.assertNonNullable)(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=ru(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:x.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,x.isNullable)(this.sourceBuffer)||(0,x.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=10;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),c=e.filter(l=>n>=l.from&&n<l.to-t||o>l.from+t&&o<=l.to);u||(c.length===1?i.status="partially_ejected":this.gaps.some(l=>l.from===i.time.from||l.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var ea=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var db=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};var J=require("@vkontakte/videoplayer-shared");var Ps=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new J.ValueSubject(void 0);this.lastConnectionReused$=new J.ValueSubject(void 0);this.lastRequestFirstBytes$=new J.ValueSubject(void 0);this.abortAllController=new yt;this.subscription=new J.Subscription;this.fetchManifest=(0,J.abortable)(this.abortAllController.signal,function(e){return me(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ea(r));let i=yield vt(r,{signal:this.abortAllController.signal}).catch(ta);return i?(t.log("success",(0,J.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",(0,J.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,J.abortable)(this.abortAllController.signal,function(c){return me(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var F,ee;let l=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let K=new URL(l,location.href);K.searchParams.append("bytes",`${r.from}-${r.to}`),l=K.toString();break}default:(0,J.assertNever)(t)}this.requestQuic&&(l=ea(l));let h=this.abortAllController.signal,m;if(n){let K=new yt;if(m=(0,J.merge)((0,J.fromEvent)(this.abortAllController.signal,"abort"),(0,J.fromEvent)(n,"abort")).subscribe(()=>{try{K.abort()}catch(M){ta(M)}}),this.abortAllController.signal.aborted||n.aborted)try{K.abort()}catch(M){ta(M)}h=K.signal}let g=(0,J.now)();p.log("startRequest",(0,J.flattenObject)({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:g}));let S=yield vt(l,{priority:s,headers:d,signal:h}).catch(ta),T=(0,J.now)();if(!S)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((F=this.throughputEstimator)==null||F.addRawRtt(T-g),!S.ok||!S.body){m==null||m.unsubscribe();let K=`Fetch error ${S.status}: ${S.statusText}`;return p.error("error",{message:K}),p.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!i&&!o){m==null||m.unsubscribe();let K=(0,J.now)(),M={requestStartedAt:g,requestEndedAt:K,duration:K-g};return p.log("endRequest",(0,J.flattenObject)(M)),p.end(),S.arrayBuffer()}let[P,I]=S.body.tee(),E=P.getReader();o&&((ee=this.throughputEstimator)==null||ee.trackStream(I,u));let A=0,_=new Uint8Array(0),ae=!1,Q=K=>{m==null||m.unsubscribe(),ae=!0,ta(K)},W=(0,J.abortable)(h,function(k){return me(this,arguments,function*({done:K,value:M}){if(A===0&&this.lastRequestFirstBytes$.next((0,J.now)()-g),h.aborted){m==null||m.unsubscribe();return}if(!K&&M){let Y=new Uint8Array(_.length+M.length);Y.set(_),Y.set(M,_.length),_=Y,A+=M.byteLength,i==null||i(new DataView(_.buffer),A),yield E==null?void 0:E.read().then(W,Q)}})}.bind(this));yield E==null?void 0:E.read().then(W,Q),m==null||m.unsubscribe();let te=(0,J.now)(),Z={failed:ae,requestStartedAt:g,requestEndedAt:te,duration:te-g};return ae?(p.error("endRequest",(0,J.flattenObject)(Z)),p.end(),null):(p.log("endRequest",(0,J.flattenObject)(Z)),p.end(),_.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,J.abortable)(this.abortAllController.signal,function(e,t,r){return me(this,null,function*(){var T;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,i),o=Math.max(l,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(T=e.indexRange)!=null?T: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 P=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!P)return null;g=new DataView(P)}let S=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,J.abortable)(this.abortAllController.signal,function(e,t){return me(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>z(C({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=db(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return O(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,J.assertNever)(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ta=a=>{if(!Xi(a))throw a};var ir=(a,e,t)=>t*e+(1-t)*a,bu=(a,e)=>a.reduce((t,r)=>t+r,0)/e,pb=(a,e,t,r)=>{let i=0,s=t,n=bu(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};var ra=require("@vkontakte/videoplayer-shared");var Ot=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new ra.ValueSubject(e.initial),this.debounced$=new ra.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Te(`raw_${t}`),this.smoothedSeries$=new Te(`smoothed_${t}`),this.reportedSeries$=new Te(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=it(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,ra.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 As=class extends Ot{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ir(this.slow,e,this.params.emaAlphaSlow),this.fast=ir(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ws=class extends Ot{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=bu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ir(this.emaSmoothed,e,this.params.emaAlpha);let r=pb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var ks=class extends Ot{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?ir(this.smoothed,t,this.params.emaAlpha):t}};var ar=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new As({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ws({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ks(C({initial:e,label:"liveEdgeDelay"},t))}};var gu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var fb=["timeupdate","progress","play","seeked","stalled","waiting"];var Rs=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.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.timeInWaiting=0;this.isActiveLowLatency$=new v.ValueSubject(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new yt;this.initManifest=(0,v.abortable)(this.destroyController.signal,function(e,t,r){return me(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Se(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,function(){return me(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t;try{t=sb(e!=null?e:"",this.manifestUrlString)}catch(u){let c=(n=Em(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 r=(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=Tt())==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 i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let l=t.streams[u].filter(({mime:h,codecs:m})=>r(u,h,m)),d=new Set(l.map(({codecs:h})=>h)),p=Im(d);if(p&&(i[u]=l.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=i.video.some(S=>S.hdr),g=i.video.some(S=>!S.hdr);v.clientChecker.isHDR&&h&&m?i.video=i.video.filter(S=>S.hdr):g&&(i.video=i.video.filter(S=>!S.hdr))}}let s=z(C({},t),{streams:i});return this.tracer.log("updateManifestEnd",(0,v.flattenObject)(s)),s})}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,function(e,t,r){return me(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",(0,v.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=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?am():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ms())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Zi("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 Zi("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,v.interval)(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=qo(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add((0,v.merge)(...fb.filter(p=>p!=="waiting").map(p=>(0,v.fromEvent)(this.element,p))).pipe((0,v.map)(p=>this.element?St(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.filter)(p=>!!p),(0,v.tap)(p=>{var h;(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=>gu(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,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,P=h-g,I=1;Math.abs(P)>S&&(I=1+Math.sign(P)*T),gu(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let m=0;if(h){let T=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var E,A;return(A=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?A:T}))-T}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(g=>O(this,[g],function*({liveLoadBufferLength:h,bufferLength:m}){if((0,v.assertNonNullable)(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,T=qo(this.manifestUrlString,2),P=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(P,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,A=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,_=isFinite(h)?h:m,ae=this.isActiveLowLatency$.getValue(),Q=P<=this.tuning.live.activeLiveDelay&&T===0;this.isActiveLowLatency$.next(ae&&Q);let W="none";if(ae?W="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&Q?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(te=>te.proceedLowLatencyLive()),W="active_low_latency"):T!==0&&_<I?W="live_forward_buffering":_<I+A&&(W="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),W==="live_forward_buffering"||W==="live_with_target_offset"){let te=p-(I+E),Z=this.normolizeLiveOffset(Math.trunc(T+te/S)),F=Math.abs(Z-T),ee;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?ee=T:Z>0&&F>this.tuning.dashCmafLive.offsetCalculationError?ee=Z:ee=0,this.manifestUrlString=Se(this.manifestUrlString,ee,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.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),Et(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,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Ps({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=ar.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,C({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return O(this,null,function*(){var r,i,s,n;(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=Se(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio))})}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...fb.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,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Dr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var n,o;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s=z(C({},s),{liveLastSeekOffset:this.liveLastSeekOffset});else{let u=this.element.currentTime*1e3;(n=this.videoBufferManager)==null||n.maintain(u),(o=this.audioBufferManager)==null||o.maintain(u),s=z(C({},s),{position:u})}this.tracer.log("stallIntervalCallback",(0,v.flattenObject)(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return O(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u,c;(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Dr(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(c=this.audioBufferManager)==null||c.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,v.flattenObject)({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,v.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return O(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=z(C({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,v.flattenObject)(t)))}}};var $s=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ls=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/it(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=C({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*it(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var mb=`attribute vec2 a_vertex;
59
59
  attribute vec2 a_texel;
60
60
 
61
61
  varying vec2 v_texel;