@vkontakte/videoplayer-core 2.0.117-dev.d9cc3d97.0 → 2.0.117
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +18 -19
- package/es2015.esm.js +17 -18
- package/es2018.cjs.js +21 -22
- package/es2018.esm.js +20 -21
- package/esnext.cjs.js +17 -18
- package/esnext.esm.js +11 -12
- package/evergreen.esm.js +15 -16
- package/package.json +2 -2
- package/types/player/Player.d.ts +0 -1
- package/types/player/types.d.ts +0 -2
- package/types/providers/HlsLiveProvider/index.d.ts +0 -2
- package/types/providers/HlsProvider/manifestDataExtractor.d.ts +1 -1
- package/types/providers/types.d.ts +0 -1
- package/types/utils/tuningConfig.d.ts +0 -2
- package/types/providers/HlsLiveProvider/LiveTextManager.d.ts +0 -42
package/es2015.cjs.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.117
|
|
3
|
-
* Thu, 14 Nov 2024
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.117
|
|
3
|
+
* Thu, 14 Nov 2024 11:50:27 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-117/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Pg=Object.create;var or=Object.defineProperty,Ag=Object.defineProperties,wg=Object.getOwnPropertyDescriptor,kg=Object.getOwnPropertyDescriptors,Rg=Object.getOwnPropertyNames,ja=Object.getOwnPropertySymbols,$g=Object.getPrototypeOf,pn=Object.prototype.hasOwnProperty,Il=Object.prototype.propertyIsEnumerable;var Lg=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var pt=Math.pow,Tl=(a,e,t)=>e in a?or(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,R=(a,e)=>{for(var t in e||(e={}))pn.call(e,t)&&Tl(a,t,e[t]);if(ja)for(var t of ja(e))Il.call(e,t)&&Tl(a,t,e[t]);return a},j=(a,e)=>Ag(a,kg(e));var El=(a,e)=>{var t={};for(var i in a)pn.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&ja)for(var i of ja(a))e.indexOf(i)<0&&Il.call(a,i)&&(t[i]=a[i]);return t};var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Mg=(a,e)=>{for(var t in e)or(a,t,{get:e[t],enumerable:!0})},xl=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Rg(e))!pn.call(a,r)&&r!==t&&or(a,r,{get:()=>e[r],enumerable:!(i=wg(e,r))||i.enumerable});return a};var Ge=(a,e,t)=>(t=a!=null?Pg($g(a)):{},xl(e||!a||!a.__esModule?or(t,"default",{value:a,enumerable:!0}):t,a)),Dg=a=>xl(or({},"__esModule",{value:!0}),a);var $=(a,e,t)=>new Promise((i,r)=>{var s=u=>{try{o(t.next(u))}catch(l){r(l)}},n=u=>{try{o(t.throw(u))}catch(l){r(l)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),hn=function(a,e){this[0]=a,this[1]=e},he=(a,e,t)=>{var i=(n,o,u,l)=>{try{var d=t[n](o),c=(o=d.value)instanceof hn,p=d.done;Promise.resolve(c?o[0]:o).then(h=>c?i(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>i("throw",h,u,l))}catch(h){l(h)}},r=n=>s[n]=o=>new Promise((u,l)=>i(n,o,u,l)),s={};return t=t.apply(a,e),s[Lg("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var _e=b((zA,Al)=>{"use strict";Al.exports=function(a){try{return!!a()}catch(e){return!0}}});var lr=b((KA,wl)=>{"use strict";var Vg=_e();wl.exports=!Vg(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var ke=b((XA,$l)=>{"use strict";var kl=lr(),Rl=Function.prototype,mn=Rl.call,Bg=kl&&Rl.bind.bind(mn,mn);$l.exports=kl?Bg:function(a){return function(){return mn.apply(a,arguments)}}});var Pi=b((JA,Ml)=>{"use strict";var Ll=ke(),Og=Ll({}.toString),_g=Ll("".slice);Ml.exports=function(a){return _g(Og(a),8,-1)}});var Cl=b((ZA,Dl)=>{"use strict";var Ng=ke(),Fg=_e(),Ug=Pi(),bn=Object,qg=Ng("".split);Dl.exports=Fg(function(){return!bn("z").propertyIsEnumerable(0)})?function(a){return Ug(a)==="String"?qg(a,""):bn(a)}:bn});var Ai=b((ew,Vl)=>{"use strict";Vl.exports=function(a){return a==null}});var cr=b((tw,Bl)=>{"use strict";var Hg=Ai(),jg=TypeError;Bl.exports=function(a){if(Hg(a))throw new jg("Can't call method on "+a);return a}});var wi=b((iw,Ol)=>{"use strict";var Gg=Cl(),Qg=cr();Ol.exports=function(a){return Gg(Qg(a))}});var gn=b((rw,_l)=>{"use strict";_l.exports=function(){}});var ai=b((aw,Nl)=>{"use strict";Nl.exports={}});var pe=b((Sn,Fl)=>{"use strict";var dr=function(a){return a&&a.Math===Math&&a};Fl.exports=dr(typeof globalThis=="object"&&globalThis)||dr(typeof window=="object"&&window)||dr(typeof self=="object"&&self)||dr(typeof global=="object"&&global)||dr(typeof Sn=="object"&&Sn)||function(){return this}()||Function("return this")()});var de=b((sw,Ul)=>{"use strict";var vn=typeof document=="object"&&document.all;Ul.exports=typeof vn=="undefined"&&vn!==void 0?function(a){return typeof a=="function"||a===vn}:function(a){return typeof a=="function"}});var jl=b((nw,Hl)=>{"use strict";var Wg=pe(),Yg=de(),ql=Wg.WeakMap;Hl.exports=Yg(ql)&&/native code/.test(String(ql))});var Qe=b((ow,Gl)=>{"use strict";var zg=de();Gl.exports=function(a){return typeof a=="object"?a!==null:zg(a)}});var We=b((uw,Ql)=>{"use strict";var Kg=_e();Ql.exports=!Kg(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ya=b((lw,Yl)=>{"use strict";var Xg=pe(),Wl=Qe(),yn=Xg.document,Jg=Wl(yn)&&Wl(yn.createElement);Yl.exports=function(a){return Jg?yn.createElement(a):{}}});var Tn=b((cw,zl)=>{"use strict";var Zg=We(),eS=_e(),tS=Ya();zl.exports=!Zg&&!eS(function(){return Object.defineProperty(tS("div"),"a",{get:function(){return 7}}).a!==7})});var In=b((dw,Kl)=>{"use strict";var iS=We(),rS=_e();Kl.exports=iS&&rS(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ht=b((pw,Xl)=>{"use strict";var aS=Qe(),sS=String,nS=TypeError;Xl.exports=function(a){if(aS(a))return a;throw new nS(sS(a)+" is not an object")}});var Ne=b((hw,Jl)=>{"use strict";var oS=lr(),za=Function.prototype.call;Jl.exports=oS?za.bind(za):function(){return za.apply(za,arguments)}});var Ka=b((fw,Zl)=>{"use strict";Zl.exports={}});var It=b((mw,tc)=>{"use strict";var En=Ka(),xn=pe(),uS=de(),ec=function(a){return uS(a)?a:void 0};tc.exports=function(a,e){return arguments.length<2?ec(En[a])||ec(xn[a]):En[a]&&En[a][e]||xn[a]&&xn[a][e]}});var pr=b((bw,ic)=>{"use strict";var lS=ke();ic.exports=lS({}.isPrototypeOf)});var ki=b((gw,sc)=>{"use strict";var cS=pe(),rc=cS.navigator,ac=rc&&rc.userAgent;sc.exports=ac?String(ac):""});var An=b((Sw,dc)=>{"use strict";var cc=pe(),Pn=ki(),nc=cc.process,oc=cc.Deno,uc=nc&&nc.versions||oc&&oc.version,lc=uc&&uc.v8,rt,Xa;lc&&(rt=lc.split("."),Xa=rt[0]>0&&rt[0]<4?1:+(rt[0]+rt[1]));!Xa&&Pn&&(rt=Pn.match(/Edge\/(\d+)/),(!rt||rt[1]>=74)&&(rt=Pn.match(/Chrome\/(\d+)/),rt&&(Xa=+rt[1])));dc.exports=Xa});var wn=b((vw,hc)=>{"use strict";var pc=An(),dS=_e(),pS=pe(),hS=pS.String;hc.exports=!!Object.getOwnPropertySymbols&&!dS(function(){var a=Symbol("symbol detection");return!hS(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&pc&&pc<41})});var kn=b((yw,fc)=>{"use strict";var fS=wn();fc.exports=fS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Rn=b((Tw,mc)=>{"use strict";var mS=It(),bS=de(),gS=pr(),SS=kn(),vS=Object;mc.exports=SS?function(a){return typeof a=="symbol"}:function(a){var e=mS("Symbol");return bS(e)&&gS(e.prototype,vS(a))}});var hr=b((Iw,bc)=>{"use strict";var yS=String;bc.exports=function(a){try{return yS(a)}catch(e){return"Object"}}});var Et=b((Ew,gc)=>{"use strict";var TS=de(),IS=hr(),ES=TypeError;gc.exports=function(a){if(TS(a))return a;throw new ES(IS(a)+" is not a function")}});var fr=b((xw,Sc)=>{"use strict";var xS=Et(),PS=Ai();Sc.exports=function(a,e){var t=a[e];return PS(t)?void 0:xS(t)}});var yc=b((Pw,vc)=>{"use strict";var $n=Ne(),Ln=de(),Mn=Qe(),AS=TypeError;vc.exports=function(a,e){var t,i;if(e==="string"&&Ln(t=a.toString)&&!Mn(i=$n(t,a))||Ln(t=a.valueOf)&&!Mn(i=$n(t,a))||e!=="string"&&Ln(t=a.toString)&&!Mn(i=$n(t,a)))return i;throw new AS("Can't convert object to primitive value")}});var at=b((Aw,Tc)=>{"use strict";Tc.exports=!0});var xc=b((ww,Ec)=>{"use strict";var Ic=pe(),wS=Object.defineProperty;Ec.exports=function(a,e){try{wS(Ic,a,{value:e,configurable:!0,writable:!0})}catch(t){Ic[a]=e}return e}});var mr=b((kw,wc)=>{"use strict";var kS=at(),RS=pe(),$S=xc(),Pc="__core-js_shared__",Ac=wc.exports=RS[Pc]||$S(Pc,{});(Ac.versions||(Ac.versions=[])).push({version:"3.38.0",mode:kS?"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 Dn=b((Rw,Rc)=>{"use strict";var kc=mr();Rc.exports=function(a,e){return kc[a]||(kc[a]=e||{})}});var br=b(($w,$c)=>{"use strict";var LS=cr(),MS=Object;$c.exports=function(a){return MS(LS(a))}});var st=b((Lw,Lc)=>{"use strict";var DS=ke(),CS=br(),VS=DS({}.hasOwnProperty);Lc.exports=Object.hasOwn||function(e,t){return VS(CS(e),t)}});var Cn=b((Mw,Mc)=>{"use strict";var BS=ke(),OS=0,_S=Math.random(),NS=BS(1 .toString);Mc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+NS(++OS+_S,36)}});var Pe=b((Dw,Cc)=>{"use strict";var FS=pe(),US=Dn(),Dc=st(),qS=Cn(),HS=wn(),jS=kn(),Ri=FS.Symbol,Vn=US("wks"),GS=jS?Ri.for||Ri:Ri&&Ri.withoutSetter||qS;Cc.exports=function(a){return Dc(Vn,a)||(Vn[a]=HS&&Dc(Ri,a)?Ri[a]:GS("Symbol."+a)),Vn[a]}});var _c=b((Cw,Oc)=>{"use strict";var QS=Ne(),Vc=Qe(),Bc=Rn(),WS=fr(),YS=yc(),zS=Pe(),KS=TypeError,XS=zS("toPrimitive");Oc.exports=function(a,e){if(!Vc(a)||Bc(a))return a;var t=WS(a,XS),i;if(t){if(e===void 0&&(e="default"),i=QS(t,a,e),!Vc(i)||Bc(i))return i;throw new KS("Can't convert object to primitive value")}return e===void 0&&(e="number"),YS(a,e)}});var Bn=b((Vw,Nc)=>{"use strict";var JS=_c(),ZS=Rn();Nc.exports=function(a){var e=JS(a,"string");return ZS(e)?e:e+""}});var si=b(Uc=>{"use strict";var ev=We(),tv=Tn(),iv=In(),Ja=ht(),Fc=Bn(),rv=TypeError,On=Object.defineProperty,av=Object.getOwnPropertyDescriptor,_n="enumerable",Nn="configurable",Fn="writable";Uc.f=ev?iv?function(e,t,i){if(Ja(e),t=Fc(t),Ja(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Fn in i&&!i[Fn]){var r=av(e,t);r&&r[Fn]&&(e[t]=i.value,i={configurable:Nn in i?i[Nn]:r[Nn],enumerable:_n in i?i[_n]:r[_n],writable:!1})}return On(e,t,i)}:On:function(e,t,i){if(Ja(e),t=Fc(t),Ja(i),tv)try{return On(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new rv("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var gr=b((Ow,qc)=>{"use strict";qc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var $i=b((_w,Hc)=>{"use strict";var sv=We(),nv=si(),ov=gr();Hc.exports=sv?function(a,e,t){return nv.f(a,e,ov(1,t))}:function(a,e,t){return a[e]=t,a}});var Za=b((Nw,Gc)=>{"use strict";var uv=Dn(),lv=Cn(),jc=uv("keys");Gc.exports=function(a){return jc[a]||(jc[a]=lv(a))}});var es=b((Fw,Qc)=>{"use strict";Qc.exports={}});var jn=b((Uw,zc)=>{"use strict";var cv=jl(),Yc=pe(),dv=Qe(),pv=$i(),Un=st(),qn=mr(),hv=Za(),fv=es(),Wc="Object already initialized",Hn=Yc.TypeError,mv=Yc.WeakMap,ts,Sr,is,bv=function(a){return is(a)?Sr(a):ts(a,{})},gv=function(a){return function(e){var t;if(!dv(e)||(t=Sr(e)).type!==a)throw new Hn("Incompatible receiver, "+a+" required");return t}};cv||qn.state?(nt=qn.state||(qn.state=new mv),nt.get=nt.get,nt.has=nt.has,nt.set=nt.set,ts=function(a,e){if(nt.has(a))throw new Hn(Wc);return e.facade=a,nt.set(a,e),e},Sr=function(a){return nt.get(a)||{}},is=function(a){return nt.has(a)}):(ni=hv("state"),fv[ni]=!0,ts=function(a,e){if(Un(a,ni))throw new Hn(Wc);return e.facade=a,pv(a,ni,e),e},Sr=function(a){return Un(a,ni)?a[ni]:{}},is=function(a){return Un(a,ni)});var nt,ni;zc.exports={set:ts,get:Sr,has:is,enforce:bv,getterFor:gv}});var Gn=b((qw,Zc)=>{"use strict";var Sv=lr(),Jc=Function.prototype,Kc=Jc.apply,Xc=Jc.call;Zc.exports=typeof Reflect=="object"&&Reflect.apply||(Sv?Xc.bind(Kc):function(){return Xc.apply(Kc,arguments)})});var Qn=b((Hw,ed)=>{"use strict";var vv=Pi(),yv=ke();ed.exports=function(a){if(vv(a)==="Function")return yv(a)}});var ad=b(rd=>{"use strict";var td={}.propertyIsEnumerable,id=Object.getOwnPropertyDescriptor,Tv=id&&!td.call({1:2},1);rd.f=Tv?function(e){var t=id(this,e);return!!t&&t.enumerable}:td});var od=b(nd=>{"use strict";var Iv=We(),Ev=Ne(),xv=ad(),Pv=gr(),Av=wi(),wv=Bn(),kv=st(),Rv=Tn(),sd=Object.getOwnPropertyDescriptor;nd.f=Iv?sd:function(e,t){if(e=Av(e),t=wv(t),Rv)try{return sd(e,t)}catch(i){}if(kv(e,t))return Pv(!Ev(xv.f,e,t),e[t])}});var Wn=b((Qw,ud)=>{"use strict";var $v=_e(),Lv=de(),Mv=/#|\.prototype\./,vr=function(a,e){var t=Cv[Dv(a)];return t===Bv?!0:t===Vv?!1:Lv(e)?$v(e):!!e},Dv=vr.normalize=function(a){return String(a).replace(Mv,".").toLowerCase()},Cv=vr.data={},Vv=vr.NATIVE="N",Bv=vr.POLYFILL="P";ud.exports=vr});var yr=b((Ww,cd)=>{"use strict";var ld=Qn(),Ov=Et(),_v=lr(),Nv=ld(ld.bind);cd.exports=function(a,e){return Ov(a),e===void 0?a:_v?Nv(a,e):function(){return a.apply(e,arguments)}}});var Ye=b((Yw,pd)=>{"use strict";var Tr=pe(),Fv=Gn(),Uv=Qn(),qv=de(),Hv=od().f,jv=Wn(),Li=Ka(),Gv=yr(),Mi=$i(),dd=st();mr();var Qv=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return Fv(a,this,arguments)};return e.prototype=a.prototype,e};pd.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?Tr:r?Tr[t]:Tr[t]&&Tr[t].prototype,o=i?Li:Li[t]||Mi(Li,t,{})[t],u=o.prototype,l,d,c,p,h,m,g,S,x;for(p in e)l=jv(i?p:t+(r?".":"#")+p,a.forced),d=!l&&n&&dd(n,p),m=o[p],d&&(a.dontCallGetSet?(x=Hv(n,p),g=x&&x.value):g=n[p]),h=d&&g?g:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&d?S=Gv(h,Tr):a.wrap&&d?S=Qv(h):s&&qv(h)?S=Uv(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&Mi(S,"sham",!0),Mi(o,p,S),s&&(c=t+"Prototype",dd(Li,c)||Mi(Li,c,{}),Mi(Li[c],p,h),a.real&&u&&(l||!u[p])&&Mi(u,p,h)))}});var md=b((zw,fd)=>{"use strict";var Yn=We(),Wv=st(),hd=Function.prototype,Yv=Yn&&Object.getOwnPropertyDescriptor,zn=Wv(hd,"name"),zv=zn&&function(){}.name==="something",Kv=zn&&(!Yn||Yn&&Yv(hd,"name").configurable);fd.exports={EXISTS:zn,PROPER:zv,CONFIGURABLE:Kv}});var gd=b((Kw,bd)=>{"use strict";var Xv=Math.ceil,Jv=Math.floor;bd.exports=Math.trunc||function(e){var t=+e;return(t>0?Jv:Xv)(t)}});var rs=b((Xw,Sd)=>{"use strict";var Zv=gd();Sd.exports=function(a){var e=+a;return e!==e||e===0?0:Zv(e)}});var yd=b((Jw,vd)=>{"use strict";var ey=rs(),ty=Math.max,iy=Math.min;vd.exports=function(a,e){var t=ey(a);return t<0?ty(t+e,0):iy(t,e)}});var Id=b((Zw,Td)=>{"use strict";var ry=rs(),ay=Math.min;Td.exports=function(a){var e=ry(a);return e>0?ay(e,9007199254740991):0}});var as=b((ek,Ed)=>{"use strict";var sy=Id();Ed.exports=function(a){return sy(a.length)}});var Ad=b((tk,Pd)=>{"use strict";var ny=wi(),oy=yd(),uy=as(),xd=function(a){return function(e,t,i){var r=ny(e),s=uy(r);if(s===0)return!a&&-1;var n=oy(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};Pd.exports={includes:xd(!0),indexOf:xd(!1)}});var Rd=b((ik,kd)=>{"use strict";var ly=ke(),Kn=st(),cy=wi(),dy=Ad().indexOf,py=es(),wd=ly([].push);kd.exports=function(a,e){var t=cy(a),i=0,r=[],s;for(s in t)!Kn(py,s)&&Kn(t,s)&&wd(r,s);for(;e.length>i;)Kn(t,s=e[i++])&&(~dy(r,s)||wd(r,s));return r}});var Xn=b((rk,$d)=>{"use strict";$d.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Md=b((ak,Ld)=>{"use strict";var hy=Rd(),fy=Xn();Ld.exports=Object.keys||function(e){return hy(e,fy)}});var Cd=b(Dd=>{"use strict";var my=We(),by=In(),gy=si(),Sy=ht(),vy=wi(),yy=Md();Dd.f=my&&!by?Object.defineProperties:function(e,t){Sy(e);for(var i=vy(t),r=yy(t),s=r.length,n=0,o;s>n;)gy.f(e,o=r[n++],i[o]);return e}});var Jn=b((nk,Vd)=>{"use strict";var Ty=It();Vd.exports=Ty("document","documentElement")});var io=b((ok,qd)=>{"use strict";var Iy=ht(),Ey=Cd(),Bd=Xn(),xy=es(),Py=Jn(),Ay=Ya(),wy=Za(),Od=">",_d="<",eo="prototype",to="script",Fd=wy("IE_PROTO"),Zn=function(){},Ud=function(a){return _d+to+Od+a+_d+"/"+to+Od},Nd=function(a){a.write(Ud("")),a.close();var e=a.parentWindow.Object;return a=null,e},ky=function(){var a=Ay("iframe"),e="java"+to+":",t;return a.style.display="none",Py.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Ud("document.F=Object")),t.close(),t.F},ss,ns=function(){try{ss=new ActiveXObject("htmlfile")}catch(e){}ns=typeof document!="undefined"?document.domain&&ss?Nd(ss):ky():Nd(ss);for(var a=Bd.length;a--;)delete ns[eo][Bd[a]];return ns()};xy[Fd]=!0;qd.exports=Object.create||function(e,t){var i;return e!==null?(Zn[eo]=Iy(e),i=new Zn,Zn[eo]=null,i[Fd]=e):i=ns(),t===void 0?i:Ey.f(i,t)}});var jd=b((uk,Hd)=>{"use strict";var Ry=_e();Hd.exports=!Ry(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ao=b((lk,Qd)=>{"use strict";var $y=st(),Ly=de(),My=br(),Dy=Za(),Cy=jd(),Gd=Dy("IE_PROTO"),ro=Object,Vy=ro.prototype;Qd.exports=Cy?ro.getPrototypeOf:function(a){var e=My(a);if($y(e,Gd))return e[Gd];var t=e.constructor;return Ly(t)&&e instanceof t?t.prototype:e instanceof ro?Vy:null}});var Di=b((ck,Wd)=>{"use strict";var By=$i();Wd.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:By(a,e,t),a}});var uo=b((dk,Kd)=>{"use strict";var Oy=_e(),_y=de(),Ny=Qe(),Fy=io(),Yd=ao(),Uy=Di(),qy=Pe(),Hy=at(),oo=qy("iterator"),zd=!1,xt,so,no;[].keys&&(no=[].keys(),"next"in no?(so=Yd(Yd(no)),so!==Object.prototype&&(xt=so)):zd=!0);var jy=!Ny(xt)||Oy(function(){var a={};return xt[oo].call(a)!==a});jy?xt={}:Hy&&(xt=Fy(xt));_y(xt[oo])||Uy(xt,oo,function(){return this});Kd.exports={IteratorPrototype:xt,BUGGY_SAFARI_ITERATORS:zd}});var os=b((pk,Jd)=>{"use strict";var Gy=Pe(),Qy=Gy("toStringTag"),Xd={};Xd[Qy]="z";Jd.exports=String(Xd)==="[object z]"});var Ir=b((hk,Zd)=>{"use strict";var Wy=os(),Yy=de(),us=Pi(),zy=Pe(),Ky=zy("toStringTag"),Xy=Object,Jy=us(function(){return arguments}())==="Arguments",Zy=function(a,e){try{return a[e]}catch(t){}};Zd.exports=Wy?us:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=Zy(e=Xy(a),Ky))=="string"?t:Jy?us(e):(i=us(e))==="Object"&&Yy(e.callee)?"Arguments":i}});var tp=b((fk,ep)=>{"use strict";var eT=os(),tT=Ir();ep.exports=eT?{}.toString:function(){return"[object "+tT(this)+"]"}});var Er=b((mk,rp)=>{"use strict";var iT=os(),rT=si().f,aT=$i(),sT=st(),nT=tp(),oT=Pe(),ip=oT("toStringTag");rp.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(sT(r,ip)||rT(r,ip,{configurable:!0,value:e}),i&&!iT&&aT(r,"toString",nT))}});var sp=b((bk,ap)=>{"use strict";var uT=uo().IteratorPrototype,lT=io(),cT=gr(),dT=Er(),pT=ai(),hT=function(){return this};ap.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=lT(uT,{next:cT(+!i,t)}),dT(a,r,!1,!0),pT[r]=hT,a}});var op=b((gk,np)=>{"use strict";var fT=ke(),mT=Et();np.exports=function(a,e,t){try{return fT(mT(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var lp=b((Sk,up)=>{"use strict";var bT=Qe();up.exports=function(a){return bT(a)||a===null}});var dp=b((vk,cp)=>{"use strict";var gT=lp(),ST=String,vT=TypeError;cp.exports=function(a){if(gT(a))return a;throw new vT("Can't set "+ST(a)+" as a prototype")}});var lo=b((yk,pp)=>{"use strict";var yT=op(),TT=Qe(),IT=cr(),ET=dp();pp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=yT(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return IT(r),ET(s),TT(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Ep=b((Tk,Ip)=>{"use strict";var xT=Ye(),PT=Ne(),ls=at(),yp=md(),AT=de(),wT=sp(),hp=ao(),fp=lo(),kT=Er(),RT=$i(),co=Di(),$T=Pe(),mp=ai(),Tp=uo(),LT=yp.PROPER,MT=yp.CONFIGURABLE,bp=Tp.IteratorPrototype,cs=Tp.BUGGY_SAFARI_ITERATORS,xr=$T("iterator"),gp="keys",Pr="values",Sp="entries",vp=function(){return this};Ip.exports=function(a,e,t,i,r,s,n){wT(t,e,i);var o=function(x){if(x===r&&p)return p;if(!cs&&x&&x in d)return d[x];switch(x){case gp:return function(){return new t(this,x)};case Pr:return function(){return new t(this,x)};case Sp:return function(){return new t(this,x)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=a.prototype,c=d[xr]||d["@@iterator"]||r&&d[r],p=!cs&&c||o(r),h=e==="Array"&&d.entries||c,m,g,S;if(h&&(m=hp(h.call(new a)),m!==Object.prototype&&m.next&&(!ls&&hp(m)!==bp&&(fp?fp(m,bp):AT(m[xr])||co(m,xr,vp)),kT(m,u,!0,!0),ls&&(mp[u]=vp))),LT&&r===Pr&&c&&c.name!==Pr&&(!ls&&MT?RT(d,"name",Pr):(l=!0,p=function(){return PT(c,this)})),r)if(g={values:o(Pr),keys:s?p:o(gp),entries:o(Sp)},n)for(S in g)(cs||l||!(S in d))&&co(d,S,g[S]);else xT({target:e,proto:!0,forced:cs||l},g);return(!ls||n)&&d[xr]!==p&&co(d,xr,p,{name:r}),mp[e]=p,g}});var Pp=b((Ik,xp)=>{"use strict";xp.exports=function(a,e){return{value:a,done:e}}});var ho=b((Ek,$p)=>{"use strict";var DT=wi(),po=gn(),Ap=ai(),kp=jn(),CT=si().f,VT=Ep(),ds=Pp(),BT=at(),OT=We(),Rp="Array Iterator",_T=kp.set,NT=kp.getterFor(Rp);$p.exports=VT(Array,"Array",function(a,e){_T(this,{type:Rp,target:DT(a),index:0,kind:e})},function(){var a=NT(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ds(void 0,!0);switch(a.kind){case"keys":return ds(t,!1);case"values":return ds(e[t],!1)}return ds([t,e[t]],!1)},"values");var wp=Ap.Arguments=Ap.Array;po("keys");po("values");po("entries");if(!BT&&OT&&wp.name!=="values")try{CT(wp,"name",{value:"values"})}catch(a){}});var Mp=b((xk,Lp)=>{"use strict";var FT=Pe(),UT=ai(),qT=FT("iterator"),HT=Array.prototype;Lp.exports=function(a){return a!==void 0&&(UT.Array===a||HT[qT]===a)}});var fo=b((Pk,Cp)=>{"use strict";var jT=Ir(),Dp=fr(),GT=Ai(),QT=ai(),WT=Pe(),YT=WT("iterator");Cp.exports=function(a){if(!GT(a))return Dp(a,YT)||Dp(a,"@@iterator")||QT[jT(a)]}});var Bp=b((Ak,Vp)=>{"use strict";var zT=Ne(),KT=Et(),XT=ht(),JT=hr(),ZT=fo(),eI=TypeError;Vp.exports=function(a,e){var t=arguments.length<2?ZT(a):e;if(KT(t))return XT(zT(t,a));throw new eI(JT(a)+" is not iterable")}});var Np=b((wk,_p)=>{"use strict";var tI=Ne(),Op=ht(),iI=fr();_p.exports=function(a,e,t){var i,r;Op(a);try{if(i=iI(a,"return"),!i){if(e==="throw")throw t;return t}i=tI(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Op(i),t}});var hs=b((kk,Hp)=>{"use strict";var rI=yr(),aI=Ne(),sI=ht(),nI=hr(),oI=Mp(),uI=as(),Fp=pr(),lI=Bp(),cI=fo(),Up=Np(),dI=TypeError,ps=function(a,e){this.stopped=a,this.result=e},qp=ps.prototype;Hp.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=rI(e,i),l,d,c,p,h,m,g,S=function(T){return l&&Up(l,"normal",T),new ps(!0,T)},x=function(T){return r?(sI(T),o?u(T[0],T[1],S):u(T[0],T[1])):o?u(T,S):u(T)};if(s)l=a.iterator;else if(n)l=a;else{if(d=cI(a),!d)throw new dI(nI(a)+" is not iterable");if(oI(d)){for(c=0,p=uI(a);p>c;c++)if(h=x(a[c]),h&&Fp(qp,h))return h;return new ps(!1)}l=lI(a,d)}for(m=s?a.next:l.next;!(g=aI(m,l)).done;){try{h=x(g.value)}catch(T){Up(l,"throw",T)}if(typeof h=="object"&&h&&Fp(qp,h))return h}return new ps(!1)}});var Gp=b((Rk,jp)=>{"use strict";var pI=We(),hI=si(),fI=gr();jp.exports=function(a,e,t){pI?hI.f(a,e,fI(0,t)):a[e]=t}});var Qp=b(()=>{"use strict";var mI=Ye(),bI=hs(),gI=Gp();mI({target:"Object",stat:!0},{fromEntries:function(e){var t={};return bI(e,function(i,r){gI(t,i,r)},{AS_ENTRIES:!0}),t}})});var Yp=b((Mk,Wp)=>{"use strict";ho();Qp();var SI=Ka();Wp.exports=SI.Object.fromEntries});var Kp=b((Dk,zp)=>{"use strict";zp.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 Jp=b(()=>{"use strict";ho();var vI=Kp(),yI=pe(),TI=Er(),Xp=ai();for(fs in vI)TI(yI[fs],fs),Xp[fs]=Xp.Array;var fs});var eh=b((Bk,Zp)=>{"use strict";var II=Yp();Jp();Zp.exports=II});var mo=b((Ok,th)=>{"use strict";var EI=eh();th.exports=EI});var ih=b(()=>{"use strict"});var bo=b((Fk,rh)=>{"use strict";var Ar=pe(),xI=ki(),PI=Pi(),ms=function(a){return xI.slice(0,a.length)===a};rh.exports=function(){return ms("Bun/")?"BUN":ms("Cloudflare-Workers")?"CLOUDFLARE":ms("Deno/")?"DENO":ms("Node.js/")?"NODE":Ar.Bun&&typeof Bun.version=="string"?"BUN":Ar.Deno&&typeof Deno.version=="object"?"DENO":PI(Ar.process)==="process"?"NODE":Ar.window&&Ar.document?"BROWSER":"REST"}()});var bs=b((Uk,ah)=>{"use strict";var AI=bo();ah.exports=AI==="NODE"});var nh=b((qk,sh)=>{"use strict";var wI=si();sh.exports=function(a,e,t){return wI.f(a,e,t)}});var lh=b((Hk,uh)=>{"use strict";var kI=It(),RI=nh(),$I=Pe(),LI=We(),oh=$I("species");uh.exports=function(a){var e=kI(a);LI&&e&&!e[oh]&&RI(e,oh,{configurable:!0,get:function(){return this}})}});var dh=b((jk,ch)=>{"use strict";var MI=pr(),DI=TypeError;ch.exports=function(a,e){if(MI(e,a))return a;throw new DI("Incorrect invocation")}});var So=b((Gk,ph)=>{"use strict";var CI=ke(),VI=de(),go=mr(),BI=CI(Function.toString);VI(go.inspectSource)||(go.inspectSource=function(a){return BI(a)});ph.exports=go.inspectSource});var Sh=b((Qk,gh)=>{"use strict";var OI=ke(),_I=_e(),hh=de(),NI=Ir(),FI=It(),UI=So(),fh=function(){},mh=FI("Reflect","construct"),vo=/^\s*(?:class|function)\b/,qI=OI(vo.exec),HI=!vo.test(fh),wr=function(e){if(!hh(e))return!1;try{return mh(fh,[],e),!0}catch(t){return!1}},bh=function(e){if(!hh(e))return!1;switch(NI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return HI||!!qI(vo,UI(e))}catch(t){return!0}};bh.sham=!0;gh.exports=!mh||_I(function(){var a;return wr(wr.call)||!wr(Object)||!wr(function(){a=!0})||a})?bh:wr});var yh=b((Wk,vh)=>{"use strict";var jI=Sh(),GI=hr(),QI=TypeError;vh.exports=function(a){if(jI(a))return a;throw new QI(GI(a)+" is not a constructor")}});var yo=b((Yk,Ih)=>{"use strict";var Th=ht(),WI=yh(),YI=Ai(),zI=Pe(),KI=zI("species");Ih.exports=function(a,e){var t=Th(a).constructor,i;return t===void 0||YI(i=Th(t)[KI])?e:WI(i)}});var xh=b((zk,Eh)=>{"use strict";var XI=ke();Eh.exports=XI([].slice)});var Ah=b((Kk,Ph)=>{"use strict";var JI=TypeError;Ph.exports=function(a,e){if(a<e)throw new JI("Not enough arguments");return a}});var To=b((Xk,wh)=>{"use strict";var ZI=ki();wh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(ZI)});var $o=b((Jk,Bh)=>{"use strict";var Fe=pe(),eE=Gn(),tE=yr(),kh=de(),iE=st(),Vh=_e(),Rh=Jn(),rE=xh(),$h=Ya(),aE=Ah(),sE=To(),nE=bs(),wo=Fe.setImmediate,ko=Fe.clearImmediate,oE=Fe.process,Io=Fe.Dispatch,uE=Fe.Function,Lh=Fe.MessageChannel,lE=Fe.String,Eo=0,kr={},Mh="onreadystatechange",Rr,oi,xo,Po;Vh(function(){Rr=Fe.location});var Ro=function(a){if(iE(kr,a)){var e=kr[a];delete kr[a],e()}},Ao=function(a){return function(){Ro(a)}},Dh=function(a){Ro(a.data)},Ch=function(a){Fe.postMessage(lE(a),Rr.protocol+"//"+Rr.host)};(!wo||!ko)&&(wo=function(e){aE(arguments.length,1);var t=kh(e)?e:uE(e),i=rE(arguments,1);return kr[++Eo]=function(){eE(t,void 0,i)},oi(Eo),Eo},ko=function(e){delete kr[e]},nE?oi=function(a){oE.nextTick(Ao(a))}:Io&&Io.now?oi=function(a){Io.now(Ao(a))}:Lh&&!sE?(xo=new Lh,Po=xo.port2,xo.port1.onmessage=Dh,oi=tE(Po.postMessage,Po)):Fe.addEventListener&&kh(Fe.postMessage)&&!Fe.importScripts&&Rr&&Rr.protocol!=="file:"&&!Vh(Ch)?(oi=Ch,Fe.addEventListener("message",Dh,!1)):Mh in $h("script")?oi=function(a){Rh.appendChild($h("script"))[Mh]=function(){Rh.removeChild(this),Ro(a)}}:oi=function(a){setTimeout(Ao(a),0)});Bh.exports={set:wo,clear:ko}});var Nh=b((Zk,_h)=>{"use strict";var Oh=pe(),cE=We(),dE=Object.getOwnPropertyDescriptor;_h.exports=function(a){if(!cE)return Oh[a];var e=dE(Oh,a);return e&&e.value}});var Lo=b((eR,Uh)=>{"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}}};Uh.exports=Fh});var Hh=b((tR,qh)=>{"use strict";var pE=ki();qh.exports=/ipad|iphone|ipod/i.test(pE)&&typeof Pebble!="undefined"});var Gh=b((iR,jh)=>{"use strict";var hE=ki();jh.exports=/web0s(?!.*chrome)/i.test(hE)});var Jh=b((rR,Xh)=>{"use strict";var Vi=pe(),fE=Nh(),Qh=yr(),Mo=$o().set,mE=Lo(),bE=To(),gE=Hh(),SE=Gh(),Do=bs(),Wh=Vi.MutationObserver||Vi.WebKitMutationObserver,Yh=Vi.document,zh=Vi.process,gs=Vi.Promise,Bo=fE("queueMicrotask"),Ci,Co,Vo,Ss,Kh;Bo||($r=new mE,Lr=function(){var a,e;for(Do&&(a=zh.domain)&&a.exit();e=$r.get();)try{e()}catch(t){throw $r.head&&Ci(),t}a&&a.enter()},!bE&&!Do&&!SE&&Wh&&Yh?(Co=!0,Vo=Yh.createTextNode(""),new Wh(Lr).observe(Vo,{characterData:!0}),Ci=function(){Vo.data=Co=!Co}):!gE&&gs&&gs.resolve?(Ss=gs.resolve(void 0),Ss.constructor=gs,Kh=Qh(Ss.then,Ss),Ci=function(){Kh(Lr)}):Do?Ci=function(){zh.nextTick(Lr)}:(Mo=Qh(Mo,Vi),Ci=function(){Mo(Lr)}),Bo=function(a){$r.head||Ci(),$r.add(a)});var $r,Lr;Xh.exports=Bo});var ef=b((aR,Zh)=>{"use strict";Zh.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var vs=b((sR,tf)=>{"use strict";tf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ui=b((nR,rf)=>{"use strict";var vE=pe();rf.exports=vE.Promise});var Bi=b((oR,of)=>{"use strict";var yE=pe(),Mr=ui(),TE=de(),IE=Wn(),EE=So(),xE=Pe(),af=bo(),PE=at(),Oo=An(),sf=Mr&&Mr.prototype,AE=xE("species"),_o=!1,nf=TE(yE.PromiseRejectionEvent),wE=IE("Promise",function(){var a=EE(Mr),e=a!==String(Mr);if(!e&&Oo===66||PE&&!(sf.catch&&sf.finally))return!0;if(!Oo||Oo<51||!/native code/.test(a)){var t=new Mr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[AE]=i,_o=t.then(function(){})instanceof i,!_o)return!0}return!e&&(af==="BROWSER"||af==="DENO")&&!nf});of.exports={CONSTRUCTOR:wE,REJECTION_EVENT:nf,SUBCLASSING:_o}});var Oi=b((uR,lf)=>{"use strict";var uf=Et(),kE=TypeError,RE=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new kE("Bad Promise constructor");e=i,t=r}),this.resolve=uf(e),this.reject=uf(t)};lf.exports.f=function(a){return new RE(a)}});var kf=b(()=>{"use strict";var $E=Ye(),LE=at(),Es=bs(),qt=pe(),Ui=Ne(),cf=Di(),df=lo(),ME=Er(),DE=lh(),CE=Et(),Is=de(),VE=Qe(),BE=dh(),OE=yo(),bf=$o().set,Ho=Jh(),_E=ef(),NE=vs(),FE=Lo(),gf=jn(),xs=ui(),jo=Bi(),Sf=Oi(),Ps="Promise",vf=jo.CONSTRUCTOR,UE=jo.REJECTION_EVENT,qE=jo.SUBCLASSING,No=gf.getterFor(Ps),HE=gf.set,_i=xs&&xs.prototype,li=xs,ys=_i,yf=qt.TypeError,Fo=qt.document,Go=qt.process,Uo=Sf.f,jE=Uo,GE=!!(Fo&&Fo.createEvent&&qt.dispatchEvent),Tf="unhandledrejection",QE="rejectionhandled",pf=0,If=1,WE=2,Qo=1,Ef=2,Ts,hf,YE,ff,xf=function(a){var e;return VE(a)&&Is(e=a.then)?e:!1},Pf=function(a,e){var t=e.value,i=e.state===If,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,d;try{r?(i||(e.rejection===Ef&&KE(e),e.rejection=Qo),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===a.promise?n(new yf("Promise-chain cycle")):(l=xf(u))?Ui(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},Af=function(a,e){a.notified||(a.notified=!0,Ho(function(){for(var t=a.reactions,i;i=t.get();)Pf(i,a);a.notified=!1,e&&!a.rejection&&zE(a)}))},wf=function(a,e,t){var i,r;GE?(i=Fo.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),qt.dispatchEvent(i)):i={promise:e,reason:t},!UE&&(r=qt["on"+a])?r(i):a===Tf&&_E("Unhandled promise rejection",t)},zE=function(a){Ui(bf,qt,function(){var e=a.facade,t=a.value,i=mf(a),r;if(i&&(r=NE(function(){Es?Go.emit("unhandledRejection",t,e):wf(Tf,e,t)}),a.rejection=Es||mf(a)?Ef:Qo,r.error))throw r.value})},mf=function(a){return a.rejection!==Qo&&!a.parent},KE=function(a){Ui(bf,qt,function(){var e=a.facade;Es?Go.emit("rejectionHandled",e):wf(QE,e,a.value)})},Ni=function(a,e,t){return function(i){a(e,i,t)}},Fi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=WE,Af(a,!0))},qo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new yf("Promise can't be resolved itself");var i=xf(e);i?Ho(function(){var r={done:!1};try{Ui(i,e,Ni(qo,r,a),Ni(Fi,r,a))}catch(s){Fi(r,s,a)}}):(a.value=e,a.state=If,Af(a,!1))}catch(r){Fi({done:!1},r,a)}}};if(vf&&(li=function(e){BE(this,ys),CE(e),Ui(Ts,this);var t=No(this);try{e(Ni(qo,t),Ni(Fi,t))}catch(i){Fi(t,i)}},ys=li.prototype,Ts=function(e){HE(this,{type:Ps,done:!1,notified:!1,parent:!1,reactions:new FE,rejection:!1,state:pf,value:void 0})},Ts.prototype=cf(ys,"then",function(e,t){var i=No(this),r=Uo(OE(this,li));return i.parent=!0,r.ok=Is(e)?e:!0,r.fail=Is(t)&&t,r.domain=Es?Go.domain:void 0,i.state===pf?i.reactions.add(r):Ho(function(){Pf(r,i)}),r.promise}),hf=function(){var a=new Ts,e=No(a);this.promise=a,this.resolve=Ni(qo,e),this.reject=Ni(Fi,e)},Sf.f=Uo=function(a){return a===li||a===YE?new hf(a):jE(a)},!LE&&Is(xs)&&_i!==Object.prototype)){ff=_i.then,qE||cf(_i,"then",function(e,t){var i=this;return new li(function(r,s){Ui(ff,i,r,s)}).then(e,t)},{unsafe:!0});try{delete _i.constructor}catch(a){}df&&df(_i,ys)}$E({global:!0,constructor:!0,wrap:!0,forced:vf},{Promise:li});ME(li,Ps,!1,!0);DE(Ps)});var Df=b((dR,Mf)=>{"use strict";var XE=Pe(),$f=XE("iterator"),Lf=!1;try{Rf=0,Wo={next:function(){return{done:!!Rf++}},return:function(){Lf=!0}},Wo[$f]=function(){return this},Array.from(Wo,function(){throw 2})}catch(a){}var Rf,Wo;Mf.exports=function(a,e){try{if(!e&&!Lf)return!1}catch(r){return!1}var t=!1;try{var i={};i[$f]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Yo=b((pR,Cf)=>{"use strict";var JE=ui(),ZE=Df(),ex=Bi().CONSTRUCTOR;Cf.exports=ex||!ZE(function(a){JE.all(a).then(void 0,function(){})})});var Vf=b(()=>{"use strict";var tx=Ye(),ix=Ne(),rx=Et(),ax=Oi(),sx=vs(),nx=hs(),ox=Yo();tx({target:"Promise",stat:!0,forced:ox},{all:function(e){var t=this,i=ax.f(t),r=i.resolve,s=i.reject,n=sx(function(){var o=rx(t.resolve),u=[],l=0,d=1;nx(e,function(c){var p=l++,h=!1;d++,ix(o,t,c).then(function(m){h||(h=!0,u[p]=m,--d||r(u))},s)}),--d||r(u)});return n.error&&s(n.value),i.promise}})});var Of=b(()=>{"use strict";var ux=Ye(),lx=at(),cx=Bi().CONSTRUCTOR,Ko=ui(),dx=It(),px=de(),hx=Di(),Bf=Ko&&Ko.prototype;ux({target:"Promise",proto:!0,forced:cx,real:!0},{catch:function(a){return this.then(void 0,a)}});!lx&&px(Ko)&&(zo=dx("Promise").prototype.catch,Bf.catch!==zo&&hx(Bf,"catch",zo,{unsafe:!0}));var zo});var _f=b(()=>{"use strict";var fx=Ye(),mx=Ne(),bx=Et(),gx=Oi(),Sx=vs(),vx=hs(),yx=Yo();fx({target:"Promise",stat:!0,forced:yx},{race:function(e){var t=this,i=gx.f(t),r=i.reject,s=Sx(function(){var n=bx(t.resolve);vx(e,function(o){mx(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Nf=b(()=>{"use strict";var Tx=Ye(),Ix=Oi(),Ex=Bi().CONSTRUCTOR;Tx({target:"Promise",stat:!0,forced:Ex},{reject:function(e){var t=Ix.f(this),i=t.reject;return i(e),t.promise}})});var Xo=b((TR,Ff)=>{"use strict";var xx=ht(),Px=Qe(),Ax=Oi();Ff.exports=function(a,e){if(xx(a),Px(e)&&e.constructor===a)return e;var t=Ax.f(a),i=t.resolve;return i(e),t.promise}});var Hf=b(()=>{"use strict";var wx=Ye(),kx=It(),Uf=at(),Rx=ui(),qf=Bi().CONSTRUCTOR,$x=Xo(),Lx=kx("Promise"),Mx=Uf&&!qf;wx({target:"Promise",stat:!0,forced:Uf||qf},{resolve:function(e){return $x(Mx&&this===Lx?Rx:this,e)}})});var jf=b(()=>{"use strict";kf();Vf();Of();_f();Nf();Hf()});var Yf=b(()=>{"use strict";var Dx=Ye(),Cx=at(),As=ui(),Vx=_e(),Qf=It(),Wf=de(),Bx=yo(),Gf=Xo(),Ox=Di(),Zo=As&&As.prototype,_x=!!As&&Vx(function(){Zo.finally.call({then:function(){}},function(){})});Dx({target:"Promise",proto:!0,real:!0,forced:_x},{finally:function(a){var e=Bx(this,Qf("Promise")),t=Wf(a);return this.then(t?function(i){return Gf(e,a()).then(function(){return i})}:a,t?function(i){return Gf(e,a()).then(function(){throw i})}:a)}});!Cx&&Wf(As)&&(Jo=Qf("Promise").prototype.finally,Zo.finally!==Jo&&Ox(Zo,"finally",Jo,{unsafe:!0}));var Jo});var ws=b((kR,zf)=>{"use strict";var Nx=It();zf.exports=Nx});var Xf=b((RR,Kf)=>{"use strict";ih();jf();Yf();var Fx=ws();Kf.exports=Fx("Promise","finally")});var Zf=b(($R,Jf)=>{"use strict";var Ux=Xf();Jf.exports=Ux});var ks=b((LR,em)=>{"use strict";var qx=Zf();em.exports=qx});var cm=b(()=>{"use strict";var Kx=Ye(),Xx=br(),Jx=as(),Zx=rs(),eP=gn();Kx({target:"Array",proto:!0},{at:function(e){var t=Xx(this),i=Jx(t),r=Zx(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});eP("at")});var pm=b((R$,dm)=>{"use strict";cm();var tP=ws();dm.exports=tP("Array","at")});var fm=b(($$,hm)=>{"use strict";var iP=pm();hm.exports=iP});var qi=b((L$,mm)=>{"use strict";var rP=fm();mm.exports=rP});var ub=b(()=>{"use strict"});var lb=b(()=>{"use strict"});var db=b((RC,cb)=>{"use strict";var NP=Qe(),FP=Pi(),UP=Pe(),qP=UP("match");cb.exports=function(a){var e;return NP(a)&&((e=a[qP])!==void 0?!!e:FP(a)==="RegExp")}});var hb=b(($C,pb)=>{"use strict";var HP=Ir(),jP=String;pb.exports=function(a){if(HP(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return jP(a)}});var mb=b((LC,fb)=>{"use strict";var GP=ht();fb.exports=function(){var a=GP(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var Sb=b((MC,gb)=>{"use strict";var QP=Ne(),WP=st(),YP=pr(),zP=mb(),bb=RegExp.prototype;gb.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in bb)&&!WP(a,"flags")&&YP(bb,a)?QP(zP,a):e}});var yb=b((DC,vb)=>{"use strict";var Iu=ke(),KP=br(),XP=Math.floor,yu=Iu("".charAt),JP=Iu("".replace),Tu=Iu("".slice),ZP=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,eA=/\$([$&'`]|\d{1,2})/g;vb.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=eA;return r!==void 0&&(r=KP(r),u=ZP),JP(s,u,function(l,d){var c;switch(yu(d,0)){case"$":return"$";case"&":return a;case"`":return Tu(e,0,t);case"'":return Tu(e,n);case"<":c=r[Tu(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=XP(p/10);return h===0?l:h<=o?i[h-1]===void 0?yu(d,1):i[h-1]+yu(d,1):l}c=i[p-1]}return c===void 0?"":c})}});var Eb=b(()=>{"use strict";var tA=Ye(),iA=Ne(),xu=ke(),Tb=cr(),rA=de(),aA=Ai(),sA=db(),zi=hb(),nA=fr(),oA=Sb(),uA=yb(),lA=Pe(),cA=at(),dA=lA("replace"),pA=TypeError,Eu=xu("".indexOf),hA=xu("".replace),Ib=xu("".slice),fA=Math.max;tA({target:"String",proto:!0},{replaceAll:function(e,t){var i=Tb(this),r,s,n,o,u,l,d,c,p,h,m=0,g="";if(!aA(e)){if(r=sA(e),r&&(s=zi(Tb(oA(e))),!~Eu(s,"g")))throw new pA("`.replaceAll` does not allow non-global regexes");if(n=nA(e,dA),n)return iA(n,e,i,t);if(cA&&r)return hA(zi(i),e,t)}for(o=zi(i),u=zi(e),l=rA(t),l||(t=zi(t)),d=u.length,c=fA(1,d),p=Eu(o,u);p!==-1;)h=l?zi(t(u,p,o)):uA(u,o,p,[],void 0,t),g+=Ib(o,m,p)+h,m=p+d,p=p+c>o.length?-1:Eu(o,u,p+c);return m<o.length&&(g+=Ib(o,m)),g}})});var Pb=b((BC,xb)=>{"use strict";ub();lb();Eb();var mA=ws();xb.exports=mA("String","replaceAll")});var wb=b((OC,Ab)=>{"use strict";var bA=Pb();Ab.exports=bA});var Rb=b((_C,kb)=>{"use strict";var gA=wb();kb.exports=gA});var VA={};Mg(VA,{ChromecastState:()=>ur,HttpConnectionType:()=>Ga,Observable:()=>vt.Observable,PlaybackState:()=>xe,Player:()=>$a,SDK_VERSION:()=>CA,Subject:()=>vt.Subject,Subscription:()=>vt.Subscription,Surface:()=>Qa,VERSION:()=>fn,ValueSubject:()=>vt.ValueSubject,VideoFormat:()=>Tt,VideoQuality:()=>vt.VideoQuality});module.exports=Dg(VA);var fn="2.0.117-dev.d9cc3d97.0";var xe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(xe||{}),Tt=(E=>(E.MPEG="MPEG",E.DASH="DASH",E.DASH_SEP="DASH_SEP",E.DASH_SEP_VK="DASH_SEP",E.DASH_WEBM="DASH_WEBM",E.DASH_WEBM_AV1="DASH_WEBM_AV1",E.DASH_STREAMS="DASH_STREAMS",E.DASH_WEBM_VK="DASH_WEBM",E.DASH_ONDEMAND="DASH_ONDEMAND",E.DASH_ONDEMAND_VK="DASH_ONDEMAND",E.DASH_LIVE="DASH_LIVE",E.DASH_LIVE_CMAF="DASH_LIVE_CMAF",E.DASH_LIVE_WEBM="DASH_LIVE_WEBM",E.HLS="HLS",E.HLS_ONDEMAND="HLS_ONDEMAND",E.HLS_JS="HLS",E.HLS_LIVE="HLS_LIVE",E.HLS_LIVE_CMAF="HLS_LIVE_CMAF",E.WEB_RTC_LIVE="WEB_RTC_LIVE",E))(Tt||{});var ur=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(ur||{}),Ga=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Ga||{});var Qa=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Qa||{});var U=require("@vkontakte/videoplayer-shared");var Pl=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Wa=class{constructor(e){this.connection$=new U.ValueSubject(void 0);this.castState$=new U.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new U.Subject;this.realCastState$=new U.ValueSubject("NOT_AVAILABLE");this.subscription=new U.Subscription;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,U.isNonNullable)((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},r||Pl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:U.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,U.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,U.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,U.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add((0,U.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,U.assertNever)(r.sessionState)}})).add((0,U.merge)((0,U.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,U.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,U.map)(r=>r.castState)),(0,U.observableFrom)([i.getCastState()])).pipe((0,U.filterChanged)(),(0,U.map)(Cg),(0,U.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=(0,U.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();(0,U.assertNonNullable)(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,U.isNullable)(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,U.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:U.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Cg=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,U.assertNever)(a)}};var ig=Ge(mo(),1);var am=Ge(ks(),1);var eu=require("@vkontakte/videoplayer-shared");var Te=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,eu.assertNever)(t)}return a},tu=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,eu.assertNever)(e)}};var k=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var ft=require("@vkontakte/videoplayer-shared"),G=class{constructor(e){this.transitionStarted$=new ft.Subject;this.transitionEnded$=new ft.Subject;this.transitionUpdated$=new ft.Subject;this.forceChanged$=new ft.Subject;this.stateChangeStarted$=(0,ft.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,ft.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,ft.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var tm=require("@vkontakte/videoplayer-shared"),im=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,tm.assertNever)(a)}};var L=require("@vkontakte/videoplayer-shared");var Hx=5,jx=5,Gx=500,rm=7e3,Dr=class{constructor(e){this.subscription=new L.Subscription;this.loadMediaTimeoutSubscription=new L.Subscription;this.videoState=new G("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.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,L.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,L.assertNever)(e)}break}default:(0,L.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(im(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 L.Subscription;this.subscription.add(e),this.subscription.add((0,L.merge)(this.videoState.stateChangeStarted$.pipe((0,L.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,L.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new L.Subject;e.add(r.pipe((0,L.debounce)(Gx)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,L.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)>Hx)&&r.next(o),s=o})),e.add((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<jx&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,L.assertNever)(n)}}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,L.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,L.observableFrom)(["init"])).pipe((0,L.debounce)(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let d=t[e];(0,L.assertNonNullable)(d);let c=(0,L.getHighestQuality)(Object.keys(d));(0,L.assertNonNullable)(c);let p=d[c];(0,L.assertNonNullable)(p),i=p,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];(0,L.assertNonNullable)(d),i=d.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];(0,L.assertNonNullable)(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];(0,L.assertNonNullable)(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];(0,L.assertNonNullable)(d),i=Te(d.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.ErrorCategory.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,L.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,L.isNonNullable)(o)&&(n.metadata.title=o),(0,L.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add((0,L.timeout)(rm).subscribe(()=>s(`timeout(${rm})`)))});(0,am.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:L.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var su=require("@vkontakte/videoplayer-shared");var sm=require("@vkontakte/videoplayer-shared"),nm=a=>{try{a.pause(),a.playbackRate=0,(0,sm.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Rs=require("@vkontakte/videoplayer-shared"),iu=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)}},ru=window.WeakMap?new WeakMap:new iu,au=window.WeakMap?new WeakMap:new Map,Qx=(a,e=20)=>{let t=0;return(0,Rs.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Re=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),i=!!t;t?(0,su.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),ru.set(t,i);let r=new Rs.Subscription;return r.add(Qx(t,e)),au.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},$e=a=>{let e=au.get(a);e==null||e.unsubscribe(),au.delete(a);let t=ru.get(a);ru.delete(a),t?(0,su.clearVideoElement)(a):nm(a)};var M=require("@vkontakte/videoplayer-shared");var Ht=require("@vkontakte/videoplayer-shared"),$s=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Ht.isNullable)(r),l=new Ht.Subscription;return r&&l.add(r.subscribe(d=>{let c=a.getState();i(d,c)&&a.setState(d)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),l},mt=(a,e,t)=>$s(e,()=>a.loop,i=>{(0,Ht.isNonNullable)(i)&&(a.loop=i)},{onError:t}),Le=(a,e,t,i)=>$s(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,Ht.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),ze=(a,e,t,i)=>$s(e,()=>a.playbackRate,r=>{(0,Ht.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),jt=$s;var Wx=a=>["__",a.language,a.label].join("|"),Yx=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},nu=class a{constructor(){this.available$=new M.Subject;this.current$=new M.ValueSubject(void 0);this.error$=new M.Subject;this.subscription=new M.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:M.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(jt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,M.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,M.isNonNullable)(s)&&(0,M.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,M.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(jt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,M.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,M.isNonNullable)(s)&&(0,M.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,M.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(jt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(jt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,M.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,M.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,M.merge)((0,M.fromEvent)(e,"addtrack"),(0,M.fromEvent)(e,"removetrack"),(0,M.observableFrom)(["init"])).pipe((0,M.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,M.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,M.merge)((0,M.fromEvent)(e,"change"),(0,M.observableFrom)(["init"])).pipe((0,M.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,M.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,M.filterChanged)()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add((0,M.fromEvent)(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,d,c,p,h;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(c=o.target)==null?void 0:c.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,M.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,M.isNonNullable)(t.align)&&(r.align=t.align),(0,M.isNonNullable)(t.position)&&(r.position=t.position),(0,M.isNonNullable)(t.size)&&(r.size=t.size),(0,M.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,M.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:Wx(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,M.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,M.isNullable)(e)||!Yx(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,M.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,M.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ke=nu;var At=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var om=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},ou=a=>{let e=om(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},um=a=>{let e=om(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var C=require("@vkontakte/videoplayer-shared");var zx=3,lm=(a,e,t=zx)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Me=a=>{let e=E=>(0,C.fromEvent)(a,E).pipe((0,C.mapTo)(void 0)),i=(0,C.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>(0,C.fromEvent)(a,E))).pipe((0,C.map)(E=>E.type==="ended"?a.readyState<2:a.readyState<3),(0,C.filterChanged)()),r=(0,C.merge)((0,C.fromEvent)(a,"progress"),(0,C.fromEvent)(a,"timeupdate")).pipe((0,C.map)(()=>lm(a.buffered,a.currentTime))),s=C.clientChecker.isSafari?(0,C.combine)({play:e("play").pipe((0,C.once)()),playing:e("playing")}).pipe((0,C.mapTo)(void 0)):e("playing"),n=(0,C.fromEvent)(a,"volumechange").pipe((0,C.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,C.fromEvent)(a,"ratechange").pipe((0,C.map)(()=>a.playbackRate)),u=(0,C.fromEvent)(a,"error").pipe((0,C.filter)(()=>!!(a.error||a.played.length)),(0,C.map)(()=>{var A;let E=a.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:C.ErrorCategory.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:(A=a.error)!=null?A:void 0}})),l=(0,C.fromEvent)(a,"timeupdate").pipe((0,C.map)(()=>a.currentTime)),d=new C.Subject,c=.3,p;l.subscribe(E=>{a.loop&&(0,C.isNonNullable)(p)&&(0,C.isNonNullable)(E)&&p>=a.duration-c&&E<=c&&d.next(p),p=E});let h=e("pause").pipe((0,C.filter)(()=>!a.error&&p!==a.duration)),m=(0,C.fromEvent)(a,"enterpictureinpicture"),g=(0,C.fromEvent)(a,"leavepictureinpicture"),S=new C.ValueSubject(um(a));m.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let x=new C.ValueSubject(ou(a));return(0,C.fromEvent)(a,"fullscreenchange").pipe((0,C.map)(()=>ou(a))).subscribe(x),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,C.fromEvent)(a,"durationchange").pipe((0,C.map)(()=>a.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:x}};var wt=require("@vkontakte/videoplayer-shared"),Gt=a=>{switch(a){case"mobile":return wt.VideoQuality.Q_144P;case"lowest":return wt.VideoQuality.Q_240P;case"low":return wt.VideoQuality.Q_360P;case"sd":case"medium":return wt.VideoQuality.Q_480P;case"hd":case"high":return wt.VideoQuality.Q_720P;case"fullhd":case"full":return wt.VideoQuality.Q_1080P;case"quadhd":case"quad":return wt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return wt.VideoQuality.Q_2160P}};var Qt=Ge(qi(),1),D=require("@vkontakte/videoplayer-shared");var uu=!1,kt={},bm=a=>{uu=a},gm=()=>{kt={}},Sm=a=>{a(kt)},Cr=(a,e)=>{var t;uu&&(kt.meta=(t=kt.meta)!=null?t:{},kt.meta[a]=e)},Ae=class{constructor(e){this.name=e}next(e){var i,r;if(!uu)return;kt.series=(i=kt.series)!=null?i:{};let t=(r=kt.series[this.name])!=null?r:[];t.push([Date.now(),e]),kt.series[this.name]=t}};var aP=new Ae("best_bitrate"),ym=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var lu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Vr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,D.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Tm='Assertion "ABR Tracks is empty array" failed',Ls=(a,e,t,i)=>{var u;let r=[...e].sort(lu(1)),s=[...t].sort(lu(1)),n=s.filter(l=>(0,D.isNonNullable)(l.bitrate)&&(0,D.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Qt.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Qt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Qt.default)(n,-1):(0,Qt.default)(s,0)},vm=a=>"quality"in a,Im=(a,e,t,i)=>{var n;let r=(0,D.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,D.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,D.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=vm(o)?"video":"audio",l=vm(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
"use strict";var Eg=Object.create;var nr=Object.defineProperty,xg=Object.defineProperties,Pg=Object.getOwnPropertyDescriptor,Ag=Object.getOwnPropertyDescriptors,wg=Object.getOwnPropertyNames,Ha=Object.getOwnPropertySymbols,kg=Object.getPrototypeOf,cn=Object.prototype.hasOwnProperty,yl=Object.prototype.propertyIsEnumerable;var Rg=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var ct=Math.pow,vl=(a,e,t)=>e in a?nr(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,$=(a,e)=>{for(var t in e||(e={}))cn.call(e,t)&&vl(a,t,e[t]);if(Ha)for(var t of Ha(e))yl.call(e,t)&&vl(a,t,e[t]);return a},K=(a,e)=>xg(a,Ag(e));var Tl=(a,e)=>{var t={};for(var i in a)cn.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&Ha)for(var i of Ha(a))e.indexOf(i)<0&&yl.call(a,i)&&(t[i]=a[i]);return t};var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),$g=(a,e)=>{for(var t in e)nr(a,t,{get:e[t],enumerable:!0})},Il=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of wg(e))!cn.call(a,r)&&r!==t&&nr(a,r,{get:()=>e[r],enumerable:!(i=Pg(e,r))||i.enumerable});return a};var je=(a,e,t)=>(t=a!=null?Eg(kg(a)):{},Il(e||!a||!a.__esModule?nr(t,"default",{value:a,enumerable:!0}):t,a)),Lg=a=>Il(nr({},"__esModule",{value:!0}),a);var B=(a,e,t)=>new Promise((i,r)=>{var s=u=>{try{o(t.next(u))}catch(l){r(l)}},n=u=>{try{o(t.throw(u))}catch(l){r(l)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),dn=function(a,e){this[0]=a,this[1]=e},he=(a,e,t)=>{var i=(n,o,u,l)=>{try{var d=t[n](o),c=(o=d.value)instanceof dn,p=d.done;Promise.resolve(c?o[0]:o).then(h=>c?i(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>i("throw",h,u,l))}catch(h){l(h)}},r=n=>s[n]=o=>new Promise((u,l)=>i(n,o,u,l)),s={};return t=t.apply(a,e),s[Rg("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var Be=b((WA,xl)=>{"use strict";xl.exports=function(a){try{return!!a()}catch(e){return!0}}});var ur=b((YA,Pl)=>{"use strict";var Cg=Be();Pl.exports=!Cg(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var we=b((zA,kl)=>{"use strict";var Al=ur(),wl=Function.prototype,hn=wl.call,Dg=Al&&wl.bind.bind(hn,hn);kl.exports=Al?Dg:function(a){return function(){return hn.apply(a,arguments)}}});var Pi=b((KA,$l)=>{"use strict";var Rl=we(),Bg=Rl({}.toString),Vg=Rl("".slice);$l.exports=function(a){return Vg(Bg(a),8,-1)}});var Ml=b((JA,Ll)=>{"use strict";var Og=we(),_g=Be(),Ng=Pi(),fn=Object,Fg=Og("".split);Ll.exports=_g(function(){return!fn("z").propertyIsEnumerable(0)})?function(a){return Ng(a)==="String"?Fg(a,""):fn(a)}:fn});var Ai=b((XA,Cl)=>{"use strict";Cl.exports=function(a){return a==null}});var lr=b((ZA,Dl)=>{"use strict";var qg=Ai(),Ug=TypeError;Dl.exports=function(a){if(qg(a))throw new Ug("Can't call method on "+a);return a}});var wi=b((ew,Bl)=>{"use strict";var Hg=Ml(),jg=lr();Bl.exports=function(a){return Hg(jg(a))}});var mn=b((tw,Vl)=>{"use strict";Vl.exports=function(){}});var ri=b((iw,Ol)=>{"use strict";Ol.exports={}});var pe=b((bn,_l)=>{"use strict";var cr=function(a){return a&&a.Math===Math&&a};_l.exports=cr(typeof globalThis=="object"&&globalThis)||cr(typeof window=="object"&&window)||cr(typeof self=="object"&&self)||cr(typeof global=="object"&&global)||cr(typeof bn=="object"&&bn)||function(){return this}()||Function("return this")()});var de=b((rw,Nl)=>{"use strict";var gn=typeof document=="object"&&document.all;Nl.exports=typeof gn=="undefined"&&gn!==void 0?function(a){return typeof a=="function"||a===gn}:function(a){return typeof a=="function"}});var Ul=b((aw,ql)=>{"use strict";var Gg=pe(),Qg=de(),Fl=Gg.WeakMap;ql.exports=Qg(Fl)&&/native code/.test(String(Fl))});var Ge=b((sw,Hl)=>{"use strict";var Wg=de();Hl.exports=function(a){return typeof a=="object"?a!==null:Wg(a)}});var Qe=b((nw,jl)=>{"use strict";var Yg=Be();jl.exports=!Yg(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Wa=b((ow,Ql)=>{"use strict";var zg=pe(),Gl=Ge(),Sn=zg.document,Kg=Gl(Sn)&&Gl(Sn.createElement);Ql.exports=function(a){return Kg?Sn.createElement(a):{}}});var vn=b((uw,Wl)=>{"use strict";var Jg=Qe(),Xg=Be(),Zg=Wa();Wl.exports=!Jg&&!Xg(function(){return Object.defineProperty(Zg("div"),"a",{get:function(){return 7}}).a!==7})});var yn=b((lw,Yl)=>{"use strict";var eS=Qe(),tS=Be();Yl.exports=eS&&tS(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var dt=b((cw,zl)=>{"use strict";var iS=Ge(),rS=String,aS=TypeError;zl.exports=function(a){if(iS(a))return a;throw new aS(rS(a)+" is not an object")}});var Ve=b((dw,Kl)=>{"use strict";var sS=ur(),Ya=Function.prototype.call;Kl.exports=sS?Ya.bind(Ya):function(){return Ya.apply(Ya,arguments)}});var za=b((pw,Jl)=>{"use strict";Jl.exports={}});var yt=b((hw,Zl)=>{"use strict";var Tn=za(),In=pe(),nS=de(),Xl=function(a){return nS(a)?a:void 0};Zl.exports=function(a,e){return arguments.length<2?Xl(Tn[a])||Xl(In[a]):Tn[a]&&Tn[a][e]||In[a]&&In[a][e]}});var dr=b((fw,ec)=>{"use strict";var oS=we();ec.exports=oS({}.isPrototypeOf)});var ki=b((mw,rc)=>{"use strict";var uS=pe(),tc=uS.navigator,ic=tc&&tc.userAgent;rc.exports=ic?String(ic):""});var xn=b((bw,lc)=>{"use strict";var uc=pe(),En=ki(),ac=uc.process,sc=uc.Deno,nc=ac&&ac.versions||sc&&sc.version,oc=nc&&nc.v8,it,Ka;oc&&(it=oc.split("."),Ka=it[0]>0&&it[0]<4?1:+(it[0]+it[1]));!Ka&&En&&(it=En.match(/Edge\/(\d+)/),(!it||it[1]>=74)&&(it=En.match(/Chrome\/(\d+)/),it&&(Ka=+it[1])));lc.exports=Ka});var Pn=b((gw,dc)=>{"use strict";var cc=xn(),lS=Be(),cS=pe(),dS=cS.String;dc.exports=!!Object.getOwnPropertySymbols&&!lS(function(){var a=Symbol("symbol detection");return!dS(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&cc&&cc<41})});var An=b((Sw,pc)=>{"use strict";var pS=Pn();pc.exports=pS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var wn=b((vw,hc)=>{"use strict";var hS=yt(),fS=de(),mS=dr(),bS=An(),gS=Object;hc.exports=bS?function(a){return typeof a=="symbol"}:function(a){var e=hS("Symbol");return fS(e)&&mS(e.prototype,gS(a))}});var pr=b((yw,fc)=>{"use strict";var SS=String;fc.exports=function(a){try{return SS(a)}catch(e){return"Object"}}});var Tt=b((Tw,mc)=>{"use strict";var vS=de(),yS=pr(),TS=TypeError;mc.exports=function(a){if(vS(a))return a;throw new TS(yS(a)+" is not a function")}});var hr=b((Iw,bc)=>{"use strict";var IS=Tt(),ES=Ai();bc.exports=function(a,e){var t=a[e];return ES(t)?void 0:IS(t)}});var Sc=b((Ew,gc)=>{"use strict";var kn=Ve(),Rn=de(),$n=Ge(),xS=TypeError;gc.exports=function(a,e){var t,i;if(e==="string"&&Rn(t=a.toString)&&!$n(i=kn(t,a))||Rn(t=a.valueOf)&&!$n(i=kn(t,a))||e!=="string"&&Rn(t=a.toString)&&!$n(i=kn(t,a)))return i;throw new xS("Can't convert object to primitive value")}});var rt=b((xw,vc)=>{"use strict";vc.exports=!0});var Ic=b((Pw,Tc)=>{"use strict";var yc=pe(),PS=Object.defineProperty;Tc.exports=function(a,e){try{PS(yc,a,{value:e,configurable:!0,writable:!0})}catch(t){yc[a]=e}return e}});var fr=b((Aw,Pc)=>{"use strict";var AS=rt(),wS=pe(),kS=Ic(),Ec="__core-js_shared__",xc=Pc.exports=wS[Ec]||kS(Ec,{});(xc.versions||(xc.versions=[])).push({version:"3.38.0",mode:AS?"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 Ln=b((ww,wc)=>{"use strict";var Ac=fr();wc.exports=function(a,e){return Ac[a]||(Ac[a]=e||{})}});var mr=b((kw,kc)=>{"use strict";var RS=lr(),$S=Object;kc.exports=function(a){return $S(RS(a))}});var at=b((Rw,Rc)=>{"use strict";var LS=we(),MS=mr(),CS=LS({}.hasOwnProperty);Rc.exports=Object.hasOwn||function(e,t){return CS(MS(e),t)}});var Mn=b(($w,$c)=>{"use strict";var DS=we(),BS=0,VS=Math.random(),OS=DS(1 .toString);$c.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+OS(++BS+VS,36)}});var Pe=b((Lw,Mc)=>{"use strict";var _S=pe(),NS=Ln(),Lc=at(),FS=Mn(),qS=Pn(),US=An(),Ri=_S.Symbol,Cn=NS("wks"),HS=US?Ri.for||Ri:Ri&&Ri.withoutSetter||FS;Mc.exports=function(a){return Lc(Cn,a)||(Cn[a]=qS&&Lc(Ri,a)?Ri[a]:HS("Symbol."+a)),Cn[a]}});var Vc=b((Mw,Bc)=>{"use strict";var jS=Ve(),Cc=Ge(),Dc=wn(),GS=hr(),QS=Sc(),WS=Pe(),YS=TypeError,zS=WS("toPrimitive");Bc.exports=function(a,e){if(!Cc(a)||Dc(a))return a;var t=GS(a,zS),i;if(t){if(e===void 0&&(e="default"),i=jS(t,a,e),!Cc(i)||Dc(i))return i;throw new YS("Can't convert object to primitive value")}return e===void 0&&(e="number"),QS(a,e)}});var Dn=b((Cw,Oc)=>{"use strict";var KS=Vc(),JS=wn();Oc.exports=function(a){var e=KS(a,"string");return JS(e)?e:e+""}});var ai=b(Nc=>{"use strict";var XS=Qe(),ZS=vn(),ev=yn(),Ja=dt(),_c=Dn(),tv=TypeError,Bn=Object.defineProperty,iv=Object.getOwnPropertyDescriptor,Vn="enumerable",On="configurable",_n="writable";Nc.f=XS?ev?function(e,t,i){if(Ja(e),t=_c(t),Ja(i),typeof e=="function"&&t==="prototype"&&"value"in i&&_n in i&&!i[_n]){var r=iv(e,t);r&&r[_n]&&(e[t]=i.value,i={configurable:On in i?i[On]:r[On],enumerable:Vn in i?i[Vn]:r[Vn],writable:!1})}return Bn(e,t,i)}:Bn:function(e,t,i){if(Ja(e),t=_c(t),Ja(i),ZS)try{return Bn(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new tv("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var br=b((Bw,Fc)=>{"use strict";Fc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var $i=b((Vw,qc)=>{"use strict";var rv=Qe(),av=ai(),sv=br();qc.exports=rv?function(a,e,t){return av.f(a,e,sv(1,t))}:function(a,e,t){return a[e]=t,a}});var Xa=b((Ow,Hc)=>{"use strict";var nv=Ln(),ov=Mn(),Uc=nv("keys");Hc.exports=function(a){return Uc[a]||(Uc[a]=ov(a))}});var Za=b((_w,jc)=>{"use strict";jc.exports={}});var Un=b((Nw,Wc)=>{"use strict";var uv=Ul(),Qc=pe(),lv=Ge(),cv=$i(),Nn=at(),Fn=fr(),dv=Xa(),pv=Za(),Gc="Object already initialized",qn=Qc.TypeError,hv=Qc.WeakMap,es,gr,ts,fv=function(a){return ts(a)?gr(a):es(a,{})},mv=function(a){return function(e){var t;if(!lv(e)||(t=gr(e)).type!==a)throw new qn("Incompatible receiver, "+a+" required");return t}};uv||Fn.state?(st=Fn.state||(Fn.state=new hv),st.get=st.get,st.has=st.has,st.set=st.set,es=function(a,e){if(st.has(a))throw new qn(Gc);return e.facade=a,st.set(a,e),e},gr=function(a){return st.get(a)||{}},ts=function(a){return st.has(a)}):(si=dv("state"),pv[si]=!0,es=function(a,e){if(Nn(a,si))throw new qn(Gc);return e.facade=a,cv(a,si,e),e},gr=function(a){return Nn(a,si)?a[si]:{}},ts=function(a){return Nn(a,si)});var st,si;Wc.exports={set:es,get:gr,has:ts,enforce:fv,getterFor:mv}});var Hn=b((Fw,Jc)=>{"use strict";var bv=ur(),Kc=Function.prototype,Yc=Kc.apply,zc=Kc.call;Jc.exports=typeof Reflect=="object"&&Reflect.apply||(bv?zc.bind(Yc):function(){return zc.apply(Yc,arguments)})});var jn=b((qw,Xc)=>{"use strict";var gv=Pi(),Sv=we();Xc.exports=function(a){if(gv(a)==="Function")return Sv(a)}});var id=b(td=>{"use strict";var Zc={}.propertyIsEnumerable,ed=Object.getOwnPropertyDescriptor,vv=ed&&!Zc.call({1:2},1);td.f=vv?function(e){var t=ed(this,e);return!!t&&t.enumerable}:Zc});var sd=b(ad=>{"use strict";var yv=Qe(),Tv=Ve(),Iv=id(),Ev=br(),xv=wi(),Pv=Dn(),Av=at(),wv=vn(),rd=Object.getOwnPropertyDescriptor;ad.f=yv?rd:function(e,t){if(e=xv(e),t=Pv(t),wv)try{return rd(e,t)}catch(i){}if(Av(e,t))return Ev(!Tv(Iv.f,e,t),e[t])}});var Gn=b((jw,nd)=>{"use strict";var kv=Be(),Rv=de(),$v=/#|\.prototype\./,Sr=function(a,e){var t=Mv[Lv(a)];return t===Dv?!0:t===Cv?!1:Rv(e)?kv(e):!!e},Lv=Sr.normalize=function(a){return String(a).replace($v,".").toLowerCase()},Mv=Sr.data={},Cv=Sr.NATIVE="N",Dv=Sr.POLYFILL="P";nd.exports=Sr});var vr=b((Gw,ud)=>{"use strict";var od=jn(),Bv=Tt(),Vv=ur(),Ov=od(od.bind);ud.exports=function(a,e){return Bv(a),e===void 0?a:Vv?Ov(a,e):function(){return a.apply(e,arguments)}}});var We=b((Qw,cd)=>{"use strict";var yr=pe(),_v=Hn(),Nv=jn(),Fv=de(),qv=sd().f,Uv=Gn(),Li=za(),Hv=vr(),Mi=$i(),ld=at();fr();var jv=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return _v(a,this,arguments)};return e.prototype=a.prototype,e};cd.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?yr:r?yr[t]:yr[t]&&yr[t].prototype,o=i?Li:Li[t]||Mi(Li,t,{})[t],u=o.prototype,l,d,c,p,h,m,g,S,x;for(p in e)l=Uv(i?p:t+(r?".":"#")+p,a.forced),d=!l&&n&&ld(n,p),m=o[p],d&&(a.dontCallGetSet?(x=qv(n,p),g=x&&x.value):g=n[p]),h=d&&g?g:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&d?S=Hv(h,yr):a.wrap&&d?S=jv(h):s&&Fv(h)?S=Nv(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&Mi(S,"sham",!0),Mi(o,p,S),s&&(c=t+"Prototype",ld(Li,c)||Mi(Li,c,{}),Mi(Li[c],p,h),a.real&&u&&(l||!u[p])&&Mi(u,p,h)))}});var hd=b((Ww,pd)=>{"use strict";var Qn=Qe(),Gv=at(),dd=Function.prototype,Qv=Qn&&Object.getOwnPropertyDescriptor,Wn=Gv(dd,"name"),Wv=Wn&&function(){}.name==="something",Yv=Wn&&(!Qn||Qn&&Qv(dd,"name").configurable);pd.exports={EXISTS:Wn,PROPER:Wv,CONFIGURABLE:Yv}});var md=b((Yw,fd)=>{"use strict";var zv=Math.ceil,Kv=Math.floor;fd.exports=Math.trunc||function(e){var t=+e;return(t>0?Kv:zv)(t)}});var is=b((zw,bd)=>{"use strict";var Jv=md();bd.exports=function(a){var e=+a;return e!==e||e===0?0:Jv(e)}});var Sd=b((Kw,gd)=>{"use strict";var Xv=is(),Zv=Math.max,ey=Math.min;gd.exports=function(a,e){var t=Xv(a);return t<0?Zv(t+e,0):ey(t,e)}});var yd=b((Jw,vd)=>{"use strict";var ty=is(),iy=Math.min;vd.exports=function(a){var e=ty(a);return e>0?iy(e,9007199254740991):0}});var rs=b((Xw,Td)=>{"use strict";var ry=yd();Td.exports=function(a){return ry(a.length)}});var xd=b((Zw,Ed)=>{"use strict";var ay=wi(),sy=Sd(),ny=rs(),Id=function(a){return function(e,t,i){var r=ay(e),s=ny(r);if(s===0)return!a&&-1;var n=sy(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};Ed.exports={includes:Id(!0),indexOf:Id(!1)}});var wd=b((ek,Ad)=>{"use strict";var oy=we(),Yn=at(),uy=wi(),ly=xd().indexOf,cy=Za(),Pd=oy([].push);Ad.exports=function(a,e){var t=uy(a),i=0,r=[],s;for(s in t)!Yn(cy,s)&&Yn(t,s)&&Pd(r,s);for(;e.length>i;)Yn(t,s=e[i++])&&(~ly(r,s)||Pd(r,s));return r}});var zn=b((tk,kd)=>{"use strict";kd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var $d=b((ik,Rd)=>{"use strict";var dy=wd(),py=zn();Rd.exports=Object.keys||function(e){return dy(e,py)}});var Md=b(Ld=>{"use strict";var hy=Qe(),fy=yn(),my=ai(),by=dt(),gy=wi(),Sy=$d();Ld.f=hy&&!fy?Object.defineProperties:function(e,t){by(e);for(var i=gy(t),r=Sy(t),s=r.length,n=0,o;s>n;)my.f(e,o=r[n++],i[o]);return e}});var Kn=b((ak,Cd)=>{"use strict";var vy=yt();Cd.exports=vy("document","documentElement")});var eo=b((sk,Fd)=>{"use strict";var yy=dt(),Ty=Md(),Dd=zn(),Iy=Za(),Ey=Kn(),xy=Wa(),Py=Xa(),Bd=">",Vd="<",Xn="prototype",Zn="script",_d=Py("IE_PROTO"),Jn=function(){},Nd=function(a){return Vd+Zn+Bd+a+Vd+"/"+Zn+Bd},Od=function(a){a.write(Nd("")),a.close();var e=a.parentWindow.Object;return a=null,e},Ay=function(){var a=xy("iframe"),e="java"+Zn+":",t;return a.style.display="none",Ey.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Nd("document.F=Object")),t.close(),t.F},as,ss=function(){try{as=new ActiveXObject("htmlfile")}catch(e){}ss=typeof document!="undefined"?document.domain&&as?Od(as):Ay():Od(as);for(var a=Dd.length;a--;)delete ss[Xn][Dd[a]];return ss()};Iy[_d]=!0;Fd.exports=Object.create||function(e,t){var i;return e!==null?(Jn[Xn]=yy(e),i=new Jn,Jn[Xn]=null,i[_d]=e):i=ss(),t===void 0?i:Ty.f(i,t)}});var Ud=b((nk,qd)=>{"use strict";var wy=Be();qd.exports=!wy(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var io=b((ok,jd)=>{"use strict";var ky=at(),Ry=de(),$y=mr(),Ly=Xa(),My=Ud(),Hd=Ly("IE_PROTO"),to=Object,Cy=to.prototype;jd.exports=My?to.getPrototypeOf:function(a){var e=$y(a);if(ky(e,Hd))return e[Hd];var t=e.constructor;return Ry(t)&&e instanceof t?t.prototype:e instanceof to?Cy:null}});var Ci=b((uk,Gd)=>{"use strict";var Dy=$i();Gd.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:Dy(a,e,t),a}});var no=b((lk,Yd)=>{"use strict";var By=Be(),Vy=de(),Oy=Ge(),_y=eo(),Qd=io(),Ny=Ci(),Fy=Pe(),qy=rt(),so=Fy("iterator"),Wd=!1,It,ro,ao;[].keys&&(ao=[].keys(),"next"in ao?(ro=Qd(Qd(ao)),ro!==Object.prototype&&(It=ro)):Wd=!0);var Uy=!Oy(It)||By(function(){var a={};return It[so].call(a)!==a});Uy?It={}:qy&&(It=_y(It));Vy(It[so])||Ny(It,so,function(){return this});Yd.exports={IteratorPrototype:It,BUGGY_SAFARI_ITERATORS:Wd}});var ns=b((ck,Kd)=>{"use strict";var Hy=Pe(),jy=Hy("toStringTag"),zd={};zd[jy]="z";Kd.exports=String(zd)==="[object z]"});var Tr=b((dk,Jd)=>{"use strict";var Gy=ns(),Qy=de(),os=Pi(),Wy=Pe(),Yy=Wy("toStringTag"),zy=Object,Ky=os(function(){return arguments}())==="Arguments",Jy=function(a,e){try{return a[e]}catch(t){}};Jd.exports=Gy?os:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=Jy(e=zy(a),Yy))=="string"?t:Ky?os(e):(i=os(e))==="Object"&&Qy(e.callee)?"Arguments":i}});var Zd=b((pk,Xd)=>{"use strict";var Xy=ns(),Zy=Tr();Xd.exports=Xy?{}.toString:function(){return"[object "+Zy(this)+"]"}});var Ir=b((hk,tp)=>{"use strict";var eT=ns(),tT=ai().f,iT=$i(),rT=at(),aT=Zd(),sT=Pe(),ep=sT("toStringTag");tp.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(rT(r,ep)||tT(r,ep,{configurable:!0,value:e}),i&&!eT&&iT(r,"toString",aT))}});var rp=b((fk,ip)=>{"use strict";var nT=no().IteratorPrototype,oT=eo(),uT=br(),lT=Ir(),cT=ri(),dT=function(){return this};ip.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=oT(nT,{next:uT(+!i,t)}),lT(a,r,!1,!0),cT[r]=dT,a}});var sp=b((mk,ap)=>{"use strict";var pT=we(),hT=Tt();ap.exports=function(a,e,t){try{return pT(hT(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var op=b((bk,np)=>{"use strict";var fT=Ge();np.exports=function(a){return fT(a)||a===null}});var lp=b((gk,up)=>{"use strict";var mT=op(),bT=String,gT=TypeError;up.exports=function(a){if(mT(a))return a;throw new gT("Can't set "+bT(a)+" as a prototype")}});var oo=b((Sk,cp)=>{"use strict";var ST=sp(),vT=Ge(),yT=lr(),TT=lp();cp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=ST(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return yT(r),TT(s),vT(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Tp=b((vk,yp)=>{"use strict";var IT=We(),ET=Ve(),us=rt(),Sp=hd(),xT=de(),PT=rp(),dp=io(),pp=oo(),AT=Ir(),wT=$i(),uo=Ci(),kT=Pe(),hp=ri(),vp=no(),RT=Sp.PROPER,$T=Sp.CONFIGURABLE,fp=vp.IteratorPrototype,ls=vp.BUGGY_SAFARI_ITERATORS,Er=kT("iterator"),mp="keys",xr="values",bp="entries",gp=function(){return this};yp.exports=function(a,e,t,i,r,s,n){PT(t,e,i);var o=function(x){if(x===r&&p)return p;if(!ls&&x&&x in d)return d[x];switch(x){case mp:return function(){return new t(this,x)};case xr:return function(){return new t(this,x)};case bp:return function(){return new t(this,x)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=a.prototype,c=d[Er]||d["@@iterator"]||r&&d[r],p=!ls&&c||o(r),h=e==="Array"&&d.entries||c,m,g,S;if(h&&(m=dp(h.call(new a)),m!==Object.prototype&&m.next&&(!us&&dp(m)!==fp&&(pp?pp(m,fp):xT(m[Er])||uo(m,Er,gp)),AT(m,u,!0,!0),us&&(hp[u]=gp))),RT&&r===xr&&c&&c.name!==xr&&(!us&&$T?wT(d,"name",xr):(l=!0,p=function(){return ET(c,this)})),r)if(g={values:o(xr),keys:s?p:o(mp),entries:o(bp)},n)for(S in g)(ls||l||!(S in d))&&uo(d,S,g[S]);else IT({target:e,proto:!0,forced:ls||l},g);return(!us||n)&&d[Er]!==p&&uo(d,Er,p,{name:r}),hp[e]=p,g}});var Ep=b((yk,Ip)=>{"use strict";Ip.exports=function(a,e){return{value:a,done:e}}});var co=b((Tk,kp)=>{"use strict";var LT=wi(),lo=mn(),xp=ri(),Ap=Un(),MT=ai().f,CT=Tp(),cs=Ep(),DT=rt(),BT=Qe(),wp="Array Iterator",VT=Ap.set,OT=Ap.getterFor(wp);kp.exports=CT(Array,"Array",function(a,e){VT(this,{type:wp,target:LT(a),index:0,kind:e})},function(){var a=OT(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,cs(void 0,!0);switch(a.kind){case"keys":return cs(t,!1);case"values":return cs(e[t],!1)}return cs([t,e[t]],!1)},"values");var Pp=xp.Arguments=xp.Array;lo("keys");lo("values");lo("entries");if(!DT&&BT&&Pp.name!=="values")try{MT(Pp,"name",{value:"values"})}catch(a){}});var $p=b((Ik,Rp)=>{"use strict";var _T=Pe(),NT=ri(),FT=_T("iterator"),qT=Array.prototype;Rp.exports=function(a){return a!==void 0&&(NT.Array===a||qT[FT]===a)}});var po=b((Ek,Mp)=>{"use strict";var UT=Tr(),Lp=hr(),HT=Ai(),jT=ri(),GT=Pe(),QT=GT("iterator");Mp.exports=function(a){if(!HT(a))return Lp(a,QT)||Lp(a,"@@iterator")||jT[UT(a)]}});var Dp=b((xk,Cp)=>{"use strict";var WT=Ve(),YT=Tt(),zT=dt(),KT=pr(),JT=po(),XT=TypeError;Cp.exports=function(a,e){var t=arguments.length<2?JT(a):e;if(YT(t))return zT(WT(t,a));throw new XT(KT(a)+" is not iterable")}});var Op=b((Pk,Vp)=>{"use strict";var ZT=Ve(),Bp=dt(),eI=hr();Vp.exports=function(a,e,t){var i,r;Bp(a);try{if(i=eI(a,"return"),!i){if(e==="throw")throw t;return t}i=ZT(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Bp(i),t}});var ps=b((Ak,qp)=>{"use strict";var tI=vr(),iI=Ve(),rI=dt(),aI=pr(),sI=$p(),nI=rs(),_p=dr(),oI=Dp(),uI=po(),Np=Op(),lI=TypeError,ds=function(a,e){this.stopped=a,this.result=e},Fp=ds.prototype;qp.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=tI(e,i),l,d,c,p,h,m,g,S=function(T){return l&&Np(l,"normal",T),new ds(!0,T)},x=function(T){return r?(rI(T),o?u(T[0],T[1],S):u(T[0],T[1])):o?u(T,S):u(T)};if(s)l=a.iterator;else if(n)l=a;else{if(d=uI(a),!d)throw new lI(aI(a)+" is not iterable");if(sI(d)){for(c=0,p=nI(a);p>c;c++)if(h=x(a[c]),h&&_p(Fp,h))return h;return new ds(!1)}l=oI(a,d)}for(m=s?a.next:l.next;!(g=iI(m,l)).done;){try{h=x(g.value)}catch(T){Np(l,"throw",T)}if(typeof h=="object"&&h&&_p(Fp,h))return h}return new ds(!1)}});var Hp=b((wk,Up)=>{"use strict";var cI=Qe(),dI=ai(),pI=br();Up.exports=function(a,e,t){cI?dI.f(a,e,pI(0,t)):a[e]=t}});var jp=b(()=>{"use strict";var hI=We(),fI=ps(),mI=Hp();hI({target:"Object",stat:!0},{fromEntries:function(e){var t={};return fI(e,function(i,r){mI(t,i,r)},{AS_ENTRIES:!0}),t}})});var Qp=b(($k,Gp)=>{"use strict";co();jp();var bI=za();Gp.exports=bI.Object.fromEntries});var Yp=b((Lk,Wp)=>{"use strict";Wp.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 Kp=b(()=>{"use strict";co();var gI=Yp(),SI=pe(),vI=Ir(),zp=ri();for(hs in gI)vI(SI[hs],hs),zp[hs]=zp.Array;var hs});var Xp=b((Dk,Jp)=>{"use strict";var yI=Qp();Kp();Jp.exports=yI});var ho=b((Bk,Zp)=>{"use strict";var TI=Xp();Zp.exports=TI});var eh=b(()=>{"use strict"});var fo=b((_k,th)=>{"use strict";var Pr=pe(),II=ki(),EI=Pi(),fs=function(a){return II.slice(0,a.length)===a};th.exports=function(){return fs("Bun/")?"BUN":fs("Cloudflare-Workers")?"CLOUDFLARE":fs("Deno/")?"DENO":fs("Node.js/")?"NODE":Pr.Bun&&typeof Bun.version=="string"?"BUN":Pr.Deno&&typeof Deno.version=="object"?"DENO":EI(Pr.process)==="process"?"NODE":Pr.window&&Pr.document?"BROWSER":"REST"}()});var ms=b((Nk,ih)=>{"use strict";var xI=fo();ih.exports=xI==="NODE"});var ah=b((Fk,rh)=>{"use strict";var PI=ai();rh.exports=function(a,e,t){return PI.f(a,e,t)}});var oh=b((qk,nh)=>{"use strict";var AI=yt(),wI=ah(),kI=Pe(),RI=Qe(),sh=kI("species");nh.exports=function(a){var e=AI(a);RI&&e&&!e[sh]&&wI(e,sh,{configurable:!0,get:function(){return this}})}});var lh=b((Uk,uh)=>{"use strict";var $I=dr(),LI=TypeError;uh.exports=function(a,e){if($I(e,a))return a;throw new LI("Incorrect invocation")}});var bo=b((Hk,ch)=>{"use strict";var MI=we(),CI=de(),mo=fr(),DI=MI(Function.toString);CI(mo.inspectSource)||(mo.inspectSource=function(a){return DI(a)});ch.exports=mo.inspectSource});var bh=b((jk,mh)=>{"use strict";var BI=we(),VI=Be(),dh=de(),OI=Tr(),_I=yt(),NI=bo(),ph=function(){},hh=_I("Reflect","construct"),go=/^\s*(?:class|function)\b/,FI=BI(go.exec),qI=!go.test(ph),Ar=function(e){if(!dh(e))return!1;try{return hh(ph,[],e),!0}catch(t){return!1}},fh=function(e){if(!dh(e))return!1;switch(OI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return qI||!!FI(go,NI(e))}catch(t){return!0}};fh.sham=!0;mh.exports=!hh||VI(function(){var a;return Ar(Ar.call)||!Ar(Object)||!Ar(function(){a=!0})||a})?fh:Ar});var Sh=b((Gk,gh)=>{"use strict";var UI=bh(),HI=pr(),jI=TypeError;gh.exports=function(a){if(UI(a))return a;throw new jI(HI(a)+" is not a constructor")}});var So=b((Qk,yh)=>{"use strict";var vh=dt(),GI=Sh(),QI=Ai(),WI=Pe(),YI=WI("species");yh.exports=function(a,e){var t=vh(a).constructor,i;return t===void 0||QI(i=vh(t)[YI])?e:GI(i)}});var Ih=b((Wk,Th)=>{"use strict";var zI=we();Th.exports=zI([].slice)});var xh=b((Yk,Eh)=>{"use strict";var KI=TypeError;Eh.exports=function(a,e){if(a<e)throw new KI("Not enough arguments");return a}});var vo=b((zk,Ph)=>{"use strict";var JI=ki();Ph.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(JI)});var ko=b((Kk,Dh)=>{"use strict";var Oe=pe(),XI=Hn(),ZI=vr(),Ah=de(),eE=at(),Ch=Be(),wh=Kn(),tE=Ih(),kh=Wa(),iE=xh(),rE=vo(),aE=ms(),Po=Oe.setImmediate,Ao=Oe.clearImmediate,sE=Oe.process,yo=Oe.Dispatch,nE=Oe.Function,Rh=Oe.MessageChannel,oE=Oe.String,To=0,wr={},$h="onreadystatechange",kr,ni,Io,Eo;Ch(function(){kr=Oe.location});var wo=function(a){if(eE(wr,a)){var e=wr[a];delete wr[a],e()}},xo=function(a){return function(){wo(a)}},Lh=function(a){wo(a.data)},Mh=function(a){Oe.postMessage(oE(a),kr.protocol+"//"+kr.host)};(!Po||!Ao)&&(Po=function(e){iE(arguments.length,1);var t=Ah(e)?e:nE(e),i=tE(arguments,1);return wr[++To]=function(){XI(t,void 0,i)},ni(To),To},Ao=function(e){delete wr[e]},aE?ni=function(a){sE.nextTick(xo(a))}:yo&&yo.now?ni=function(a){yo.now(xo(a))}:Rh&&!rE?(Io=new Rh,Eo=Io.port2,Io.port1.onmessage=Lh,ni=ZI(Eo.postMessage,Eo)):Oe.addEventListener&&Ah(Oe.postMessage)&&!Oe.importScripts&&kr&&kr.protocol!=="file:"&&!Ch(Mh)?(ni=Mh,Oe.addEventListener("message",Lh,!1)):$h in kh("script")?ni=function(a){wh.appendChild(kh("script"))[$h]=function(){wh.removeChild(this),wo(a)}}:ni=function(a){setTimeout(xo(a),0)});Dh.exports={set:Po,clear:Ao}});var Oh=b((Jk,Vh)=>{"use strict";var Bh=pe(),uE=Qe(),lE=Object.getOwnPropertyDescriptor;Vh.exports=function(a){if(!uE)return Bh[a];var e=lE(Bh,a);return e&&e.value}});var Ro=b((Xk,Nh)=>{"use strict";var _h=function(){this.head=null,this.tail=null};_h.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}}};Nh.exports=_h});var qh=b((Zk,Fh)=>{"use strict";var cE=ki();Fh.exports=/ipad|iphone|ipod/i.test(cE)&&typeof Pebble!="undefined"});var Hh=b((eR,Uh)=>{"use strict";var dE=ki();Uh.exports=/web0s(?!.*chrome)/i.test(dE)});var Kh=b((tR,zh)=>{"use strict";var Bi=pe(),pE=Oh(),jh=vr(),$o=ko().set,hE=Ro(),fE=vo(),mE=qh(),bE=Hh(),Lo=ms(),Gh=Bi.MutationObserver||Bi.WebKitMutationObserver,Qh=Bi.document,Wh=Bi.process,bs=Bi.Promise,Do=pE("queueMicrotask"),Di,Mo,Co,gs,Yh;Do||(Rr=new hE,$r=function(){var a,e;for(Lo&&(a=Wh.domain)&&a.exit();e=Rr.get();)try{e()}catch(t){throw Rr.head&&Di(),t}a&&a.enter()},!fE&&!Lo&&!bE&&Gh&&Qh?(Mo=!0,Co=Qh.createTextNode(""),new Gh($r).observe(Co,{characterData:!0}),Di=function(){Co.data=Mo=!Mo}):!mE&&bs&&bs.resolve?(gs=bs.resolve(void 0),gs.constructor=bs,Yh=jh(gs.then,gs),Di=function(){Yh($r)}):Lo?Di=function(){Wh.nextTick($r)}:($o=jh($o,Bi),Di=function(){$o($r)}),Do=function(a){Rr.head||Di(),Rr.add(a)});var Rr,$r;zh.exports=Do});var Xh=b((iR,Jh)=>{"use strict";Jh.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ss=b((rR,Zh)=>{"use strict";Zh.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var oi=b((aR,ef)=>{"use strict";var gE=pe();ef.exports=gE.Promise});var Vi=b((sR,sf)=>{"use strict";var SE=pe(),Lr=oi(),vE=de(),yE=Gn(),TE=bo(),IE=Pe(),tf=fo(),EE=rt(),Bo=xn(),rf=Lr&&Lr.prototype,xE=IE("species"),Vo=!1,af=vE(SE.PromiseRejectionEvent),PE=yE("Promise",function(){var a=TE(Lr),e=a!==String(Lr);if(!e&&Bo===66||EE&&!(rf.catch&&rf.finally))return!0;if(!Bo||Bo<51||!/native code/.test(a)){var t=new Lr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[xE]=i,Vo=t.then(function(){})instanceof i,!Vo)return!0}return!e&&(tf==="BROWSER"||tf==="DENO")&&!af});sf.exports={CONSTRUCTOR:PE,REJECTION_EVENT:af,SUBCLASSING:Vo}});var Oi=b((nR,of)=>{"use strict";var nf=Tt(),AE=TypeError,wE=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new AE("Bad Promise constructor");e=i,t=r}),this.resolve=nf(e),this.reject=nf(t)};of.exports.f=function(a){return new wE(a)}});var Af=b(()=>{"use strict";var kE=We(),RE=rt(),Is=ms(),Ut=pe(),qi=Ve(),uf=Ci(),lf=oo(),$E=Ir(),LE=oh(),ME=Tt(),Ts=de(),CE=Ge(),DE=lh(),BE=So(),ff=ko().set,qo=Kh(),VE=Xh(),OE=Ss(),_E=Ro(),mf=Un(),Es=oi(),Uo=Vi(),bf=Oi(),xs="Promise",gf=Uo.CONSTRUCTOR,NE=Uo.REJECTION_EVENT,FE=Uo.SUBCLASSING,Oo=mf.getterFor(xs),qE=mf.set,_i=Es&&Es.prototype,ui=Es,vs=_i,Sf=Ut.TypeError,_o=Ut.document,Ho=Ut.process,No=bf.f,UE=No,HE=!!(_o&&_o.createEvent&&Ut.dispatchEvent),vf="unhandledrejection",jE="rejectionhandled",cf=0,yf=1,GE=2,jo=1,Tf=2,ys,df,QE,pf,If=function(a){var e;return CE(a)&&Ts(e=a.then)?e:!1},Ef=function(a,e){var t=e.value,i=e.state===yf,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,d;try{r?(i||(e.rejection===Tf&&YE(e),e.rejection=jo),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===a.promise?n(new Sf("Promise-chain cycle")):(l=If(u))?qi(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},xf=function(a,e){a.notified||(a.notified=!0,qo(function(){for(var t=a.reactions,i;i=t.get();)Ef(i,a);a.notified=!1,e&&!a.rejection&&WE(a)}))},Pf=function(a,e,t){var i,r;HE?(i=_o.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Ut.dispatchEvent(i)):i={promise:e,reason:t},!NE&&(r=Ut["on"+a])?r(i):a===vf&&VE("Unhandled promise rejection",t)},WE=function(a){qi(ff,Ut,function(){var e=a.facade,t=a.value,i=hf(a),r;if(i&&(r=OE(function(){Is?Ho.emit("unhandledRejection",t,e):Pf(vf,e,t)}),a.rejection=Is||hf(a)?Tf:jo,r.error))throw r.value})},hf=function(a){return a.rejection!==jo&&!a.parent},YE=function(a){qi(ff,Ut,function(){var e=a.facade;Is?Ho.emit("rejectionHandled",e):Pf(jE,e,a.value)})},Ni=function(a,e,t){return function(i){a(e,i,t)}},Fi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=GE,xf(a,!0))},Fo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Sf("Promise can't be resolved itself");var i=If(e);i?qo(function(){var r={done:!1};try{qi(i,e,Ni(Fo,r,a),Ni(Fi,r,a))}catch(s){Fi(r,s,a)}}):(a.value=e,a.state=yf,xf(a,!1))}catch(r){Fi({done:!1},r,a)}}};if(gf&&(ui=function(e){DE(this,vs),ME(e),qi(ys,this);var t=Oo(this);try{e(Ni(Fo,t),Ni(Fi,t))}catch(i){Fi(t,i)}},vs=ui.prototype,ys=function(e){qE(this,{type:xs,done:!1,notified:!1,parent:!1,reactions:new _E,rejection:!1,state:cf,value:void 0})},ys.prototype=uf(vs,"then",function(e,t){var i=Oo(this),r=No(BE(this,ui));return i.parent=!0,r.ok=Ts(e)?e:!0,r.fail=Ts(t)&&t,r.domain=Is?Ho.domain:void 0,i.state===cf?i.reactions.add(r):qo(function(){Ef(r,i)}),r.promise}),df=function(){var a=new ys,e=Oo(a);this.promise=a,this.resolve=Ni(Fo,e),this.reject=Ni(Fi,e)},bf.f=No=function(a){return a===ui||a===QE?new df(a):UE(a)},!RE&&Ts(Es)&&_i!==Object.prototype)){pf=_i.then,FE||uf(_i,"then",function(e,t){var i=this;return new ui(function(r,s){qi(pf,i,r,s)}).then(e,t)},{unsafe:!0});try{delete _i.constructor}catch(a){}lf&&lf(_i,vs)}kE({global:!0,constructor:!0,wrap:!0,forced:gf},{Promise:ui});$E(ui,xs,!1,!0);LE(xs)});var Lf=b((lR,$f)=>{"use strict";var zE=Pe(),kf=zE("iterator"),Rf=!1;try{wf=0,Go={next:function(){return{done:!!wf++}},return:function(){Rf=!0}},Go[kf]=function(){return this},Array.from(Go,function(){throw 2})}catch(a){}var wf,Go;$f.exports=function(a,e){try{if(!e&&!Rf)return!1}catch(r){return!1}var t=!1;try{var i={};i[kf]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Qo=b((cR,Mf)=>{"use strict";var KE=oi(),JE=Lf(),XE=Vi().CONSTRUCTOR;Mf.exports=XE||!JE(function(a){KE.all(a).then(void 0,function(){})})});var Cf=b(()=>{"use strict";var ZE=We(),ex=Ve(),tx=Tt(),ix=Oi(),rx=Ss(),ax=ps(),sx=Qo();ZE({target:"Promise",stat:!0,forced:sx},{all:function(e){var t=this,i=ix.f(t),r=i.resolve,s=i.reject,n=rx(function(){var o=tx(t.resolve),u=[],l=0,d=1;ax(e,function(c){var p=l++,h=!1;d++,ex(o,t,c).then(function(m){h||(h=!0,u[p]=m,--d||r(u))},s)}),--d||r(u)});return n.error&&s(n.value),i.promise}})});var Bf=b(()=>{"use strict";var nx=We(),ox=rt(),ux=Vi().CONSTRUCTOR,Yo=oi(),lx=yt(),cx=de(),dx=Ci(),Df=Yo&&Yo.prototype;nx({target:"Promise",proto:!0,forced:ux,real:!0},{catch:function(a){return this.then(void 0,a)}});!ox&&cx(Yo)&&(Wo=lx("Promise").prototype.catch,Df.catch!==Wo&&dx(Df,"catch",Wo,{unsafe:!0}));var Wo});var Vf=b(()=>{"use strict";var px=We(),hx=Ve(),fx=Tt(),mx=Oi(),bx=Ss(),gx=ps(),Sx=Qo();px({target:"Promise",stat:!0,forced:Sx},{race:function(e){var t=this,i=mx.f(t),r=i.reject,s=bx(function(){var n=fx(t.resolve);gx(e,function(o){hx(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Of=b(()=>{"use strict";var vx=We(),yx=Oi(),Tx=Vi().CONSTRUCTOR;vx({target:"Promise",stat:!0,forced:Tx},{reject:function(e){var t=yx.f(this),i=t.reject;return i(e),t.promise}})});var zo=b((vR,_f)=>{"use strict";var Ix=dt(),Ex=Ge(),xx=Oi();_f.exports=function(a,e){if(Ix(a),Ex(e)&&e.constructor===a)return e;var t=xx.f(a),i=t.resolve;return i(e),t.promise}});var qf=b(()=>{"use strict";var Px=We(),Ax=yt(),Nf=rt(),wx=oi(),Ff=Vi().CONSTRUCTOR,kx=zo(),Rx=Ax("Promise"),$x=Nf&&!Ff;Px({target:"Promise",stat:!0,forced:Nf||Ff},{resolve:function(e){return kx($x&&this===Rx?wx:this,e)}})});var Uf=b(()=>{"use strict";Af();Cf();Bf();Vf();Of();qf()});var Qf=b(()=>{"use strict";var Lx=We(),Mx=rt(),Ps=oi(),Cx=Be(),jf=yt(),Gf=de(),Dx=So(),Hf=zo(),Bx=Ci(),Jo=Ps&&Ps.prototype,Vx=!!Ps&&Cx(function(){Jo.finally.call({then:function(){}},function(){})});Lx({target:"Promise",proto:!0,real:!0,forced:Vx},{finally:function(a){var e=Dx(this,jf("Promise")),t=Gf(a);return this.then(t?function(i){return Hf(e,a()).then(function(){return i})}:a,t?function(i){return Hf(e,a()).then(function(){throw i})}:a)}});!Mx&&Gf(Ps)&&(Ko=jf("Promise").prototype.finally,Jo.finally!==Ko&&Bx(Jo,"finally",Ko,{unsafe:!0}));var Ko});var As=b((AR,Wf)=>{"use strict";var Ox=yt();Wf.exports=Ox});var zf=b((wR,Yf)=>{"use strict";eh();Uf();Qf();var _x=As();Yf.exports=_x("Promise","finally")});var Jf=b((kR,Kf)=>{"use strict";var Nx=zf();Kf.exports=Nx});var ws=b((RR,Xf)=>{"use strict";var Fx=Jf();Xf.exports=Fx});var um=b(()=>{"use strict";var Yx=We(),zx=mr(),Kx=rs(),Jx=is(),Xx=mn();Yx({target:"Array",proto:!0},{at:function(e){var t=zx(this),i=Kx(t),r=Jx(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});Xx("at")});var cm=b((w$,lm)=>{"use strict";um();var Zx=As();lm.exports=Zx("Array","at")});var pm=b((k$,dm)=>{"use strict";var eP=cm();dm.exports=eP});var Ui=b((R$,hm)=>{"use strict";var tP=pm();hm.exports=tP});var nb=b(()=>{"use strict"});var ob=b(()=>{"use strict"});var lb=b((wD,ub)=>{"use strict";var OP=Ge(),_P=Pi(),NP=Pe(),FP=NP("match");ub.exports=function(a){var e;return OP(a)&&((e=a[FP])!==void 0?!!e:_P(a)==="RegExp")}});var db=b((kD,cb)=>{"use strict";var qP=Tr(),UP=String;cb.exports=function(a){if(qP(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return UP(a)}});var hb=b((RD,pb)=>{"use strict";var HP=dt();pb.exports=function(){var a=HP(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 bb=b(($D,mb)=>{"use strict";var jP=Ve(),GP=at(),QP=dr(),WP=hb(),fb=RegExp.prototype;mb.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in fb)&&!GP(a,"flags")&&QP(fb,a)?jP(WP,a):e}});var Sb=b((LD,gb)=>{"use strict";var yu=we(),YP=mr(),zP=Math.floor,Su=yu("".charAt),KP=yu("".replace),vu=yu("".slice),JP=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,XP=/\$([$&'`]|\d{1,2})/g;gb.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=XP;return r!==void 0&&(r=YP(r),u=JP),KP(s,u,function(l,d){var c;switch(Su(d,0)){case"$":return"$";case"&":return a;case"`":return vu(e,0,t);case"'":return vu(e,n);case"<":c=r[vu(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=zP(p/10);return h===0?l:h<=o?i[h-1]===void 0?Su(d,1):i[h-1]+Su(d,1):l}c=i[p-1]}return c===void 0?"":c})}});var Tb=b(()=>{"use strict";var ZP=We(),eA=Ve(),Iu=we(),vb=lr(),tA=de(),iA=Ai(),rA=lb(),zi=db(),aA=hr(),sA=bb(),nA=Sb(),oA=Pe(),uA=rt(),lA=oA("replace"),cA=TypeError,Tu=Iu("".indexOf),dA=Iu("".replace),yb=Iu("".slice),pA=Math.max;ZP({target:"String",proto:!0},{replaceAll:function(e,t){var i=vb(this),r,s,n,o,u,l,d,c,p,h,m=0,g="";if(!iA(e)){if(r=rA(e),r&&(s=zi(vb(sA(e))),!~Tu(s,"g")))throw new cA("`.replaceAll` does not allow non-global regexes");if(n=aA(e,lA),n)return eA(n,e,i,t);if(uA&&r)return dA(zi(i),e,t)}for(o=zi(i),u=zi(e),l=tA(t),l||(t=zi(t)),d=u.length,c=pA(1,d),p=Tu(o,u);p!==-1;)h=l?zi(t(u,p,o)):nA(u,o,p,[],void 0,t),g+=yb(o,m,p)+h,m=p+d,p=p+c>o.length?-1:Tu(o,u,p+c);return m<o.length&&(g+=yb(o,m)),g}})});var Eb=b((DD,Ib)=>{"use strict";nb();ob();Tb();var hA=As();Ib.exports=hA("String","replaceAll")});var Pb=b((BD,xb)=>{"use strict";var fA=Eb();xb.exports=fA});var wb=b((VD,Ab)=>{"use strict";var mA=Pb();Ab.exports=mA});var CA={};$g(CA,{ChromecastState:()=>or,HttpConnectionType:()=>ja,Observable:()=>gt.Observable,PlaybackState:()=>xe,Player:()=>Ra,SDK_VERSION:()=>MA,Subject:()=>gt.Subject,Subscription:()=>gt.Subscription,Surface:()=>Ga,VERSION:()=>pn,ValueSubject:()=>gt.ValueSubject,VideoFormat:()=>vt,VideoQuality:()=>gt.VideoQuality});module.exports=Lg(CA);var pn="2.0.117";var xe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(xe||{}),vt=(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))(vt||{});var or=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(or||{}),ja=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(ja||{});var Ga=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ga||{});var q=require("@vkontakte/videoplayer-shared");var El=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Qa=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 i=(0,q.isNonNullable)((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},r||El("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 i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,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),i=cast.framework.CastContext.getInstance();this.subscription.add((0,q.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,q.assertNever)(r.sessionState)}})).add((0,q.merge)((0,q.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,q.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,q.map)(r=>r.castState)),(0,q.observableFrom)([i.getCastState()])).pipe((0,q.filterChanged)(),(0,q.map)(Mg),(0,q.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=(0,q.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();(0,q.assertNonNullable)(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,q.isNullable)(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,q.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:q.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Mg=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 eg=je(ho(),1);var im=je(ws(),1);var Xo=require("@vkontakte/videoplayer-shared");var Ie=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Xo.assertNever)(t)}return a},Zo=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Xo.assertNever)(e)}};var k=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var pt=require("@vkontakte/videoplayer-shared"),j=class{constructor(e){this.transitionStarted$=new pt.Subject;this.transitionEnded$=new pt.Subject;this.transitionUpdated$=new pt.Subject;this.forceChanged$=new pt.Subject;this.stateChangeStarted$=(0,pt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,pt.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,pt.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Zf=require("@vkontakte/videoplayer-shared"),em=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,Zf.assertNever)(a)}};var L=require("@vkontakte/videoplayer-shared");var qx=5,Ux=5,Hx=500,tm=7e3,Mr=class{constructor(e){this.subscription=new L.Subscription;this.loadMediaTimeoutSubscription=new L.Subscription;this.videoState=new j("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.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,L.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,L.assertNever)(e)}break}default:(0,L.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(em(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 L.Subscription;this.subscription.add(e),this.subscription.add((0,L.merge)(this.videoState.stateChangeStarted$.pipe((0,L.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,L.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new L.Subject;e.add(r.pipe((0,L.debounce)(Hx)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,L.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)>qx)&&r.next(o),s=o})),e.add((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Ux&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,L.assertNever)(n)}}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,L.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,L.observableFrom)(["init"])).pipe((0,L.debounce)(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let d=t[e];(0,L.assertNonNullable)(d);let c=(0,L.getHighestQuality)(Object.keys(d));(0,L.assertNonNullable)(c);let p=d[c];(0,L.assertNonNullable)(p),i=p,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];(0,L.assertNonNullable)(d),i=d.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];(0,L.assertNonNullable)(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];(0,L.assertNonNullable)(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];(0,L.assertNonNullable)(d),i=Ie(d.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.ErrorCategory.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,L.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,L.isNonNullable)(o)&&(n.metadata.title=o),(0,L.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add((0,L.timeout)(tm).subscribe(()=>s(`timeout(${tm})`)))});(0,im.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:L.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ru=require("@vkontakte/videoplayer-shared");var rm=require("@vkontakte/videoplayer-shared"),am=a=>{try{a.pause(),a.playbackRate=0,(0,rm.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var ks=require("@vkontakte/videoplayer-shared"),eu=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},tu=window.WeakMap?new WeakMap:new eu,iu=window.WeakMap?new WeakMap:new Map,jx=(a,e=20)=>{let t=0;return(0,ks.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},ke=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),i=!!t;t?(0,ru.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),tu.set(t,i);let r=new ks.Subscription;return r.add(jx(t,e)),iu.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Re=a=>{let e=iu.get(a);e==null||e.unsubscribe(),iu.delete(a);let t=tu.get(a);tu.delete(a),t?(0,ru.clearVideoElement)(a):am(a)};var M=require("@vkontakte/videoplayer-shared");var Ht=require("@vkontakte/videoplayer-shared"),Rs=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Ht.isNullable)(r),l=new Ht.Subscription;return r&&l.add(r.subscribe(d=>{let c=a.getState();i(d,c)&&a.setState(d)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),l},ht=(a,e,t)=>Rs(e,()=>a.loop,i=>{(0,Ht.isNonNullable)(i)&&(a.loop=i)},{onError:t}),$e=(a,e,t,i)=>Rs(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,Ht.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ye=(a,e,t,i)=>Rs(e,()=>a.playbackRate,r=>{(0,Ht.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),jt=Rs;var Gx=a=>["__",a.language,a.label].join("|"),Qx=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},au=class a{constructor(){this.available$=new M.Subject;this.current$=new M.ValueSubject(void 0);this.error$=new M.Subject;this.subscription=new M.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:M.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(jt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,M.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,M.isNonNullable)(s)&&(0,M.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,M.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(jt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,M.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,M.isNonNullable)(s)&&(0,M.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,M.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(jt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(jt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,M.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,M.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,M.merge)((0,M.fromEvent)(e,"addtrack"),(0,M.fromEvent)(e,"removetrack"),(0,M.observableFrom)(["init"])).pipe((0,M.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,M.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,M.merge)((0,M.fromEvent)(e,"change"),(0,M.observableFrom)(["init"])).pipe((0,M.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,M.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,M.filterChanged)()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add((0,M.fromEvent)(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,d,c,p,h;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(c=o.target)==null?void 0:c.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,M.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,M.isNonNullable)(t.align)&&(r.align=t.align),(0,M.isNonNullable)(t.position)&&(r.position=t.position),(0,M.isNonNullable)(t.size)&&(r.size=t.size),(0,M.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,M.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:Gx(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,M.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,M.isNullable)(e)||!Qx(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,M.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,M.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},ze=au;var xt=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 sm=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},su=a=>{let e=sm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},nm=a=>{let e=sm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var D=require("@vkontakte/videoplayer-shared");var Wx=3,om=(a,e,t=Wx)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Le=a=>{let e=I=>(0,D.fromEvent)(a,I).pipe((0,D.mapTo)(void 0)),i=(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)()),r=(0,D.merge)((0,D.fromEvent)(a,"progress"),(0,D.fromEvent)(a,"timeupdate")).pipe((0,D.map)(()=>om(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 A;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:(A=a.error)!=null?A:void 0}})),l=(0,D.fromEvent)(a,"timeupdate").pipe((0,D.map)(()=>a.currentTime)),d=new D.Subject,c=.3,p;l.subscribe(I=>{a.loop&&(0,D.isNonNullable)(p)&&(0,D.isNonNullable)(I)&&p>=a.duration-c&&I<=c&&d.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(nm(a));m.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let x=new D.ValueSubject(su(a));return(0,D.fromEvent)(a,"fullscreenchange").pipe((0,D.map)(()=>su(a))).subscribe(x),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,D.fromEvent)(a,"durationchange").pipe((0,D.map)(()=>a.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:x}};var Pt=require("@vkontakte/videoplayer-shared"),Gt=a=>{switch(a){case"mobile":return Pt.VideoQuality.Q_144P;case"lowest":return Pt.VideoQuality.Q_240P;case"low":return Pt.VideoQuality.Q_360P;case"sd":case"medium":return Pt.VideoQuality.Q_480P;case"hd":case"high":return Pt.VideoQuality.Q_720P;case"fullhd":case"full":return Pt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Pt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Pt.VideoQuality.Q_2160P}};var Qt=je(Ui(),1),C=require("@vkontakte/videoplayer-shared");var nu=!1,At={},fm=a=>{nu=a},mm=()=>{At={}},bm=a=>{a(At)},Cr=(a,e)=>{var t;nu&&(At.meta=(t=At.meta)!=null?t:{},At.meta[a]=e)},Ae=class{constructor(e){this.name=e}next(e){var i,r;if(!nu)return;At.series=(i=At.series)!=null?i:{};let t=(r=At.series[this.name])!=null?r:[];t.push([Date.now(),e]),At.series[this.name]=t}};var iP=new Ae("best_bitrate"),Sm=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var ou=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Dr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,C.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},vm='Assertion "ABR Tracks is empty array" failed',$s=(a,e,t,i)=>{var u;let r=[...e].sort(ou(1)),s=[...t].sort(ou(1)),n=s.filter(l=>(0,C.isNonNullable)(l.bitrate)&&(0,C.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Qt.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Qt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Qt.default)(n,-1):(0,Qt.default)(s,0)},gm=a=>"quality"in a,ym=(a,e,t,i)=>{var n;let r=(0,C.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,C.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,C.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=gm(o)?"video":"audio",l=gm(o)?o.quality:o.bitrate;return e({message:`
|
|
7
7
|
[last ${u} selected] ${l}
|
|
8
|
-
`}),o}return i==null||i.recordSwitch(t),t},
|
|
8
|
+
`}),o}return i==null||i.recordSwitch(t),t},rP=(a,e)=>Math.log(e)/Math.log(a),Wt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m})=>{var ee,N,ie,H,ne,R;(0,C.assertNotEmptyArray)(a,vm);let g=i.containerSizeFactor;if(i.usePixelRatio&&window.devicePixelRatio){let P=window.devicePixelRatio;if(i.pixelRatioMultiplier)g*=i.pixelRatioMultiplier*(P-1)+1;else{let J=i.pixelRatioLogBase,[W=0,fe=0,qe=0]=i.pixelRatioLogCoefficients,Dt=rP(J,W*P+fe)+qe;Number.isFinite(Dt)&&(g*=Dt)}}let S=i.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*g,height:e.height*g}:void 0,x=i.considerPlaybackRate&&(0,C.isNonNullable)(o)?o:1,T=a.filter(P=>!(0,C.isInvariantQuality)(P.quality)).sort((P,J)=>(0,C.isHigher)(P.quality,J.quality)?-1:1),I=(ee=(0,Qt.default)(T,-1))==null?void 0:ee.quality,A=(N=(0,Qt.default)(T,0))==null?void 0:N.quality,w=(0,C.isNullable)(r)||(0,C.isNonNullable)(r.min)&&(0,C.isNonNullable)(r.max)&&(0,C.isLower)(r.max,r.min)||(0,C.isNonNullable)(r.min)&&A&&(0,C.isHigher)(r.min,A)||(0,C.isNonNullable)(r.max)&&I&&(0,C.isLower)(r.max,I),V=x*Sm(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),z={},U=T.filter(P=>{let J=!0;if(S)if(P.size)J=P.size.width<=S.width&&P.size.height<=S.height;else{let ye=S&&(0,C.videoSizeToQuality)(S);J=ye?(0,C.isLowerOrEqual)(P.quality,ye):!0}if(!J)return z[P.quality]="FitsContainer",!1;let W=h||t;if(!((0,C.isNonNullable)(W)&&isFinite(W)&&(0,C.isNonNullable)(P.bitrate)?W-s>=P.bitrate*V:!0))return z[P.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,C.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,C.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,C.isHigher)(P.quality,u.quality))return z[P.quality]="Buffer",!1;if(!!c&&(0,C.isHigherOrEqual)(P.quality,c))return z[P.quality]="DroppedFramesLimit",!1;if(!!p&&(0,C.isHigherOrEqual)(P.quality,p))return z[P.quality]="StallsLimit",!1;let te=w||((0,C.isNullable)(r.max)||(0,C.isLowerOrEqual)(P.quality,r.max))&&((0,C.isNullable)(r.min)||(0,C.isHigherOrEqual)(P.quality,r.min)),ve=(0,C.isNonNullable)(d)&&!d?(0,C.isLowerOrEqual)(P.quality,i.backgroundVideoQualityLimit):!0;return!te||!ve?(z[P.quality]="FitsQualityLimits",!1):!0})[0];U&&U.bitrate&&iP.next(U.bitrate);let Q=(ie=U!=null?U:(0,Qt.default)(T,-1))!=null?ie:a[0];return Q.quality!==((H=l==null?void 0:l.last)==null?void 0:H.quality)&&m({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
10
10
|
[available video tracks]
|
|
11
|
-
${a.map(
|
|
11
|
+
${a.map(P=>`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate} }`).join(`
|
|
12
12
|
`)}
|
|
13
13
|
|
|
14
14
|
[tuning]
|
|
15
|
-
${Object.entries(i!=null?i:{}).map(([
|
|
15
|
+
${Object.entries(i!=null?i:{}).map(([P,J])=>`${P}: ${J}`).join(`
|
|
16
16
|
`)}
|
|
17
17
|
|
|
18
18
|
[limit params]
|
|
19
|
-
containerSizeLimit: ${(
|
|
19
|
+
containerSizeLimit: ${(ne=S==null?void 0:S.width)!=null?ne:0} x ${(R=S==null?void 0:S.width)!=null?R:0},
|
|
20
20
|
estimatedThroughput: ${t},
|
|
21
21
|
stallsPredictedThroughput: ${h},
|
|
22
22
|
reserve: ${s},
|
|
23
23
|
playbackRate: ${o},
|
|
24
24
|
playbackRateFactor: ${x},
|
|
25
25
|
forwardBufferHealth: ${n},
|
|
26
|
-
bitrateFactor: ${
|
|
26
|
+
bitrateFactor: ${V},
|
|
27
27
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
28
28
|
droppedVideoMaxQualityLimit: ${c},
|
|
29
29
|
stallsVideoMaxQualityLimit: ${p},
|
|
@@ -32,19 +32,19 @@
|
|
|
32
32
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
33
33
|
|
|
34
34
|
[limited video tracks]
|
|
35
|
-
${Object.entries(z).map(([
|
|
35
|
+
${Object.entries(z).map(([P,J])=>`${P}: ${J}`).join(`
|
|
36
36
|
`)||"All tracks are available"}
|
|
37
37
|
|
|
38
|
-
[best video track] ${
|
|
39
|
-
[selected video track] ${
|
|
40
|
-
`}),
|
|
38
|
+
[best video track] ${U==null?void 0:U.quality}
|
|
39
|
+
[selected video track] ${Q==null?void 0:Q.quality}
|
|
40
|
+
`}),ym(i,m,Q,l)},Tm=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var x;(0,C.assertNotEmptyArray)(t,vm);let d=r.considerPlaybackRate&&(0,C.isNonNullable)(s)?s:1,c=[...t].sort(ou(-1)),p=a.bitrate;(0,C.assertNonNullable)(p);let h=d*Sm(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,g=$s(a,e,t,r.minVideoAudioRatio),S=l||i;return(0,C.isNonNullable)(S)&&isFinite(S)&&(m=c.find(T=>(0,C.isNonNullable)(T.bitrate)&&(0,C.isNonNullable)(g==null?void 0:g.bitrate)?S-p>=T.bitrate*h&&T.bitrate>=g.bitrate:!1)),m||(m=g),(m==null?void 0:m.bitrate)!==((x=o==null?void 0:o.last)==null?void 0:x.bitrate)&&u({message:`
|
|
41
41
|
[AUDIO TRACKS ABR]
|
|
42
42
|
[available audio tracks]
|
|
43
43
|
${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
|
|
44
44
|
`)}
|
|
45
45
|
|
|
46
46
|
[tuning]
|
|
47
|
-
${Object.entries(r!=null?r:{}).map(([T,
|
|
47
|
+
${Object.entries(r!=null?r:{}).map(([T,I])=>`${T}: ${I}`).join(`
|
|
48
48
|
`)}
|
|
49
49
|
|
|
50
50
|
[limit params]
|
|
@@ -58,14 +58,14 @@
|
|
|
58
58
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
59
59
|
|
|
60
60
|
[selected audio track] ${m==null?void 0:m.id}
|
|
61
|
-
`}),m&&Im(r,u,m,o)};var ge=a=>new URL(a).hostname;var O=require("@vkontakte/videoplayer-shared");var xm=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"))},De=(a,e)=>$(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(i){if(!xm(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{yield a.play()}catch(r){return xm(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});var Ue=require("@vkontakte/videoplayer-shared");var bt=require("@vkontakte/videoplayer-shared");function Se(){return(0,bt.now)()}function cu(a){return Se()-a}function du(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Pm(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Hi(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,h="arraybuffer",m=7e3,g=2e3,S=()=>{if(u)return;(0,bt.assertNonNullable)(d);let N=cu(d),te;if(N<g){te=g-N,setTimeout(S,te);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new r,B()},x=N=>(s=N,Z),T=N=>(c=N,Z),E=()=>(h="json",Z),A=()=>{if(!u){if(--l>=0){S(),i&&i();return}u=!0,c&&c(),t&&t()}},w=N=>(p=N,Z),B=()=>{d=Se(),n=new r,n.open("get",a);let N=0,te,H=0,ne=()=>((0,bt.assertNonNullable)(d),Math.max(d,Math.max(te||0,H||0)));if(s&&n.addEventListener("progress",I=>{let V=Se();s.updateChunk&&I.loaded>N&&(s.updateChunk(ne(),I.loaded-N),N=I.loaded,te=V)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>A())),n.addEventListener("load",()=>{if(u)return;(0,bt.assertNonNullable)(n);let I=n.status;if(I>=200&&I<300){if(n.response.byteLength&&s){let V=n.response.byteLength-N;V&&s.updateChunk&&s.updateChunk(ne(),V)}n.responseType==="json"&&!Object.values(n.response).length?A():(c&&c(),e(n.response))}else A()}),n.addEventListener("error",()=>{A()}),p){let I=()=>{(0,bt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(H=Se(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=h,n.send(),Z},Z={withBitrateReporting:x,withParallel:w,withJSONResponse:E,withRetryCount:N=>(l=N,Z),withRetryInterval:(N,te)=>((0,bt.isNonNullable)(N)&&(g=N),(0,bt.isNonNullable)(te)&&(m=te),Z),withTimeout:N=>(o=N,Z),withFinally:T,send:B,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return Z}var Br=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Or=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Se(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=Se()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Hi(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Se()}_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=Se();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Am=require("@vkontakte/videoplayer-shared"),Ms=1e4,pu=3;var oP=6e4,uP=10,lP=1,cP=500,_r=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new Am.Subject,this.chunkRateEstimator=new Br(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=du(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=du(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Ue.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Pm(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Or(pu,Ms,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let A=s&&(!d||d===this.rep);return A||t("Not running!"),A},p=(A,w,B)=>{u&&u.abort(),u=Hi(this.urlResolver.resolve(A,!1),w,B,()=>this._retryCallback()).withTimeout(Ms).withBitrateReporting(this.bitrateSwitcher).withRetryCount(pu).withFinally(()=>{u=null}).send()},h=(A,w,B)=>{(0,Ue.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(A,!1),w,B,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=A=>{let w=i.playbackRate;i.playbackRate!==A&&(t(`Playback rate switch: ${w}=>${A}`),i.playbackRate=A)},g=A=>{this.lowLatency=A,t(`lowLatency changed to ${A}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let A=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let B=Se()-1e4,z=0;for(let q=0;q<this.bufferStates.length;q++){let W=this.bufferStates[q];A=Math.min(A,W.buf),W.ts<B&&z++}this.bufferStates.splice(0,z),t(`update playback rate; minBuffer=${A} drop=${z} jitter=${this.sourceJitter}`);let se=A-lP;this.sourceJitter>=0?se-=this.sourceJitter/2:this.sourceJitter-=1,se>3?m(1.15):se>1?m(1.1):se>.3?m(1.05):m(1)}},x=A=>{let w,B=()=>w&&w.start?w.start.length:0,z=I=>w.start[I]/1e3,se=I=>w.dur[I]/1e3,q=I=>w.fragIndex+I,W=(I,V)=>({chunkIdx:q(I),startTS:z(I),dur:se(I),discontinuity:V}),Z=()=>{let I=0;if(w&&w.dur){let V=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ie=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,K=V;this.sourceJitter>1&&(K+=this.sourceJitter-1);let fe=w.dur.length-1;for(;fe>=0&&(K-=w.dur[fe],!(K<=0));--fe);I=Math.min(fe,w.dur.length-1-ie),I=Math.max(I,0)}return W(I,!0)},N=I=>{let V=B();if(!(V<=0)){if((0,Ue.isNonNullable)(I)){for(let ie=0;ie<V;ie++)if(z(ie)>I)return W(ie)}return Z()}},te=I=>{let V=B(),ie=I?I.chunkIdx+1:0,K=ie-w.fragIndex;if(!(V<=0)){if(!I||K<0||K-V>uP)return t(`Resync: offset=${K} bChunks=${V} chunk=`+JSON.stringify(I)),Z();if(!(K>=V))return W(ie-w.fragIndex,!1)}},H=(I,V,ie)=>{l&&l.abort(),l=Hi(this.urlResolver.resolve(I,!0,this.lowLatency),V,ie,()=>this._retryCallback()).withTimeout(Ms).withRetryCount(pu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(I,V)=>{H(A,ie=>{if(!c())return;w=ie;let K=!!w.lowLatency;K!==this.lowLatency&&g(K);let fe=0;for(let Be=0;Be<w.dur.length;++Be)fe+=w.dur[Be];fe>0&&((0,Ue.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(fe/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,I(N(V))},()=>this._handleNetworkError())},nextChunk:te}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ue.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:A=>{let{videoElement:w,logger:B}=this.params,z=x(e.jidxUrl),se,q,W,Z,N=0,te,H,ne,I=()=>{te&&(clearTimeout(te),te=void 0);let ee=Math.max(cP,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),me=N+ee,Oe=Se(),He=Math.min(1e4,me-Oe);N=Oe;let Vt=()=>{l||c()&&z.seek(()=>{c()&&(N=Se(),V(),I())})};He>0?te=window.setTimeout(()=>{this.paused?I():Vt()},He):Vt()},V=()=>{let ee;for(;ee=z.nextChunk(Z);)Z=ee,er(ee);let me=z.nextChunk(W);if(me){if(W&&me.discontinuity){B("Detected discontinuity; restarting playback"),this.paused?I():(T(),this._initPlayerWith(e));return}Be(me)}else I()},ie=(ee,me)=>{if(!c()||!this.sourceBuffer)return;let Oe,He,Vt,gi=Bt=>{window.setTimeout(()=>{c()&&ie(ee,me)},Bt)};if(this.sourceBuffer.updating)B("Source buffer is updating; delaying appendBuffer"),gi(100);else{let Bt=Se(),Zt=w.currentTime;!this.paused&&w.buffered.length>1&&H===Zt&&Bt-ne>500&&(B("Stall suspected; trying to fix"),this._fixupStall()),H!==Zt&&(H=Zt,ne=Bt);let Si=this._getBufferSizeSec();if(Si>30)B(`Buffered ${Si} seconds; delaying appendBuffer`),gi(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:Bt,buf:Si}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),me&&me()}catch(tr){if(tr.name==="QuotaExceededError")B("QuotaExceededError; delaying appendBuffer"),Vt=this.sourceBuffer.buffered.length,Vt!==0&&(Oe=this.sourceBuffer.buffered.start(0),He=Zt,He-Oe>4&&this.sourceBuffer.remove(Oe,He-3)),gi(1e3);else throw tr}}},K=()=>{q&&se&&(B([`Appending chunk, sz=${q.byteLength}:`,JSON.stringify(W)]),ie(q,function(){q=null,V()}))},fe=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),Be=ee=>{c()&&h(fe(ee),(me,Oe)=>{if(c()){if(Oe/=1e3,q=me,W=ee,n=ee.startTS,Oe){let He=Math.min(10,ee.dur/Oe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*He:He}K()}},()=>this._handleNetworkError())},er=ee=>{c()&&((0,Ue.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(fe(ee),!1)))},Jt=ee=>{c()&&(e.cachedHeader=ee,ie(ee,()=>{se=!0,K()}))};s=!0,z.seek(ee=>{if(c()){if(N=Se(),!ee){I();return}Z=ee,!(0,Ue.isNullable)(A)||ee.startTS>A?Be(ee):(W=ee,V())}},A),e.cachedHeader?Jt(e.cachedHeader):p(e.headerUrl,Jt,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,Ue.isNonNullable)(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Ue.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ue.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/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(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,h)=>{let m=Se();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,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&cu(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=s.updateChunk(c,p);return h&&l(),h},notifySwitch:c=>{let p=Se();c<o&&(n=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Hi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Ms).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;De(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},oP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var le=require("@vkontakte/videoplayer-shared"),hu=class{constructor(){this.onDroopedVideoFramesLimit$=new le.Subject;this.subscription=new le.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new le.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,le.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,le.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,le.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,le.interval)(this.droppedFramesChecker.checkTime).pipe((0,le.filter)(()=>this.playing),(0,le.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,le.debounce)(this.droppedFramesChecker.checkTime)),i=(0,le.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,le.isLower)(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Ds=hu;var Cs=require("@vkontakte/videoplayer-shared"),wm=require("@vkontakte/videoplayer-shared");var Nr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var dP=(a,e)=>new Cs.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Nr()))},R(R({},i),e));r.observe(a);let s=(0,wm.fromEvent)(document,"visibilitychange").pipe((0,Cs.map)(n=>!document.hidden||Nr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe}}),Xe=dP;var pP=["paused","playing","ready"],hP=["paused","playing","ready"],Fr=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new G("stopped");this.representations$=new O.ValueSubject([]);this.textTracksManager=new Ke;this.droppedFramesManager=new Ds;this.maxSeekBackTime$=new O.ValueSubject(1/0);this.zeroTime$=new O.ValueSubject(void 0);this.liveOffset=new At;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:O.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),d=(i=Gt(u.name))!=null?i:(0,O.videoSizeToQuality)(u.video),c=u.bitrate/1e3,p=R({},u.video);if(!d)continue;let h={id:l,quality:d,bitrate:c,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,O.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(hP.includes(e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&pP.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Te(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Te(this.params.source.url,u))}return;default:return(0,O.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:O.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};(0,O.merge)(this.videoState.stateChangeStarted$.pipe((0,O.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,O.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})}),this.video=Re(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Me(this.video);this.subscription.add(this.representations$.pipe((0,O.map)(r=>r.map(({track:s})=>s)),(0,O.filter)(r=>!!r.length),(0,O.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,O.filterChanged)(),(0,O.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,O.combine)({zeroTime:this.zeroTime$.pipe((0,O.filter)(O.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(mt(this.video,this.params.desiredState.isLooped,t)).add(Le(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ze(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Xe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let s=r&&(0,O.videoQualityToHeight)(r);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,O.assertNever)(r.to)}},t)).add((0,O.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.observableFrom)(["init"])).pipe((0,O.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),$e(this.video)}createLiveDashPlayer(){let e=new _r({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,p,h,m;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(p=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,O.isNonNullable)(t)?t:Wt(e.map(({track:g})=>g),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let g=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;(0,O.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;(0,O.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Te(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var km=Fr;var gt=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var _=require("@vkontakte/videoplayer-shared");var Vs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ji=class extends Vs{constructor(){super(),this.listeners||Vs.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)}},Ur=class{constructor(){Object.defineProperty(this,"signal",{value:new ji,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ur.prototype[Symbol.toStringTag]="AbortController",ji.prototype[Symbol.toStringTag]="AbortSignal");function Bs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function fu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Bs({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(h){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var qr=Bs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Rm=qr?fu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ot=qr?Rm.fetch:window.fetch,zL=qr?Rm.Request:window.Request,Ie=qr?Ur:window.AbortController,KL=qr?ji:window.AbortSignal;var Gs=Ge(qi(),1);var Rt=()=>window.ManagedMediaSource||window.MediaSource,Os=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},$m=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Lm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var St=require("@vkontakte/videoplayer-shared");var Je=document.createElement("video"),bP='video/mp4; codecs="avc1.42000a,mp4a.40.2"',gP='video/mp4; codecs="hev1.1.6.L93.B0"',qm='video/webm; codecs="vp09.00.10.08"',Hm='video/webm; codecs="av01.0.00M.08"',SP='audio/mp4; codecs="mp4a.40.2"',vP='audio/webm; codecs="opus"',Mm,Dm,Hr={mms:Os(),mse:$m(),hls:!!((Mm=Je.canPlayType)!=null&&Mm.call(Je,"application/x-mpegurl")||(Dm=Je.canPlayType)!=null&&Dm.call(Je,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Cm,Vm,Ce={mp4:!!((Cm=Je.canPlayType)!=null&&Cm.call(Je,"video/mp4")),webm:!!((Vm=Je.canPlayType)!=null&&Vm.call(Je,"video/webm")),cmaf:!0},Ns,Bm,Fs,Om,Us,_m,qs,Nm,Hs,Fm,js,Um,Ve={h264:!!((Bm=(Ns=Rt())==null?void 0:Ns.isTypeSupported)!=null&&Bm.call(Ns,bP)),h265:!!((Om=(Fs=Rt())==null?void 0:Fs.isTypeSupported)!=null&&Om.call(Fs,gP)),vp9:!!((_m=(Us=Rt())==null?void 0:Us.isTypeSupported)!=null&&_m.call(Us,qm)),av1:!!((Nm=(qs=Rt())==null?void 0:qs.isTypeSupported)!=null&&Nm.call(qs,Hm)),aac:!!((Fm=(Hs=Rt())==null?void 0:Hs.isTypeSupported)!=null&&Fm.call(Hs,SP)),opus:!!((Um=(js=Rt())==null?void 0:js.isTypeSupported)!=null&&Um.call(js,vP))},Gi=(Ve.h264||Ve.h265)&&Ve.aac,ci,yP=()=>$(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(j(R({},a),{video:j(R({},a.video),{contentType:Hm})})),window.navigator.mediaCapabilities.decodingInfo(j(R({},a),{video:j(R({},a.video),{contentType:qm})}))]);ci={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{yP()}catch(a){console.error(a)}var Qi=Hr.hls&&Ce.mp4,jm=()=>Object.keys(Ve).filter(a=>Ve[a]),Gm=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let r=Hr.mse&&(!i||!!window.MediaStreamTrack)||Hr.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return r&&Ce.mp4&&Gi;case"DASH_WEBM":return r&&Ce.webm&&Ve.vp9&&Ve.opus;case"DASH_WEBM_AV1":return r&&Ce.webm&&Ve.av1&&Ve.opus;case"DASH_STREAMS":return r&&(Ce.mp4&&Gi||Ce.webm&&(Ve.vp9||Ve.av1)&&(Ve.opus||Ve.aac));case"DASH_LIVE":return r&&Ce.mp4&&Gi;case"DASH_LIVE_CMAF":return r&&Ce.mp4&&Gi&&Ce.cmaf;case"DASH_ONDEMAND":return r&&Ce.mp4&&Gi;case"HLS":case"HLS_ONDEMAND":return Qi||e&&r&&Ce.mp4&&Gi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Qi;case"MPEG":return Ce.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Hr.webrtc&&Hr.ws&&Ve.h264&&(Ce.mp4||Ce.webm);default:return(0,St.assertNever)(s)}})},_s=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return ci?ci[t].smooth?[t,e]:ci[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ci?ci[t].powerEfficient?[t,e]:ci[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,St.assertNever)(a)}return[e,t]},Qm=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],..._s(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(St.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",..._s(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[..._s(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",..._s(a),...r,"HLS","HLS_ONDEMAND"];default:(0,St.assertNever)(e)}return Qi?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Wm=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=St.clientChecker.isMac&&St.clientChecker.isSafari;if(St.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,St.assertNever)(a)}else Qi&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},mu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ym=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Gs.default)(t.value.split("."),0)}for(let t of a){let i=(0,Gs.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Gs.default)(e.value.split("."),0)};var Wi=require("@vkontakte/videoplayer-shared"),zm=a=>{if(!a)return{id:"EmptyResponse",category:Wi.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Wi.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:Wi.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:Wi.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Wi.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Yt=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared");var Xi=Ge(qi(),1);var TP=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},IP=a=>window.clearTimeout(a),Km=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Xm=!Km(window.requestIdleCallback)||!Km(window.cancelIdleCallback),bu=Xm?TP:window.requestIdleCallback,lM=Xm?IP:window.cancelIdleCallback;var Fb=Ge(ks(),1);var Ze=require("@vkontakte/videoplayer-shared");var EP=18,Jm=!1;try{Jm=Ze.clientChecker.isSafari&&!!Ze.clientChecker.macVersion&&Ze.clientChecker.macVersion<=EP}catch(a){console.error(a)}var gu=class{constructor(e){this.bufferFull$=new Ze.Subject;this.error$=new Ze.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:Ze.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return $(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return $(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})})}abort(e){return $(this,null,function*(){return new Promise(t=>{let i;Jm&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ze.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,Ze.assertNever)(t)}}},Zm=gu;var Su=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var P=require("@vkontakte/videoplayer-shared");var re=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Yi=class extends re{};var jr=class extends re{};var Gr=class extends re{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Qr=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ce=class extends re{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Wr=class extends ce{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Yr=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zr=class extends re{constructor(e,t){super(e,t),this.data=this.content}};var di=class extends ce{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Kr=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xr=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Jr=class extends ce{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 Zr=class extends ce{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ea=class extends ce{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ta=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ia=class extends ce{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 ra=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var aa=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var sa=class extends ce{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var na=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oa=class extends ce{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 ua=class extends ce{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var la=class extends ce{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var PP={ftyp:Gr,moov:Qr,mvhd:Wr,moof:Yr,mdat:zr,sidx:di,trak:Kr,mdia:ta,mfhd:sa,tkhd:ia,traf:na,tfhd:oa,tfdt:ua,trun:la,minf:ra,sv3d:Xr,st3d:Jr,prhd:Zr,proj:aa,equi:ea,uuid:jr,unknown:Yi},zt=class a{constructor(e={}){this.options=R({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=PP[e];return i?new i(t,new a):new Yi(t,new a)}};var pi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var wP=new TextDecoder("ascii"),kP=a=>wP.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",RP=a=>{let e=new di(a,new zt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},$P=(a,e)=>{let i=new zt().parse(a),r=new pi(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,c)},LP=a=>{var r;let t=new zt().parse(a);return(r=new pi(t).find("sidx"))==null?void 0:r.timescale},MP=(a,e)=>{let i=new zt().parse(a),s=new pi(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},DP=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new zt().parse(a),r=new pi(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},eb={validateData:kP,parseInit:DP,getIndexRange:()=>{},parseSegments:RP,parseFeedableSegmentChunk:$P,getChunkEndTime:MP,getTimescaleFromIndex:LP};var $t=require("@vkontakte/videoplayer-shared");var ib=require("@vkontakte/videoplayer-shared");var tb={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"}},rb=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ca(a,t),r=i in tb,s=r?tb[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,d=ca(u),c=l*pt(2,(o-1)*8)+d,p=t+o,h;return p+c>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},ca=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*pt(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*pt(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*pt(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},ut=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ca(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,ib.assertNever)(e)}},hi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=rb(i);if(!e(r))return;r.type==="master"&&hi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},ab=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=rb(a);return hi(r.value,({tag:s,type:n,value:o})=>(s===17143?e=ut(o,n):s===17026?t=ut(o,n):s===17029&&(i=ut(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var sb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],CP=[231,22612,22743,167,171,163,160,175],VP=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return hi(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let S=ut(m,h);l=ca(S)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=ut(m,h):p===17545?r=ut(m,h):p===21420&&l===475249515?u=ut(m,h):p===374648427?hi(m,({tag:S,type:x,value:T})=>S===30321?(d=ut(T,x)===1,!1):!0):s&&n&&sb.includes(p)&&(o=!0),!o}),(0,$t.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,$t.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,$t.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},BP=a=>{if((0,$t.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},OP=(a,e)=>{let t=!1,i=!1,r=o=>(0,$t.isNonNullable)(o.time)&&(0,$t.isNonNullable)(o.position),s=[],n;return hi(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=ut(l,u));break;case 183:break;case 241:n&&(n.position=ut(l,u));break;default:t&&sb.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},_P=a=>{let e=0,t=!1;try{hi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):CP.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=[163,160,175].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},nb={validateData:ab,parseInit:VP,getIndexRange:BP,parseSegments:OP,parseFeedableSegmentChunk:_P};var da=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return nb;case"mp4":return eb}}throw new ReferenceError(`Unsupported mime type ${a}`)},ob=a=>"getChunkEndTime"in a;var Au=Ge(Rb(),1),Db=Ge(qi(),1);var Pu=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var Ki=require("@vkontakte/videoplayer-shared");var $b=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Lb=a=>{var e;try{let t=SA(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function SA(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
61
|
+
`}),m&&ym(r,u,m,o)};var be=a=>new URL(a).hostname;var O=require("@vkontakte/videoplayer-shared");var Im=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"))},Me=(a,e)=>B(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(i){if(!Im(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{yield a.play()}catch(r){return Im(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});var _e=require("@vkontakte/videoplayer-shared");var ft=require("@vkontakte/videoplayer-shared");function ge(){return(0,ft.now)()}function uu(a){return ge()-a}function lu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Em(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Hi(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,h="arraybuffer",m=7e3,g=2e3,S=()=>{if(u)return;(0,ft.assertNonNullable)(d);let N=uu(d),ie;if(N<g){ie=g-N,setTimeout(S,ie);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new r,V()},x=N=>(s=N,ee),T=N=>(c=N,ee),I=()=>(h="json",ee),A=()=>{if(!u){if(--l>=0){S(),i&&i();return}u=!0,c&&c(),t&&t()}},w=N=>(p=N,ee),V=()=>{d=ge(),n=new r,n.open("get",a);let N=0,ie,H=0,ne=()=>((0,ft.assertNonNullable)(d),Math.max(d,Math.max(ie||0,H||0)));if(s&&n.addEventListener("progress",R=>{let P=ge();s.updateChunk&&R.loaded>N&&(s.updateChunk(ne(),R.loaded-N),N=R.loaded,ie=P)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>A())),n.addEventListener("load",()=>{if(u)return;(0,ft.assertNonNullable)(n);let R=n.status;if(R>=200&&R<300){if(n.response.byteLength&&s){let P=n.response.byteLength-N;P&&s.updateChunk&&s.updateChunk(ne(),P)}n.responseType==="json"&&!Object.values(n.response).length?A():(c&&c(),e(n.response))}else A()}),n.addEventListener("error",()=>{A()}),p){let R=()=>{(0,ft.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(H=ge(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=h,n.send(),ee},ee={withBitrateReporting:x,withParallel:w,withJSONResponse:I,withRetryCount:N=>(l=N,ee),withRetryInterval:(N,ie)=>((0,ft.isNonNullable)(N)&&(g=N),(0,ft.isNonNullable)(ie)&&(m=ie),ee),withTimeout:N=>(o=N,ee),withFinally:T,send:V,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return ee}var Br=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Vr=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=ge(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ge()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Hi(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=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 i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var xm=require("@vkontakte/videoplayer-shared"),Ls=1e4,cu=3;var sP=6e4,nP=10,oP=1,uP=500,Or=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new xm.Subject,this.chunkRateEstimator=new Br(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=lu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=lu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,_e.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Em(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Vr(cu,Ls,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let A=s&&(!d||d===this.rep);return A||t("Not running!"),A},p=(A,w,V)=>{u&&u.abort(),u=Hi(this.urlResolver.resolve(A,!1),w,V,()=>this._retryCallback()).withTimeout(Ls).withBitrateReporting(this.bitrateSwitcher).withRetryCount(cu).withFinally(()=>{u=null}).send()},h=(A,w,V)=>{(0,_e.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(A,!1),w,V,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=A=>{let w=i.playbackRate;i.playbackRate!==A&&(t(`Playback rate switch: ${w}=>${A}`),i.playbackRate=A)},g=A=>{this.lowLatency=A,t(`lowLatency changed to ${A}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let A=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let V=ge()-1e4,z=0;for(let U=0;U<this.bufferStates.length;U++){let Q=this.bufferStates[U];A=Math.min(A,Q.buf),Q.ts<V&&z++}this.bufferStates.splice(0,z),t(`update playback rate; minBuffer=${A} drop=${z} jitter=${this.sourceJitter}`);let se=A-oP;this.sourceJitter>=0?se-=this.sourceJitter/2:this.sourceJitter-=1,se>3?m(1.15):se>1?m(1.1):se>.3?m(1.05):m(1)}},x=A=>{let w,V=()=>w&&w.start?w.start.length:0,z=R=>w.start[R]/1e3,se=R=>w.dur[R]/1e3,U=R=>w.fragIndex+R,Q=(R,P)=>({chunkIdx:U(R),startTS:z(R),dur:se(R),discontinuity:P}),ee=()=>{let R=0;if(w&&w.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,J=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,W=P;this.sourceJitter>1&&(W+=this.sourceJitter-1);let fe=w.dur.length-1;for(;fe>=0&&(W-=w.dur[fe],!(W<=0));--fe);R=Math.min(fe,w.dur.length-1-J),R=Math.max(R,0)}return Q(R,!0)},N=R=>{let P=V();if(!(P<=0)){if((0,_e.isNonNullable)(R)){for(let J=0;J<P;J++)if(z(J)>R)return Q(J)}return ee()}},ie=R=>{let P=V(),J=R?R.chunkIdx+1:0,W=J-w.fragIndex;if(!(P<=0)){if(!R||W<0||W-P>nP)return t(`Resync: offset=${W} bChunks=${P} chunk=`+JSON.stringify(R)),ee();if(!(W>=P))return Q(J-w.fragIndex,!1)}},H=(R,P,J)=>{l&&l.abort(),l=Hi(this.urlResolver.resolve(R,!0,this.lowLatency),P,J,()=>this._retryCallback()).withTimeout(Ls).withRetryCount(cu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(R,P)=>{H(A,J=>{if(!c())return;w=J;let W=!!w.lowLatency;W!==this.lowLatency&&g(W);let fe=0;for(let qe=0;qe<w.dur.length;++qe)fe+=w.dur[qe];fe>0&&((0,_e.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(fe/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,R(N(P))},()=>this._handleNetworkError())},nextChunk:ie}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,_e.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:A=>{let{videoElement:w,logger:V}=this.params,z=x(e.jidxUrl),se,U,Q,ee,N=0,ie,H,ne,R=()=>{ie&&(clearTimeout(ie),ie=void 0);let te=Math.max(uP,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ve=N+te,ye=ge(),Ue=Math.min(1e4,ve-ye);N=ye;let Bt=()=>{l||c()&&z.seek(()=>{c()&&(N=ge(),P(),R())})};Ue>0?ie=window.setTimeout(()=>{this.paused?R():Bt()},Ue):Bt()},P=()=>{let te;for(;te=z.nextChunk(ee);)ee=te,Dt(te);let ve=z.nextChunk(Q);if(ve){if(Q&&ve.discontinuity){V("Detected discontinuity; restarting playback"),this.paused?R():(T(),this._initPlayerWith(e));return}qe(ve)}else R()},J=(te,ve)=>{if(!c()||!this.sourceBuffer)return;let ye,Ue,Bt,gi=Vt=>{window.setTimeout(()=>{c()&&J(te,ve)},Vt)};if(this.sourceBuffer.updating)V("Source buffer is updating; delaying appendBuffer"),gi(100);else{let Vt=ge(),Xt=w.currentTime;!this.paused&&w.buffered.length>1&&H===Xt&&Vt-ne>500&&(V("Stall suspected; trying to fix"),this._fixupStall()),H!==Xt&&(H=Xt,ne=Vt);let Si=this._getBufferSizeSec();if(Si>30)V(`Buffered ${Si} seconds; delaying appendBuffer`),gi(2e3);else try{this.sourceBuffer.appendBuffer(te),this.videoPlayStarted?(this.bufferStates.push({ts:Vt,buf:Si}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ve&&ve()}catch(er){if(er.name==="QuotaExceededError")V("QuotaExceededError; delaying appendBuffer"),Bt=this.sourceBuffer.buffered.length,Bt!==0&&(ye=this.sourceBuffer.buffered.start(0),Ue=Xt,Ue-ye>4&&this.sourceBuffer.remove(ye,Ue-3)),gi(1e3);else throw er}}},W=()=>{U&&se&&(V([`Appending chunk, sz=${U.byteLength}:`,JSON.stringify(Q)]),J(U,function(){U=null,P()}))},fe=te=>e.fragUrlTemplate.replace("%%id%%",te.chunkIdx),qe=te=>{c()&&h(fe(te),(ve,ye)=>{if(c()){if(ye/=1e3,U=ve,Q=te,n=te.startTS,ye){let Ue=Math.min(10,te.dur/ye);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ue:Ue}W()}},()=>this._handleNetworkError())},Dt=te=>{c()&&((0,_e.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(fe(te),!1)))},bi=te=>{c()&&(e.cachedHeader=te,J(te,()=>{se=!0,W()}))};s=!0,z.seek(te=>{if(c()){if(N=ge(),!te){R();return}ee=te,!(0,_e.isNullable)(A)||te.startTS>A?qe(te):(Q=te,P())}},A),e.cachedHeader?bi(e.cachedHeader):p(e.headerUrl,bi,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,_e.isNonNullable)(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,_e.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,_e.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/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(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},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,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&uu(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=s.updateChunk(c,p);return h&&l(),h},notifySwitch:c=>{let p=ge();c<o&&(n=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Hi(this.urlResolver.resolve(e,!0),t,i,()=>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;Me(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},sP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var le=require("@vkontakte/videoplayer-shared"),du=class{constructor(){this.onDroopedVideoFramesLimit$=new le.Subject;this.subscription=new le.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new le.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,le.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,le.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,le.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,le.interval)(this.droppedFramesChecker.checkTime).pipe((0,le.filter)(()=>this.playing),(0,le.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,le.debounce)(this.droppedFramesChecker.checkTime)),i=(0,le.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,le.isLower)(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Ms=du;var Cs=require("@vkontakte/videoplayer-shared"),Pm=require("@vkontakte/videoplayer-shared");var _r=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var lP=(a,e)=>new Cs.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||_r()))},$($({},i),e));r.observe(a);let s=(0,Pm.fromEvent)(document,"visibilitychange").pipe((0,Cs.map)(n=>!document.hidden||_r())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe}}),Ke=lP;var cP=["paused","playing","ready"],dP=["paused","playing","ready"],Nr=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new j("stopped");this.representations$=new O.ValueSubject([]);this.textTracksManager=new ze;this.droppedFramesManager=new Ms;this.maxSeekBackTime$=new O.ValueSubject(1/0);this.zeroTime$=new O.ValueSubject(void 0);this.liveOffset=new xt;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:O.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),d=(i=Gt(u.name))!=null?i:(0,O.videoSizeToQuality)(u.video),c=u.bitrate/1e3,p=$({},u.video);if(!d)continue;let h={id:l,quality:d,bitrate:c,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,O.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(dP.includes(e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&cP.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ie(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Ie(this.params.source.url,u))}return;default:return(0,O.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:O.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};(0,O.merge)(this.videoState.stateChangeStarted$.pipe((0,O.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,O.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})}),this.video=ke(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Le(this.video);this.subscription.add(this.representations$.pipe((0,O.map)(r=>r.map(({track:s})=>s)),(0,O.filter)(r=>!!r.length),(0,O.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,O.filterChanged)(),(0,O.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,O.combine)({zeroTime:this.zeroTime$.pipe((0,O.filter)(O.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ht(this.video,this.params.desiredState.isLooped,t)).add($e(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ye(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let s=r&&(0,O.videoQualityToHeight)(r);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,O.assertNever)(r.to)}},t)).add((0,O.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.observableFrom)(["init"])).pipe((0,O.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),Re(this.video)}createLiveDashPlayer(){let e=new Or({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,p,h,m;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(p=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,O.isNonNullable)(t)?t:Wt(e.map(({track:g})=>g),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let g=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;(0,O.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;(0,O.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ie(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Am=Nr;var mt=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var _=require("@vkontakte/videoplayer-shared");var Ds=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ji=class extends Ds{constructor(){super(),this.listeners||Ds.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)}},Fr=class{constructor(){Object.defineProperty(this,"signal",{value:new ji,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Fr.prototype[Symbol.toStringTag]="AbortController",ji.prototype[Symbol.toStringTag]="AbortSignal");function Bs(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 pu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Bs({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(h){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var qr=Bs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),wm=qr?pu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,wt=qr?wm.fetch:window.fetch,WL=qr?wm.Request:window.Request,Ne=qr?Fr:window.AbortController,YL=qr?ji:window.AbortSignal;var js=je(Ui(),1);var kt=()=>window.ManagedMediaSource||window.MediaSource,Vs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},km=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Rm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var bt=require("@vkontakte/videoplayer-shared");var Je=document.createElement("video"),fP='video/mp4; codecs="avc1.42000a,mp4a.40.2"',mP='video/mp4; codecs="hev1.1.6.L93.B0"',Fm='video/webm; codecs="vp09.00.10.08"',qm='video/webm; codecs="av01.0.00M.08"',bP='audio/mp4; codecs="mp4a.40.2"',gP='audio/webm; codecs="opus"',$m,Lm,Ur={mms:Vs(),mse:km(),hls:!!(($m=Je.canPlayType)!=null&&$m.call(Je,"application/x-mpegurl")||(Lm=Je.canPlayType)!=null&&Lm.call(Je,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Mm,Cm,Ce={mp4:!!((Mm=Je.canPlayType)!=null&&Mm.call(Je,"video/mp4")),webm:!!((Cm=Je.canPlayType)!=null&&Cm.call(Je,"video/webm")),cmaf:!0},_s,Dm,Ns,Bm,Fs,Vm,qs,Om,Us,_m,Hs,Nm,De={h264:!!((Dm=(_s=kt())==null?void 0:_s.isTypeSupported)!=null&&Dm.call(_s,fP)),h265:!!((Bm=(Ns=kt())==null?void 0:Ns.isTypeSupported)!=null&&Bm.call(Ns,mP)),vp9:!!((Vm=(Fs=kt())==null?void 0:Fs.isTypeSupported)!=null&&Vm.call(Fs,Fm)),av1:!!((Om=(qs=kt())==null?void 0:qs.isTypeSupported)!=null&&Om.call(qs,qm)),aac:!!((_m=(Us=kt())==null?void 0:Us.isTypeSupported)!=null&&_m.call(Us,bP)),opus:!!((Nm=(Hs=kt())==null?void 0:Hs.isTypeSupported)!=null&&Nm.call(Hs,gP))},Gi=(De.h264||De.h265)&&De.aac,li,SP=()=>B(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(K($({},a),{video:K($({},a.video),{contentType:qm})})),window.navigator.mediaCapabilities.decodingInfo(K($({},a),{video:K($({},a.video),{contentType:Fm})}))]);li={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{SP()}catch(a){console.error(a)}var Qi=Ur.hls&&Ce.mp4,Um=()=>Object.keys(De).filter(a=>De[a]),Hm=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let r=Ur.mse&&(!i||!!window.MediaStreamTrack)||Ur.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return r&&Ce.mp4&&Gi;case"DASH_WEBM":return r&&Ce.webm&&De.vp9&&De.opus;case"DASH_WEBM_AV1":return r&&Ce.webm&&De.av1&&De.opus;case"DASH_STREAMS":return r&&(Ce.mp4&&Gi||Ce.webm&&(De.vp9||De.av1)&&(De.opus||De.aac));case"DASH_LIVE":return r&&Ce.mp4&&Gi;case"DASH_LIVE_CMAF":return r&&Ce.mp4&&Gi&&Ce.cmaf;case"DASH_ONDEMAND":return r&&Ce.mp4&&Gi;case"HLS":case"HLS_ONDEMAND":return Qi||e&&r&&Ce.mp4&&Gi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Qi;case"MPEG":return Ce.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Ur.webrtc&&Ur.ws&&De.h264&&(Ce.mp4||Ce.webm);default:return(0,bt.assertNever)(s)}})},Os=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return li?li[t].smooth?[t,e]:li[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return li?li[t].powerEfficient?[t,e]:li[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,bt.assertNever)(a)}return[e,t]},jm=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Os(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(bt.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Os(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Os(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Os(a),...r,"HLS","HLS_ONDEMAND"];default:(0,bt.assertNever)(e)}return Qi?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Gm=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=bt.clientChecker.isMac&&bt.clientChecker.isSafari;if(bt.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,bt.assertNever)(a)}else Qi&&!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"]},hu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Qm=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,js.default)(t.value.split("."),0)}for(let t of a){let i=(0,js.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,js.default)(e.value.split("."),0)};var Wi=require("@vkontakte/videoplayer-shared"),Wm=a=>{if(!a)return{id:"EmptyResponse",category:Wi.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Wi.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:Wi.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:Wi.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Wi.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Yt=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared");var Ji=je(Ui(),1);var vP=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},yP=a=>window.clearTimeout(a),Ym=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),zm=!Ym(window.requestIdleCallback)||!Ym(window.cancelIdleCallback),fu=zm?vP:window.requestIdleCallback,oM=zm?yP:window.cancelIdleCallback;var _b=je(ws(),1);var Xe=require("@vkontakte/videoplayer-shared");var TP=18,Km=!1;try{Km=Xe.clientChecker.isSafari&&!!Xe.clientChecker.macVersion&&Xe.clientChecker.macVersion<=TP}catch(a){console.error(a)}var mu=class{constructor(e){this.bufferFull$=new Xe.Subject;this.error$=new Xe.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:Xe.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return B(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return B(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})})}abort(e){return B(this,null,function*(){return new Promise(t=>{let i;Km&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Xe.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,Xe.assertNever)(t)}}},Jm=mu;var bu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var E=require("@vkontakte/videoplayer-shared");var re=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Yi=class extends re{};var Hr=class extends re{};var jr=class extends re{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Gr=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ce=class extends re{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Qr=class extends ce{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Wr=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yr=class extends re{constructor(e,t){super(e,t),this.data=this.content}};var ci=class extends ce{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var zr=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Kr=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Jr=class extends ce{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 Xr=class extends ce{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Zr=class extends ce{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ea=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ta=class extends ce{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 ia=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ra=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var aa=class extends ce{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var sa=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var na=class extends ce{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 oa=class extends ce{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ua=class extends ce{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var EP={ftyp:jr,moov:Gr,mvhd:Qr,moof:Wr,mdat:Yr,sidx:ci,trak:zr,mdia:ea,mfhd:aa,tkhd:ta,traf:sa,tfhd:na,tfdt:oa,trun:ua,minf:ia,sv3d:Kr,st3d:Jr,prhd:Xr,proj:ra,equi:Zr,uuid:Hr,unknown:Yi},zt=class a{constructor(e={}){this.options=$({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=EP[e];return i?new i(t,new a):new Yi(t,new a)}};var di=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var PP=new TextDecoder("ascii"),AP=a=>PP.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",wP=a=>{let e=new ci(a,new zt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},kP=(a,e)=>{let i=new zt().parse(a),r=new di(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,c)},RP=a=>{var r;let t=new zt().parse(a);return(r=new di(t).find("sidx"))==null?void 0:r.timescale},$P=(a,e)=>{let i=new zt().parse(a),s=new di(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},LP=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new zt().parse(a),r=new di(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Xm={validateData:AP,parseInit:LP,getIndexRange:()=>{},parseSegments:wP,parseFeedableSegmentChunk:kP,getChunkEndTime:$P,getTimescaleFromIndex:RP};var Rt=require("@vkontakte/videoplayer-shared");var eb=require("@vkontakte/videoplayer-shared");var Zm={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"}},tb=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=la(a,t),r=i in Zm,s=r?Zm[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,d=la(u),c=l*ct(2,(o-1)*8)+d,p=t+o,h;return p+c>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},la=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*ct(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*ct(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*ct(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},nt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return la(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,eb.assertNever)(e)}},pi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=tb(i);if(!e(r))return;r.type==="master"&&pi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},ib=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=tb(a);return pi(r.value,({tag:s,type:n,value:o})=>(s===17143?e=nt(o,n):s===17026?t=nt(o,n):s===17029&&(i=nt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var rb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],MP=[231,22612,22743,167,171,163,160,175],CP=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return pi(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let S=nt(m,h);l=la(S)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=nt(m,h):p===17545?r=nt(m,h):p===21420&&l===475249515?u=nt(m,h):p===374648427?pi(m,({tag:S,type:x,value:T})=>S===30321?(d=nt(T,x)===1,!1):!0):s&&n&&rb.includes(p)&&(o=!0),!o}),(0,Rt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Rt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Rt.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},DP=a=>{if((0,Rt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},BP=(a,e)=>{let t=!1,i=!1,r=o=>(0,Rt.isNonNullable)(o.time)&&(0,Rt.isNonNullable)(o.position),s=[],n;return pi(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=nt(l,u));break;case 183:break;case 241:n&&(n.position=nt(l,u));break;default:t&&rb.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},VP=a=>{let e=0,t=!1;try{pi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):MP.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=[163,160,175].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},ab={validateData:ib,parseInit:CP,getIndexRange:DP,parseSegments:BP,parseFeedableSegmentChunk:VP};var ca=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return ab;case"mp4":return Xm}}throw new ReferenceError(`Unsupported mime type ${a}`)},sb=a=>"getChunkEndTime"in a;var xu=je(wb(),1),Lb=je(Ui(),1);var Eu=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var Ki=require("@vkontakte/videoplayer-shared");var kb=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Rb=a=>{var e;try{let t=bA(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function bA(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
62
62
|
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
63
63
|
(-(?<script>[a-z]{4}))?
|
|
64
64
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
65
65
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
66
66
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
67
67
|
(?:-(?<privateuse>(?:${e})))?
|
|
68
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Mb=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Lt=(a,e)=>{let t=a;t=(0,Au.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Au.default)(t,n,(o,u)=>(0,Ki.isNullable)(s)?o:(0,Ki.isNullable)(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Cb=(a,e)=>{var w,B,z,se,q,W,Z,N,te,H,ne,I,V,ie,K,fe,Be,er,Jt,ee,me,Oe,He,Vt,gi,Bt,Zt,Si,tr,qu,Hu,ju,Gu,Qu,Wu,Yu,zu,Ku,Xu,Ju,Zu,el,tl,il,rl,al,sl,nl,ol,ul,ll,cl,dl,pl,hl,fl,ml,bl,gl,Sl;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(ye=>{var La,Ot;return(Ot=(La=ye.textContent)==null?void 0:La.trim())!=null?Ot:""}),u=(w=(0,Db.default)(o,0))!=null?w:"",l=n.children,d=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),p=c?new Date(c).getTime():void 0,h,m=s.getAttribute("mediaPresentationDuration"),g=n.getAttribute("duration"),S=s.getElementsByTagName("vk:Attrs")[0],x=S==null?void 0:S.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)h=Mb(m);else if(g){let ye=Mb(g);(0,Ki.isNonNullable)(ye)&&(h=ye)}else x&&(h=parseInt(x,10));let T=0,E=(z=(B=s.getAttribute("profiles"))==null?void 0:B.split(","))!=null?z:[];for(let ye of l){let La=(se=ye.getAttribute("id"))!=null?se:"id"+(T++).toString(10),Ot=(q=ye.getAttribute("mimeType"))!=null?q:"",on=(W=ye.getAttribute("codecs"))!=null?W:"",un=(Z=ye.getAttribute("contentType"))!=null?Z:Ot==null?void 0:Ot.split("/")[0],fg=(te=(N=ye.getAttribute("profiles"))==null?void 0:N.split(","))!=null?te:[],vl=(ne=Lb((H=ye.getAttribute("lang"))!=null?H:""))!=null?ne:{},mg=(ie=(V=(I=ye.querySelector("Label"))==null?void 0:I.textContent)==null?void 0:V.trim())!=null?ie:void 0,bg=ye.querySelectorAll("Representation"),gg=ye.querySelector("SegmentTemplate"),Sg=(fe=(K=ye.querySelector("Role"))==null?void 0:K.getAttribute("value"))!=null?fe:void 0,ir=un,be={id:La,language:vl.language,isDefault:Sg==="main",label:mg,codecs:on,hdr:ir==="video"&&Pu(on),mime:Ot,representations:[]};for(let oe of bg){let vg=(Be=oe.getAttribute("lang"))!=null?Be:void 0,yg=(er=oe.getAttribute("label"))!=null?er:void 0,Tg=(me=(ee=(Jt=oe.querySelector("BaseURL"))==null?void 0:Jt.textContent)==null?void 0:ee.trim())!=null?me:"",Ma=new URL(Tg||u,e).toString(),vi=(Oe=oe.getAttribute("mimeType"))!=null?Oe:Ot,Da=(Vt=(He=oe.getAttribute("codecs"))!=null?He:on)!=null?Vt:"",Ca;if(un==="text"){let _t=oe.getAttribute("id")||"",Va=((gi=vl.privateuse)==null?void 0:gi.includes("x-auto"))||_t.includes("_auto"),ei=oe.querySelector("SegmentTemplate");if(ei){let rr={representationId:(Bt=oe.getAttribute("id"))!=null?Bt:void 0,bandwidth:(Zt=oe.getAttribute("bandwidth"))!=null?Zt:void 0},Ba=parseInt((Si=oe.getAttribute("bandwidth"))!=null?Si:"",10)/1e3,Oa=(qu=parseInt((tr=ei.getAttribute("startNumber"))!=null?tr:"",10))!=null?qu:1,yi=parseInt((Hu=ei.getAttribute("timescale"))!=null?Hu:"",10),ln=(ju=ei.querySelectorAll("SegmentTimeline S"))!=null?ju:[],Ti=ei.getAttribute("media");if(!Ti)continue;let _a=[],Na=0,Fa="",Ii=0,ar=Oa,Ee=0;for(let tt of ln){let ti=parseInt((Gu=tt.getAttribute("d"))!=null?Gu:"",10),je=parseInt((Qu=tt.getAttribute("r"))!=null?Qu:"",10)||0,Nt=parseInt((Wu=tt.getAttribute("t"))!=null?Wu:"",10);Ee=Number.isFinite(Nt)?Nt:Ee;let ii=ti/yi*1e3,Ft=Ee/yi*1e3;for(let ct=0;ct<je+1;ct++){let Ut=Lt(Ti,j(R({},rr),{segmentNumber:ar.toString(10),segmentTime:(Ee+ct*ti).toString(10)})),Ei=(Ft!=null?Ft:0)+ct*ii,nr=Ei+ii;ar++,_a.push({time:{from:Ei,to:nr},url:Ut})}Ee+=(je+1)*ti,Na+=(je+1)*ii}Ii=Ee/yi*1e3,Fa=Lt(Ti,j(R({},rr),{segmentNumber:ar.toString(10),segmentTime:Ee.toString(10)}));let sr={time:{from:Ii,to:1/0},url:Fa},yt={type:"template",baseUrl:Ma,segmentTemplateUrl:Ti,initUrl:"",totalSegmentsDurationMs:Na,segments:_a,nextSegmentBeyondManifest:sr,timescale:yi};Ca={id:_t,kind:"text",segmentReference:yt,profiles:[],duration:h,bitrate:Ba,mime:"",codecs:"",width:0,height:0,isAuto:Va}}else Ca={id:_t,isAuto:Va,kind:"text",url:Ma}}else{let _t=(zu=(Yu=oe.getAttribute("contentType"))!=null?Yu:vi==null?void 0:vi.split("/")[0])!=null?zu:un,Va=(Xu=(Ku=ye.getAttribute("profiles"))==null?void 0:Ku.split(","))!=null?Xu:[],ei=parseInt((Ju=oe.getAttribute("width"))!=null?Ju:"",10),rr=parseInt((Zu=oe.getAttribute("height"))!=null?Zu:"",10),Ba=parseInt((el=oe.getAttribute("bandwidth"))!=null?el:"",10)/1e3,Oa=(tl=oe.getAttribute("frameRate"))!=null?tl:"",yi=(il=oe.getAttribute("quality"))!=null?il:void 0,ln=Oa?$b(Oa):void 0,Ti=(rl=oe.getAttribute("id"))!=null?rl:"id"+(T++).toString(10),_a=_t==="video"?`${rr}p`:_t==="audio"?`${Ba}Kbps`:Da,Na=`${Ti}@${_a}`,Fa=[...E,...fg,...Va],Ii,ar=oe.querySelector("SegmentBase"),Ee=(al=oe.querySelector("SegmentTemplate"))!=null?al:gg;if(ar){let yt=(nl=(sl=oe.querySelector("SegmentBase Initialization"))==null?void 0:sl.getAttribute("range"))!=null?nl:"",[tt,ti]=yt.split("-").map(Ut=>parseInt(Ut,10)),je={from:tt,to:ti},Nt=(ol=oe.querySelector("SegmentBase"))==null?void 0:ol.getAttribute("indexRange"),[ii,Ft]=Nt?Nt.split("-").map(Ut=>parseInt(Ut,10)):[],ct=Nt?{from:ii,to:Ft}:void 0;Ii={type:"byteRange",url:Ma,initRange:je,indexRange:ct}}else if(Ee){let yt={representationId:(ul=oe.getAttribute("id"))!=null?ul:void 0,bandwidth:(ll=oe.getAttribute("bandwidth"))!=null?ll:void 0},tt=parseInt((cl=Ee.getAttribute("timescale"))!=null?cl:"",10),ti=(dl=Ee.getAttribute("initialization"))!=null?dl:"",je=Ee.getAttribute("media"),Nt=(hl=parseInt((pl=Ee.getAttribute("startNumber"))!=null?pl:"",10))!=null?hl:1,ii=Lt(ti,yt);if(!je)throw new ReferenceError("No media attribute in SegmentTemplate");let Ft=(fl=Ee.querySelectorAll("SegmentTimeline S"))!=null?fl:[],ct=[],Ut=0,Ei="",nr=0;if(Ft.length){let Ua=Nt,it=0;for(let xi of Ft){let dt=parseInt((ml=xi.getAttribute("d"))!=null?ml:"",10),ri=parseInt((bl=xi.getAttribute("r"))!=null?bl:"",10)||0,qa=parseInt((gl=xi.getAttribute("t"))!=null?gl:"",10);it=Number.isFinite(qa)?qa:it;let cn=dt/tt*1e3,dn=it/tt*1e3;for(let Ha=0;Ha<ri+1;Ha++){let Eg=Lt(je,j(R({},yt),{segmentNumber:Ua.toString(10),segmentTime:(it+Ha*dt).toString(10)})),yl=(dn!=null?dn:0)+Ha*cn,xg=yl+cn;Ua++,ct.push({time:{from:yl,to:xg},url:Eg})}it+=(ri+1)*dt,Ut+=(ri+1)*cn}nr=it/tt*1e3,Ei=Lt(je,j(R({},yt),{segmentNumber:Ua.toString(10),segmentTime:it.toString(10)}))}else if((0,Ki.isNonNullable)(h)){let it=parseInt((Sl=Ee.getAttribute("duration"))!=null?Sl:"",10)/tt*1e3,xi=Math.ceil(h/it),dt=0;for(let ri=1;ri<xi;ri++){let qa=Lt(je,j(R({},yt),{segmentNumber:ri.toString(10),segmentTime:dt.toString(10)}));ct.push({time:{from:dt,to:dt+it},url:qa}),dt+=it}nr=dt,Ei=Lt(je,j(R({},yt),{segmentNumber:xi.toString(10),segmentTime:dt.toString(10)}))}let Ig={time:{from:nr,to:1/0},url:Ei};Ii={type:"template",baseUrl:Ma,segmentTemplateUrl:je,initUrl:ii,totalSegmentsDurationMs:Ut,segments:ct,nextSegmentBeyondManifest:Ig,timescale:tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!_t||!vi)continue;let sr={video:"video",audio:"audio",text:"text"}[_t];if(!sr)continue;ir||(ir=sr),Ca={id:Na,kind:sr,segmentReference:Ii,profiles:Fa,duration:h,bitrate:Ba,mime:vi,codecs:Da,width:ei,height:rr,fps:ln,quality:yi}}be.language||(be.language=vg),be.label||(be.label=yg),be.mime||(be.mime=vi),be.codecs||(be.codecs=Da),be.hdr||(be.hdr=ir==="video"&&Pu(Da)),be.representations.push(Ca)}ir&&r[ir].push(be)}return{dynamic:d,liveAvailabilityStartTime:p,duration:h,streams:r,baseUrls:o}};var Ru=Ge(qi(),1);var Vb=require("@vkontakte/videoplayer-shared"),Bb=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s})=>{var o;let n=(o=s?Gt(s):void 0)!=null?o:(0,Vb.videoSizeToQuality)({width:e,height:t});return n&&{id:a,quality:n,bitrate:i,size:{width:e,height:t},fps:r}},Ob=({id:a,bitrate:e})=>({id:a,bitrate:e}),_b=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Nb=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),$u=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Ru.default)(i.split("."),0),isDefault:r}),Lu=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Ru.default)(r.split("."),0)}),Mu=a=>"url"in a,qe=a=>a.type==="template",pa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ha=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new P.ValueSubject(0);this.onLastSegment$=new P.ValueSubject(!1);this.fullyBuffered$=new P.ValueSubject(!1);this.playingRepresentation$=new P.ValueSubject(void 0);this.playingRepresentationInit$=new P.ValueSubject(void 0);this.error$=new P.Subject;this.gaps=[];this.subscription=new P.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ie;this.switchAbortController=new Ie;this.destroyAbortController=new Ie;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,P.abortable)(this.destroyAbortController.signal,function(e){return he(this,null,function*(){let t=this.representations.get(e);(0,P.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Zm(this.sourceBuffer),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:P.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,Su(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=gt(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,P.assertNonNullable)(i,"No init buffer for starting representation"),(0,P.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchToOld=(0,P.abortable)(this.destroyAbortController.signal,function(e,t=!1){return he(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,P.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,P.isNullable)(s)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,P.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new hn(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,P.abortable)(this.destroyAbortController.signal,function(e){return he(this,null,function*(){var u,l;let t=(u=e==null?void 0:e.flatMap(d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(m=>m.id===d);c&&this.representations.set(d,c);let p=this.representations.get(d);if(!p||!qe(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,P.assertNonNullable)(r);let s=this.segments.get(i);(0,P.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,P.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Ie,(0,P.abortable)(this.switchAbortController.signal,function(i,r=!1){return he(this,null,function*(){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,P.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,P.isNullable)(o)||(0,P.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,P.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,P.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ie,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,d;if((0,P.isNullable)(e)||(0,P.isNullable)(this.downloadingRepresentationId)||(0,P.isNullable)(this.playingRepresentationId)||(0,P.isNullable)(this.sourceBuffer)||(0,P.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,P.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next(((l=r==null?void 0:r.time.to)!=null?l:0)-((d=r==null?void 0:r.time.from)!=null?d:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=gt(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&Su(this.sourceBuffer.buffered)>=this.bufferLimit){let c=gt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))c="high";else{let p=(0,Xi.default)(o,0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&>(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Xi.default)(i,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;(0,P.isNonNullable)(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?i:[];for(let o of t){if(!o||!qe(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>j(R({},p),{status:"none",size:void 0})),l=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,Xi.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,c=u==null?void 0:u.findIndex(p=>Math.floor(d)>=Math.floor(p.time.from)&&Math.floor(d)<=Math.floor(p.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(c+1);this.segments.set(o.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,P.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){var s;(0,P.assertNonNullable)(this.playingRepresentationId);let e=(s=this.representations.get(this.playingRepresentationId))==null?void 0:s.duration;(0,P.assertNonNullable)(e);let{shortVideoDuration:t,shortVideoBufferStallSize:i,longVideoBufferStallSize:r}=this.tuning.dash.accumulationBufferStallSize;this.bufferAccumulation={enabled:!1,targetBufferSizeMs:e<=t?i:r,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let i of this.representations.values()){let r=i.segmentReference;if(!qe(r))return;let s=(t=this.segments.get(i.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=Lt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:p,to:h}},m)=>{let g=p<=i&&h>=i,S=p>i||g||m===0&&i===0,x=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+x||h<=i+x;return(c==="none"||c==="partially_ejected"&&S&&T&&this.sourceBuffer&&!(Yt(this.sourceBuffer.buffered,p)&&Yt(this.sourceBuffer.buffered,h)))&&S&&T});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<s.length&&(n<=l||o<=d);c++){let p=s[c];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,i="auto"){return $(this,null,function*(){qe(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return $(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,P.abortable)(o,function(){return he(this,null,function*(){let d=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,P.now)(),!d)return;let c=new DataView(d);if(!isFinite(r.segment.time.to)){let p=t.segmentReference.timescale,h=da(t.mime);r.segment.time.to=h.getChunkEndTime(c,p)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),pa(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())qe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return $(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:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,P.abortable)(n,function(){return he(this,null,function*(){let u=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,P.fromEvent)(window,"online").pipe((0,P.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,P.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),pa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(qe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Xi.default)(e,0).byte.from,to:(0,Xi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!qe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return $(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=da(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return $(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:d}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let c=d.byte.from-i,p=d.byte.to-i,h=p-c+1,m=c<r,g=p<=r;if(!m)continue;let S=da(u.mime),x=this.tuning.dash.enableSubSegmentBufferFeeding&&(ob(S)||this.bufferAccumulation.targetBufferSizeMs===0);if(d.status==="downloading"&&g){d.status="downloaded";let T=new DataView(e.buffer,e.byteOffset+c,h),E=this.getCurrentPosition();(0,P.isNonNullable)(E)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-E,this.bufferAccumulation.accumulated.push({dataView:T,segmentProgress:l}),this.activeSegments.delete(l));let A=z=>$(this,[z],function*({dataView:w,segmentProgress:B}){(yield this.sourceBufferTaskQueue.append(w,s))&&!s.aborted?this.onSegmentFullyAppended(B,t):n()});this.bufferAccumulation.enabled&&this.bufferAccumulation.accumulatedBufferSizeMs>this.bufferAccumulation.targetBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(A),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||(0,P.isNullable)(E))&&(A({dataView:T,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(x&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(h,r-c),l.loadedBytes>l.feedingBytes)){let T=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),E=l.loadedBytes===h?T:S.parseFeedableSegmentChunk(T);E!=null&&E.byteLength&&(d.status="partially_fed",l.feedingBytes+=E.byteLength,(yield this.sourceBufferTaskQueue.append(E,s))&&!s.aborted?(l.fedBytes+=E.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):n())}}})}onSegmentFullyAppended(e,t){var i;this.tuning.useSafariEndlessRequestBugfix&&((0,P.assertNonNullable)(this.sourceBuffer),Yt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Yt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Mu(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");(0,P.assertNonNullable)(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment]),this.tuning.useNewPruneBufferStrategy&&this.pruneBuffer(this.getCurrentPosition(),1/0,!1)}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=bu(()=>(0,Fb.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return $(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,P.abortable)(this.destroyAbortController.signal,function(){return he(this,null,function*(){let o=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,da(e.mime),r)).then(o=>$(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&qe(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:P.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return $(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,i=!1){return $(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,P.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,p):l.push(u[d])}return l},o=u=>{var d;if(s>=t)return r;r.push(R({},u.time)),r=n(r);let l=Mu(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(0,P.isNullable)(e)?0:gt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){(0,P.assertNonNullable)(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=bu(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:P.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,P.isNullable)(this.sourceBuffer)||(0,P.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var fa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Ub=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};var X=require("@vkontakte/videoplayer-shared");var qb=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Qs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new X.ValueSubject(void 0);this.lastConnectionReused$=new X.ValueSubject(void 0);this.lastRequestFirstBytes$=new X.ValueSubject(void 0);this.abortAllController=new Ie;this.subscription=new X.Subscription;this.fetchManifest=(0,X.abortable)(this.abortAllController.signal,function(e){return he(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=fa(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=qb(i));let r=yield ot(i,{signal:this.abortAllController.signal}).catch(ma);return r?(t.log("success",(0,X.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,X.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,X.abortable)(this.abortAllController.signal,function(l){return he(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var N,te;let d=e,c=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let H=new URL(d,location.href);H.searchParams.append("bytes",`${i.from}-${i.to}`),d=H.toString();break}default:(0,X.assertNever)(t)}this.requestQuic&&(d=fa(d));let h=this.abortAllController.signal,m;if(n){let H=new Ie;if(m=(0,X.merge)((0,X.fromEvent)(this.abortAllController.signal,"abort"),(0,X.fromEvent)(n,"abort")).subscribe(()=>{try{H.abort()}catch(ne){ma(ne)}}),this.abortAllController.signal.aborted||n.aborted)try{H.abort()}catch(ne){ma(ne)}h=H.signal}let g=(0,X.now)();p.log("startRequest",(0,X.flattenObject)({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g}));let S=yield ot(d,{priority:s,headers:c,signal:h}).catch(ma),x=(0,X.now)();if(!S)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((N=this.throughputEstimator)==null||N.addRawRtt(x-g),!S.ok||!S.body){m==null||m.unsubscribe();let H=`Fetch error ${S.status}: ${S.statusText}`;return p.error("error",{message:H}),p.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!o){m==null||m.unsubscribe();let H=(0,X.now)(),ne={requestStartedAt:g,requestEndedAt:H,duration:H-g};return p.log("endRequest",(0,X.flattenObject)(ne)),p.end(),S.arrayBuffer()}let[T,E]=S.body.tee(),A=T.getReader();o&&((te=this.throughputEstimator)==null||te.trackStream(E,u));let w=0,B=new Uint8Array(0),z=!1,se=H=>{m==null||m.unsubscribe(),z=!0,ma(H)},q=(0,X.abortable)(h,function(I){return he(this,arguments,function*({done:H,value:ne}){if(w===0&&this.lastRequestFirstBytes$.next((0,X.now)()-g),h.aborted){m==null||m.unsubscribe();return}if(!H&&ne){let V=new Uint8Array(B.length+ne.length);V.set(B),V.set(ne,B.length),B=V,w+=ne.byteLength,r==null||r(new DataView(B.buffer),w),yield A==null?void 0:A.read().then(q,se)}})}.bind(this));yield A==null?void 0:A.read().then(q,se),m==null||m.unsubscribe();let W=(0,X.now)(),Z={failed:z,requestStartedAt:g,requestEndedAt:W,duration:W-g};return z?(p.error("endRequest",(0,X.flattenObject)(Z)),p.end(),null):(p.log("endRequest",(0,X.flattenObject)(Z)),p.end(),B.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,X.abortable)(this.abortAllController.signal,function(e,t,i){return he(this,null,function*(){var x;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(x=e.indexRange)!=null?x:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(c,m.from-n,m.to-m.from+1);else{let T=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!T)return null;g=new DataView(T)}let S=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(c),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,X.abortable)(this.abortAllController.signal,function(e,t){return he(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>j(R({},n),{status:"none",size:void 0})),dataView:new DataView(r)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Ub(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return $(this,null,function*(){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,X.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ma=a=>{if(!pa(a))throw a};var fi=(a,e,t)=>t*e+(1-t)*a,Du=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Hb=(a,e,t,i)=>{let r=0,s=t,n=Du(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};var ba=require("@vkontakte/videoplayer-shared");var Kt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new ba.ValueSubject(e.initial),this.debounced$=new ba.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ae(`raw_${t}`),this.smoothedSeries$=new Ae(`smoothed_${t}`),this.reportedSeries$=new Ae(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=pt(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,ba.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 Ws=class extends Kt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=fi(this.slow,e,this.params.emaAlphaSlow),this.fast=fi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ys=class extends Kt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Du(this.pastMeasures,this.takenMeasures);this.emaSmoothed=fi(this.emaSmoothed,e,this.params.emaAlpha);let i=Hb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var zs=class extends Kt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?fi(this.smoothed,t,this.params.emaAlpha):t}};var mi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ws({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Ys({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new zs(R({initial:e,label:"liveEdgeDelay"},t))}};var Cu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var Ks=require("@vkontakte/videoplayer-shared");var ga=class a{constructor(e,t){this.currentRepresentation$=new Ks.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,Ks.isNullable)(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(j(R({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&qe(t.segmentReference))}};var TA=["timeupdate","progress","play","seeked","stalled","waiting"],IA=["timeupdate","progress","loadeddata","playing","seeked"];var Xs=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 G("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentAudioRepresentation$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.currentLiveTextRepresentation$=new v.ValueSubject(null);this.isLive$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.isLowLatency$=new v.ValueSubject(!1);this.isActiveLowLatency$=new v.ValueSubject(!1);this.currentStallDuration$=new v.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new v.ValueSubject(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new Ie;this.initManifest=(0,v.abortable)(this.destroyController.signal,function(e,t,i){return he(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Te(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,function(){return he(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=null;try{t=Cb(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=zm(e))!=null?n:{id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,p,h,m;return!!((p=(c=this.element)==null?void 0:c.canPlayType)!=null&&p.call(c,l)&&((m=(h=Rt())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${l}; codecs="${d}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:h,codecs:m})=>i(u,h,m)),c=new Set(d.map(({codecs:h})=>h)),p=Ym(c);if(p&&(r[u]=d.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=r.video.some(S=>S.hdr),g=r.video.some(S=>!S.hdr);v.clientChecker.isHDR&&h&&m?r.video=r.video.filter(S=>S.hdr):g&&(r.video=r.video.filter(S=>!S.hdr))}}let s=j(R({},t),{streams:r});return this.tracer.log("updateManifestEnd",(0,v.flattenObject)(s)),s})}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,function(e,t,i){return he(this,null,function*(){var p;this.tracer.log("initRepresentationsStart",(0,v.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=h=>{this.representationSubscription.add((0,v.fromEvent)(h,"error").pipe((0,v.filter)(m=>{var g;return!!((g=this.element)!=null&&g.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Lm():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Os())if(i){let h=document.createElement("source");r(h),h.type="application/x-mpegurl",h.src=i.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());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((h,m)=>[...h,...m.representations],[]);if(this.videoBufferManager=new ha("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let h=this.manifest.streams.audio.reduce((m,g)=>[...m,...g.representations],[]);this.audioBufferManager=new ha("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}ga.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ga(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,v.interval)(1e3).subscribe(h=>{var m;if((m=this.element)!=null&&m.paused){let g=tu(this.manifestUrlString,2);this.manifestUrlString=Te(this.manifestUrlString,g+1e3,2)}}));let u=()=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,v.merge)(...IA.map(h=>(0,v.fromEvent)(this.element,h))).pipe((0,v.map)(h=>this.element?gt(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.tap)(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,v.merge)((0,v.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,v.filterChanged)()).subscribe(m=>Cu(this.element,1))),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,v.filter)(({bufferLength:m,isActiveLowLatency:g})=>g&&!!m)).subscribe(({bufferLength:m})=>this.liveEstimatedDelay.next(m))),this.representationSubscription.add((0,v.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:m,isActiveLowLatency:g})=>{if(!g)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,x=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=m-S,A=1;Math.abs(E)>x&&(A=1+Math.sign(E)*T),Cu(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var S,x;let g=0;if(m){let T=((x=(S=this.element)==null?void 0:S.currentTime)!=null?x:0)*1e3;g=Math.min(...this.bufferManagers.map(A=>{var w,B;return(B=(w=A.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?B:T}))-T}this.liveLoadBufferLength$.getValue()!==g&&this.liveLoadBufferLength$.next(g)}));let h=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(S=>$(this,[S],function*({liveLoadBufferLength:m,bufferLength:g}){if((0,v.assertNonNullable)(this.element),this.isUpdatingLive)return;let x=this.element.playbackRate,T=tu(this.manifestUrlString,2),E=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,A=Math.min(E,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*x),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*x,B=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*x,z=isFinite(m)?m:g,se=this.isActiveLowLatency$.getValue(),q=E<=this.tuning.live.activeLiveDelay&&T===0;this.isActiveLowLatency$.next(se&&q);let W="none";if(se?W="active_low_latency":this.isLowLatency$.getValue()&&q?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(Z=>Z.proceedLowLatencyLive()),W="active_low_latency"):T!==0&&z<A?W="live_forward_buffering":z<A+B&&(W="live_with_target_offset"),isFinite(m)&&(h=m>h?m:h),W==="live_forward_buffering"||W==="live_with_target_offset"){let Z=h-(A+w),N=this.normolizeLiveOffset(Math.trunc(T+Z/x)),te=Math.abs(N-T),H;!m||te<=this.tuning.dashCmafLive.offsetCalculationError?H=T:N>0&&te>this.tuning.dashCmafLive.offsetCalculationError?H=N:H=0,this.manifestUrlString=Te(this.manifestUrlString,H,2)}W!=="none"&&W!=="active_low_latency"&&(h=0,this.updateLive())})))}let l=(0,v.merge)(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=(0,v.merge)(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add((0,v.merge)(this.forceEnded$,(0,v.combine)({allBuffersFull:l,someBufferEnded:d}).pipe((0,v.filter)(({allBuffersFull:h,someBufferEnded:m})=>h&&m))).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(h=this.source)==null||h.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add((0,v.merge)(...this.bufferManagers.map(h=>h.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(h=>{var m;return(m=this.source)==null?void 0:m.addEventListener("sourceopen",h)}));let c=[(p=this.manifest.duration)!=null?p:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(h=>h.representations).flatMap(h=>{let m=[];return h.duration&&m.push(h.duration),qe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&(0,v.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,i,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(i=this.liveTextManager)==null||i.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Qs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveEstimatedDelay=mi.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,R({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return $(this,null,function*(){var i,r,s;(0,v.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=Te(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive(this.manifest.streams.video),yield(r=this.audioBufferManager)==null?void 0:r.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...TA.map(e=>(0,v.fromEvent)(this.element,e)),(0,v.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,v.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{var t,i,r;this.element&&this.element.readyState===2&&!this.element.seeking&&Yt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var g,S,x,T,E,A,w,B,z,se;if(!this.element)return;let s=this.currentStallDuration$.getValue();s+=50,this.currentStallDuration$.next(s);let n={timeInWaiting:s},o=(0,v.now)(),u=100,l=(S=(g=this.videoBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0;this.videoLastDataObtainedTimestamp$.next(l);let d=(T=(x=this.audioBufferManager)==null?void 0:x.lastDataObtainedTimestamp)!=null?T:0,c=(A=(E=this.videoBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?A:0,p=(B=(w=this.audioBufferManager)==null?void 0:w.getForwardBufferDuration())!=null?B:0,h=c<u&&o-l>this.tuning.dash.crashOnStallTWithoutDataTimeout,m=this.audioBufferManager&&p<u&&o-d>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||m)&&s>this.tuning.dash.crashOnStallTWithoutDataTimeout||s>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${s} ms`);if(this.isLive$.getValue()&&s%5e3===0)this.seekLive(this.liveLastSeekOffset),n.liveLastSeekOffset=this.liveLastSeekOffset;else{let q=this.element.currentTime*1e3;(z=this.videoBufferManager)==null||z.maintain(q),(se=this.audioBufferManager)==null||se.maintain(q),n.position=q}this.tracer.log("stallIntervalCallback",(0,v.flattenObject)(n))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(i=this.audioBufferManager)==null||i.startAccumulateBuffer(),(r=this.stallWatchdogSubscription)==null||r.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(50).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return $(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)})}seek(e,t){var r,s,n,o,u,l;(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Yt(this.element.buffered,i)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(l=this.audioBufferManager)==null||l.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,v.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,v.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return $(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,r=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=i&&o.to+s>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r.push(1/0):r.push(o.to));if(r.length){let n=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=j(R({},t),{gapEnds:r,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,v.flattenObject)(t)))}}};var Js=class{constructor(e,t){this.fov=e,this.orientation=t}};var Zs=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/pt(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed=R({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*pt(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Gb=`attribute vec2 a_vertex;
|
|
68
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var $b=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},$t=(a,e)=>{let t=a;t=(0,xu.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,xu.default)(t,n,(o,u)=>(0,Ki.isNullable)(s)?o:(0,Ki.isNullable)(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Mb=(a,e)=>{var w,V,z,se,U,Q,ee,N,ie,H,ne,R,P,J,W,fe,qe,Dt,bi,te,ve,ye,Ue,Bt,gi,Vt,Xt,Si,er,Fu,qu,Uu,Hu,ju,Gu,Qu,Wu,Yu,zu,Ku,Ju,Xu,Zu,el,tl,il,rl,al,sl,nl,ol,ul,ll,cl,dl,pl,hl,fl,ml,bl;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Te=>{var $a,Ot;return(Ot=($a=Te.textContent)==null?void 0:$a.trim())!=null?Ot:""}),u=(w=(0,Lb.default)(o,0))!=null?w:"",l=n.children,d=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),p=c?new Date(c).getTime():void 0,h,m=s.getAttribute("mediaPresentationDuration"),g=n.getAttribute("duration"),S=s.getElementsByTagName("vk:Attrs")[0],x=S==null?void 0:S.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)h=$b(m);else if(g){let Te=$b(g);(0,Ki.isNonNullable)(Te)&&(h=Te)}else x&&(h=parseInt(x,10));let T=0,I=(z=(V=s.getAttribute("profiles"))==null?void 0:V.split(","))!=null?z:[];for(let Te of l){let $a=(se=Te.getAttribute("id"))!=null?se:"id"+(T++).toString(10),Ot=(U=Te.getAttribute("mimeType"))!=null?U:"",sn=(Q=Te.getAttribute("codecs"))!=null?Q:"",nn=(ee=Te.getAttribute("contentType"))!=null?ee:Ot==null?void 0:Ot.split("/")[0],pg=(ie=(N=Te.getAttribute("profiles"))==null?void 0:N.split(","))!=null?ie:[],gl=(ne=Rb((H=Te.getAttribute("lang"))!=null?H:""))!=null?ne:{},hg=(J=(P=(R=Te.querySelector("Label"))==null?void 0:R.textContent)==null?void 0:P.trim())!=null?J:void 0,fg=Te.querySelectorAll("Representation"),mg=Te.querySelector("SegmentTemplate"),bg=(fe=(W=Te.querySelector("Role"))==null?void 0:W.getAttribute("value"))!=null?fe:void 0,tr=nn,me={id:$a,language:gl.language,isDefault:bg==="main",label:hg,codecs:sn,hdr:tr==="video"&&Eu(sn),mime:Ot,representations:[]};for(let oe of fg){let gg=(qe=oe.getAttribute("lang"))!=null?qe:void 0,Sg=(Dt=oe.getAttribute("label"))!=null?Dt:void 0,vg=(ve=(te=(bi=oe.querySelector("BaseURL"))==null?void 0:bi.textContent)==null?void 0:te.trim())!=null?ve:"",La=new URL(vg||u,e).toString(),vi=(ye=oe.getAttribute("mimeType"))!=null?ye:Ot,Ma=(Bt=(Ue=oe.getAttribute("codecs"))!=null?Ue:sn)!=null?Bt:"",Ca;if(nn==="text"){let _t=oe.getAttribute("id")||"",Da=((gi=gl.privateuse)==null?void 0:gi.includes("x-auto"))||_t.includes("_auto"),Zt=oe.querySelector("SegmentTemplate");if(Zt){let ir={representationId:(Vt=oe.getAttribute("id"))!=null?Vt:void 0,bandwidth:(Xt=oe.getAttribute("bandwidth"))!=null?Xt:void 0},Ba=parseInt((Si=oe.getAttribute("bandwidth"))!=null?Si:"",10)/1e3,Va=(Fu=parseInt((er=Zt.getAttribute("startNumber"))!=null?er:"",10))!=null?Fu:1,yi=parseInt((qu=Zt.getAttribute("timescale"))!=null?qu:"",10),on=(Uu=Zt.querySelectorAll("SegmentTimeline S"))!=null?Uu:[],Ti=Zt.getAttribute("media");if(!Ti)continue;let Oa=[],_a=0,Na="",Ii=0,rr=Va,Ee=0;for(let et of on){let ei=parseInt((Hu=et.getAttribute("d"))!=null?Hu:"",10),He=parseInt((ju=et.getAttribute("r"))!=null?ju:"",10)||0,Nt=parseInt((Gu=et.getAttribute("t"))!=null?Gu:"",10);Ee=Number.isFinite(Nt)?Nt:Ee;let ti=ei/yi*1e3,Ft=Ee/yi*1e3;for(let ut=0;ut<He+1;ut++){let qt=$t(Ti,K($({},ir),{segmentNumber:rr.toString(10),segmentTime:(Ee+ut*ei).toString(10)})),Ei=(Ft!=null?Ft:0)+ut*ti,sr=Ei+ti;rr++,Oa.push({time:{from:Ei,to:sr},url:qt})}Ee+=(He+1)*ei,_a+=(He+1)*ti}Ii=Ee/yi*1e3,Na=$t(Ti,K($({},ir),{segmentNumber:rr.toString(10),segmentTime:Ee.toString(10)}));let ar={time:{from:Ii,to:1/0},url:Na},St={type:"template",baseUrl:La,segmentTemplateUrl:Ti,initUrl:"",totalSegmentsDurationMs:_a,segments:Oa,nextSegmentBeyondManifest:ar,timescale:yi};Ca={id:_t,kind:"text",segmentReference:St,profiles:[],duration:h,bitrate:Ba,mime:"",codecs:"",width:0,height:0,isAuto:Da}}else Ca={id:_t,isAuto:Da,kind:"text",url:La}}else{let _t=(Wu=(Qu=oe.getAttribute("contentType"))!=null?Qu:vi==null?void 0:vi.split("/")[0])!=null?Wu:nn,Da=(zu=(Yu=Te.getAttribute("profiles"))==null?void 0:Yu.split(","))!=null?zu:[],Zt=parseInt((Ku=oe.getAttribute("width"))!=null?Ku:"",10),ir=parseInt((Ju=oe.getAttribute("height"))!=null?Ju:"",10),Ba=parseInt((Xu=oe.getAttribute("bandwidth"))!=null?Xu:"",10)/1e3,Va=(Zu=oe.getAttribute("frameRate"))!=null?Zu:"",yi=(el=oe.getAttribute("quality"))!=null?el:void 0,on=Va?kb(Va):void 0,Ti=(tl=oe.getAttribute("id"))!=null?tl:"id"+(T++).toString(10),Oa=_t==="video"?`${ir}p`:_t==="audio"?`${Ba}Kbps`:Ma,_a=`${Ti}@${Oa}`,Na=[...I,...pg,...Da],Ii,rr=oe.querySelector("SegmentBase"),Ee=(il=oe.querySelector("SegmentTemplate"))!=null?il:mg;if(rr){let St=(al=(rl=oe.querySelector("SegmentBase Initialization"))==null?void 0:rl.getAttribute("range"))!=null?al:"",[et,ei]=St.split("-").map(qt=>parseInt(qt,10)),He={from:et,to:ei},Nt=(sl=oe.querySelector("SegmentBase"))==null?void 0:sl.getAttribute("indexRange"),[ti,Ft]=Nt?Nt.split("-").map(qt=>parseInt(qt,10)):[],ut=Nt?{from:ti,to:Ft}:void 0;Ii={type:"byteRange",url:La,initRange:He,indexRange:ut}}else if(Ee){let St={representationId:(nl=oe.getAttribute("id"))!=null?nl:void 0,bandwidth:(ol=oe.getAttribute("bandwidth"))!=null?ol:void 0},et=parseInt((ul=Ee.getAttribute("timescale"))!=null?ul:"",10),ei=(ll=Ee.getAttribute("initialization"))!=null?ll:"",He=Ee.getAttribute("media"),Nt=(dl=parseInt((cl=Ee.getAttribute("startNumber"))!=null?cl:"",10))!=null?dl:1,ti=$t(ei,St);if(!He)throw new ReferenceError("No media attribute in SegmentTemplate");let Ft=(pl=Ee.querySelectorAll("SegmentTimeline S"))!=null?pl:[],ut=[],qt=0,Ei="",sr=0;if(Ft.length){let Fa=Nt,tt=0;for(let xi of Ft){let lt=parseInt((hl=xi.getAttribute("d"))!=null?hl:"",10),ii=parseInt((fl=xi.getAttribute("r"))!=null?fl:"",10)||0,qa=parseInt((ml=xi.getAttribute("t"))!=null?ml:"",10);tt=Number.isFinite(qa)?qa:tt;let un=lt/et*1e3,ln=tt/et*1e3;for(let Ua=0;Ua<ii+1;Ua++){let Tg=$t(He,K($({},St),{segmentNumber:Fa.toString(10),segmentTime:(tt+Ua*lt).toString(10)})),Sl=(ln!=null?ln:0)+Ua*un,Ig=Sl+un;Fa++,ut.push({time:{from:Sl,to:Ig},url:Tg})}tt+=(ii+1)*lt,qt+=(ii+1)*un}sr=tt/et*1e3,Ei=$t(He,K($({},St),{segmentNumber:Fa.toString(10),segmentTime:tt.toString(10)}))}else if((0,Ki.isNonNullable)(h)){let tt=parseInt((bl=Ee.getAttribute("duration"))!=null?bl:"",10)/et*1e3,xi=Math.ceil(h/tt),lt=0;for(let ii=1;ii<xi;ii++){let qa=$t(He,K($({},St),{segmentNumber:ii.toString(10),segmentTime:lt.toString(10)}));ut.push({time:{from:lt,to:lt+tt},url:qa}),lt+=tt}sr=lt,Ei=$t(He,K($({},St),{segmentNumber:xi.toString(10),segmentTime:lt.toString(10)}))}let yg={time:{from:sr,to:1/0},url:Ei};Ii={type:"template",baseUrl:La,segmentTemplateUrl:He,initUrl:ti,totalSegmentsDurationMs:qt,segments:ut,nextSegmentBeyondManifest:yg,timescale:et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!_t||!vi)continue;let ar={video:"video",audio:"audio",text:"text"}[_t];if(!ar)continue;tr||(tr=ar),Ca={id:_a,kind:ar,segmentReference:Ii,profiles:Na,duration:h,bitrate:Ba,mime:vi,codecs:Ma,width:Zt,height:ir,fps:on,quality:yi}}me.language||(me.language=gg),me.label||(me.label=Sg),me.mime||(me.mime=vi),me.codecs||(me.codecs=Ma),me.hdr||(me.hdr=tr==="video"&&Eu(Ma)),me.representations.push(Ca)}tr&&r[tr].push(me)}return{dynamic:d,liveAvailabilityStartTime:p,duration:h,streams:r,baseUrls:o}};var wu=je(Ui(),1);var Cb=require("@vkontakte/videoplayer-shared"),Db=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s})=>{var o;let n=(o=s?Gt(s):void 0)!=null?o:(0,Cb.videoSizeToQuality)({width:e,height:t});return n&&{id:a,quality:n,bitrate:i,size:{width:e,height:t},fps:r}},Bb=({id:a,bitrate:e})=>({id:a,bitrate:e}),Vb=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Ob=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),ku=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,wu.default)(i.split("."),0),isDefault:r}),Ru=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,wu.default)(r.split("."),0)}),$u=a=>"url"in a,Fe=a=>a.type==="template",da=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var pa=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new E.ValueSubject(0);this.onLastSegment$=new E.ValueSubject(!1);this.fullyBuffered$=new E.ValueSubject(!1);this.playingRepresentation$=new E.ValueSubject(void 0);this.playingRepresentationInit$=new E.ValueSubject(void 0);this.error$=new E.Subject;this.gaps=[];this.subscription=new E.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ne;this.switchAbortController=new Ne;this.destroyAbortController=new Ne;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,E.abortable)(this.destroyAbortController.signal,function(e){return he(this,null,function*(){let t=this.representations.get(e);(0,E.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Jm(this.sourceBuffer),this.subscription.add((0,E.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,E.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:E.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,bu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=mt(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,E.assertNonNullable)(i,"No init buffer for starting representation"),(0,E.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchToOld=(0,E.abortable)(this.destroyAbortController.signal,function(e,t=!1){return he(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,E.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,E.isNullable)(s)||(0,E.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,E.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,E.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new dn(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,E.abortable)(this.destroyAbortController.signal,function(e){return he(this,null,function*(){var u,l;let t=(u=e==null?void 0:e.flatMap(d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(m=>m.id===d);c&&this.representations.set(d,c);let p=this.representations.get(d);if(!p||!Fe(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,E.assertNonNullable)(r);let s=this.segments.get(i);(0,E.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,E.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Ne,(0,E.abortable)(this.switchAbortController.signal,function(i,r=!1){return he(this,null,function*(){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,E.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,E.isNullable)(o)||(0,E.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,E.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,E.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ne,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,d;if((0,E.isNullable)(e)||(0,E.isNullable)(this.downloadingRepresentationId)||(0,E.isNullable)(this.playingRepresentationId)||(0,E.isNullable)(this.sourceBuffer)||(0,E.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,E.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next(((l=r==null?void 0:r.time.to)!=null?l:0)-((d=r==null?void 0:r.time.from)!=null?d:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=mt(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&bu(this.sourceBuffer.buffered)>=this.bufferLimit){let c=mt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))c="high";else{let p=(0,Ji.default)(o,0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&mt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Ji.default)(i,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;(0,E.isNonNullable)(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?i:[];for(let o of t){if(!o||!Fe(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>K($({},p),{status:"none",size:void 0})),l=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,Ji.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,c=u==null?void 0:u.findIndex(p=>Math.floor(d)>=Math.floor(p.time.from)&&Math.floor(d)<=Math.floor(p.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(c+1);this.segments.set(o.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,E.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){var s;(0,E.assertNonNullable)(this.playingRepresentationId);let e=(s=this.representations.get(this.playingRepresentationId))==null?void 0:s.duration;(0,E.assertNonNullable)(e);let{shortVideoDuration:t,shortVideoBufferStallSize:i,longVideoBufferStallSize:r}=this.tuning.dash.accumulationBufferStallSize;this.bufferAccumulation={enabled:!1,targetBufferSizeMs:e<=t?i:r,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let i of this.representations.values()){let r=i.segmentReference;if(!Fe(r))return;let s=(t=this.segments.get(i.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=$t(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:p,to:h}},m)=>{let g=p<=i&&h>=i,S=p>i||g||m===0&&i===0,x=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+x||h<=i+x;return(c==="none"||c==="partially_ejected"&&S&&T&&this.sourceBuffer&&!(Yt(this.sourceBuffer.buffered,p)&&Yt(this.sourceBuffer.buffered,h)))&&S&&T});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<s.length&&(n<=l||o<=d);c++){let p=s[c];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,i="auto"){return B(this,null,function*(){Fe(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return B(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,E.abortable)(o,function(){return he(this,null,function*(){let d=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,E.now)(),!d)return;let c=new DataView(d);if(!isFinite(r.segment.time.to)){let p=t.segmentReference.timescale,h=ca(t.mime);r.segment.time.to=h.getChunkEndTime(c,p)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),da(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Fe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return B(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:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,E.abortable)(n,function(){return he(this,null,function*(){let u=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,E.fromEvent)(window,"online").pipe((0,E.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,E.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),da(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Fe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ji.default)(e,0).byte.from,to:(0,Ji.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,E.now)(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Fe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,E.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return B(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=ca(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return B(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:d}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let c=d.byte.from-i,p=d.byte.to-i,h=p-c+1,m=c<r,g=p<=r;if(!m)continue;let S=ca(u.mime),x=this.tuning.dash.enableSubSegmentBufferFeeding&&(sb(S)||this.bufferAccumulation.targetBufferSizeMs===0);if(d.status==="downloading"&&g){d.status="downloaded";let T=new DataView(e.buffer,e.byteOffset+c,h),I=this.getCurrentPosition();(0,E.isNonNullable)(I)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-I,this.bufferAccumulation.accumulated.push({dataView:T,segmentProgress:l}),this.activeSegments.delete(l));let A=z=>B(this,[z],function*({dataView:w,segmentProgress:V}){(yield this.sourceBufferTaskQueue.append(w,s))&&!s.aborted?this.onSegmentFullyAppended(V,t):n()});this.bufferAccumulation.enabled&&this.bufferAccumulation.accumulatedBufferSizeMs>this.bufferAccumulation.targetBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(A),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||(0,E.isNullable)(I))&&(A({dataView:T,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(x&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(h,r-c),l.loadedBytes>l.feedingBytes)){let T=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),I=l.loadedBytes===h?T:S.parseFeedableSegmentChunk(T);I!=null&&I.byteLength&&(d.status="partially_fed",l.feedingBytes+=I.byteLength,(yield this.sourceBufferTaskQueue.append(I,s))&&!s.aborted?(l.fedBytes+=I.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):n())}}})}onSegmentFullyAppended(e,t){var i;this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&((0,E.assertNonNullable)(this.sourceBuffer),Yt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Yt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",$u(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");(0,E.assertNonNullable)(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=fu(()=>(0,_b.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return B(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,E.abortable)(this.destroyAbortController.signal,function(){return he(this,null,function*(){let o=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ca(e.mime),r)).then(o=>B(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&Fe(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:E.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return B(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,i=!1){return B(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,E.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,p):l.push(u[d])}return l},o=u=>{var d;if(s>=t)return r;r.push($({},u.time)),r=n(r);let l=$u(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(0,E.isNullable)(e)?0:mt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){(0,E.assertNonNullable)(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=fu(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:E.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,E.isNullable)(this.sourceBuffer)||(0,E.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var ha=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Nb=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};var X=require("@vkontakte/videoplayer-shared");var Fb=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Gs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new X.ValueSubject(void 0);this.lastConnectionReused$=new X.ValueSubject(void 0);this.lastRequestFirstBytes$=new X.ValueSubject(void 0);this.abortAllController=new Ne;this.subscription=new X.Subscription;this.fetchManifest=(0,X.abortable)(this.abortAllController.signal,function(e){return he(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ha(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Fb(i));let r=yield wt(i,{signal:this.abortAllController.signal}).catch(fa);return r?(t.log("success",(0,X.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,X.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,X.abortable)(this.abortAllController.signal,function(l){return he(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var N,ie;let d=e,c=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let H=new URL(d,location.href);H.searchParams.append("bytes",`${i.from}-${i.to}`),d=H.toString();break}default:(0,X.assertNever)(t)}this.requestQuic&&(d=ha(d));let h=this.abortAllController.signal,m;if(n){let H=new Ne;if(m=(0,X.merge)((0,X.fromEvent)(this.abortAllController.signal,"abort"),(0,X.fromEvent)(n,"abort")).subscribe(()=>{try{H.abort()}catch(ne){fa(ne)}}),this.abortAllController.signal.aborted||n.aborted)try{H.abort()}catch(ne){fa(ne)}h=H.signal}let g=(0,X.now)();p.log("startRequest",(0,X.flattenObject)({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g}));let S=yield wt(d,{priority:s,headers:c,signal:h}).catch(fa),x=(0,X.now)();if(!S)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((N=this.throughputEstimator)==null||N.addRawRtt(x-g),!S.ok||!S.body){m==null||m.unsubscribe();let H=`Fetch error ${S.status}: ${S.statusText}`;return p.error("error",{message:H}),p.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!o){m==null||m.unsubscribe();let H=(0,X.now)(),ne={requestStartedAt:g,requestEndedAt:H,duration:H-g};return p.log("endRequest",(0,X.flattenObject)(ne)),p.end(),S.arrayBuffer()}let[T,I]=S.body.tee(),A=T.getReader();o&&((ie=this.throughputEstimator)==null||ie.trackStream(I,u));let w=0,V=new Uint8Array(0),z=!1,se=H=>{m==null||m.unsubscribe(),z=!0,fa(H)},U=(0,X.abortable)(h,function(R){return he(this,arguments,function*({done:H,value:ne}){if(w===0&&this.lastRequestFirstBytes$.next((0,X.now)()-g),h.aborted){m==null||m.unsubscribe();return}if(!H&&ne){let P=new Uint8Array(V.length+ne.length);P.set(V),P.set(ne,V.length),V=P,w+=ne.byteLength,r==null||r(new DataView(V.buffer),w),yield A==null?void 0:A.read().then(U,se)}})}.bind(this));yield A==null?void 0:A.read().then(U,se),m==null||m.unsubscribe();let Q=(0,X.now)(),ee={failed:z,requestStartedAt:g,requestEndedAt:Q,duration:Q-g};return z?(p.error("endRequest",(0,X.flattenObject)(ee)),p.end(),null):(p.log("endRequest",(0,X.flattenObject)(ee)),p.end(),V.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,X.abortable)(this.abortAllController.signal,function(e,t,i){return he(this,null,function*(){var x;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(x=e.indexRange)!=null?x:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(c,m.from-n,m.to-m.from+1);else{let T=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!T)return null;g=new DataView(T)}let S=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(c),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,X.abortable)(this.abortAllController.signal,function(e,t){return he(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>K($({},n),{status:"none",size:void 0})),dataView:new DataView(r)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Nb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return B(this,null,function*(){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,X.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},fa=a=>{if(!da(a))throw a};var hi=(a,e,t)=>t*e+(1-t)*a,Lu=(a,e)=>a.reduce((t,i)=>t+i,0)/e,qb=(a,e,t,i)=>{let r=0,s=t,n=Lu(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};var ma=require("@vkontakte/videoplayer-shared");var Kt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new ma.ValueSubject(e.initial),this.debounced$=new ma.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ae(`raw_${t}`),this.smoothedSeries$=new Ae(`smoothed_${t}`),this.reportedSeries$=new Ae(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=ct(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,ma.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Qs=class extends Kt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=hi(this.slow,e,this.params.emaAlphaSlow),this.fast=hi(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 Kt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Lu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=hi(this.emaSmoothed,e,this.params.emaAlpha);let i=qb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ys=class extends Kt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?hi(this.smoothed,t,this.params.emaAlpha):t}};var fi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Qs({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Ws({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Ys($({initial:e,label:"liveEdgeDelay"},t))}};var Mu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var zs=require("@vkontakte/videoplayer-shared");var ba=class a{constructor(e,t){this.currentRepresentation$=new zs.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,zs.isNullable)(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(K($({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Fe(t.segmentReference))}};var vA=["timeupdate","progress","play","seeked","stalled","waiting"],yA=["timeupdate","progress","loadeddata","playing","seeked"];var Ks=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new v.Subscription;this.representationSubscription=new v.Subscription;this.state$=new j("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentAudioRepresentation$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.currentLiveTextRepresentation$=new v.ValueSubject(null);this.isLive$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.isLowLatency$=new v.ValueSubject(!1);this.isActiveLowLatency$=new v.ValueSubject(!1);this.currentStallDuration$=new v.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new v.ValueSubject(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new Ne;this.initManifest=(0,v.abortable)(this.destroyController.signal,function(e,t,i){return he(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ie(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,function(){return he(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=null;try{t=Mb(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Wm(e))!=null?n:{id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,p,h,m;return!!((p=(c=this.element)==null?void 0:c.canPlayType)!=null&&p.call(c,l)&&((m=(h=kt())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${l}; codecs="${d}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:h,codecs:m})=>i(u,h,m)),c=new Set(d.map(({codecs:h})=>h)),p=Qm(c);if(p&&(r[u]=d.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=r.video.some(S=>S.hdr),g=r.video.some(S=>!S.hdr);v.clientChecker.isHDR&&h&&m?r.video=r.video.filter(S=>S.hdr):g&&(r.video=r.video.filter(S=>!S.hdr))}}let s=K($({},t),{streams:r});return this.tracer.log("updateManifestEnd",(0,v.flattenObject)(s)),s})}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,function(e,t,i){return he(this,null,function*(){var p;this.tracer.log("initRepresentationsStart",(0,v.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=h=>{this.representationSubscription.add((0,v.fromEvent)(h,"error").pipe((0,v.filter)(m=>{var g;return!!((g=this.element)!=null&&g.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Rm():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Vs())if(i){let h=document.createElement("source");r(h),h.type="application/x-mpegurl",h.src=i.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());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((h,m)=>[...h,...m.representations],[]);if(this.videoBufferManager=new pa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let h=this.manifest.streams.audio.reduce((m,g)=>[...m,...g.representations],[]);this.audioBufferManager=new pa("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}ba.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ba(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,v.interval)(1e3).subscribe(h=>{var m;if((m=this.element)!=null&&m.paused){let g=Zo(this.manifestUrlString,2);this.manifestUrlString=Ie(this.manifestUrlString,g+1e3,2)}}));let u=()=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,v.merge)(...yA.map(h=>(0,v.fromEvent)(this.element,h))).pipe((0,v.map)(h=>this.element?mt(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.tap)(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,v.merge)((0,v.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,v.filterChanged)()).subscribe(m=>Mu(this.element,1))),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,v.filter)(({bufferLength:m,isActiveLowLatency:g})=>g&&!!m)).subscribe(({bufferLength:m})=>this.liveEstimatedDelay.next(m))),this.representationSubscription.add((0,v.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:m,isActiveLowLatency:g})=>{if(!g)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,x=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=m-S,A=1;Math.abs(I)>x&&(A=1+Math.sign(I)*T),Mu(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var S,x;let g=0;if(m){let T=((x=(S=this.element)==null?void 0:S.currentTime)!=null?x:0)*1e3;g=Math.min(...this.bufferManagers.map(A=>{var w,V;return(V=(w=A.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?V:T}))-T}this.liveLoadBufferLength$.getValue()!==g&&this.liveLoadBufferLength$.next(g)}));let h=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(S=>B(this,[S],function*({liveLoadBufferLength:m,bufferLength:g}){if((0,v.assertNonNullable)(this.element),this.isUpdatingLive)return;let x=this.element.playbackRate,T=Zo(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,A=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*x),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*x,V=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*x,z=isFinite(m)?m:g,se=this.isActiveLowLatency$.getValue(),U=I<=this.tuning.live.activeLiveDelay&&T===0;this.isActiveLowLatency$.next(se&&U);let Q="none";if(se?Q="active_low_latency":this.isLowLatency$.getValue()&&U?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(ee=>ee.proceedLowLatencyLive()),Q="active_low_latency"):T!==0&&z<A?Q="live_forward_buffering":z<A+V&&(Q="live_with_target_offset"),isFinite(m)&&(h=m>h?m:h),Q==="live_forward_buffering"||Q==="live_with_target_offset"){let ee=h-(A+w),N=this.normolizeLiveOffset(Math.trunc(T+ee/x)),ie=Math.abs(N-T),H;!m||ie<=this.tuning.dashCmafLive.offsetCalculationError?H=T:N>0&&ie>this.tuning.dashCmafLive.offsetCalculationError?H=N:H=0,this.manifestUrlString=Ie(this.manifestUrlString,H,2)}Q!=="none"&&Q!=="active_low_latency"&&(h=0,this.updateLive())})))}let l=(0,v.merge)(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=(0,v.merge)(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add((0,v.merge)(this.forceEnded$,(0,v.combine)({allBuffersFull:l,someBufferEnded:d}).pipe((0,v.filter)(({allBuffersFull:h,someBufferEnded:m})=>h&&m))).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(h=this.source)==null||h.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add((0,v.merge)(...this.bufferManagers.map(h=>h.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(h=>{var m;return(m=this.source)==null?void 0:m.addEventListener("sourceopen",h)}));let c=[(p=this.manifest.duration)!=null?p:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(h=>h.representations).flatMap(h=>{let m=[];return h.duration&&m.push(h.duration),Fe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&(0,v.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,i,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(i=this.liveTextManager)==null||i.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Gs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveEstimatedDelay=fi.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,$({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return B(this,null,function*(){var i,r,s;(0,v.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=Ie(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive(this.manifest.streams.video),yield(r=this.audioBufferManager)==null?void 0:r.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...vA.map(e=>(0,v.fromEvent)(this.element,e)),(0,v.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,v.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{var t,i,r;this.element&&this.element.readyState===2&&!this.element.seeking&&Yt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var g,S,x,T,I,A,w,V,z,se;if(!this.element)return;let s=this.currentStallDuration$.getValue();s+=50,this.currentStallDuration$.next(s);let n={timeInWaiting:s},o=(0,v.now)(),u=100,l=(S=(g=this.videoBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0;this.videoLastDataObtainedTimestamp$.next(l);let d=(T=(x=this.audioBufferManager)==null?void 0:x.lastDataObtainedTimestamp)!=null?T:0,c=(A=(I=this.videoBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?A:0,p=(V=(w=this.audioBufferManager)==null?void 0:w.getForwardBufferDuration())!=null?V:0,h=c<u&&o-l>this.tuning.dash.crashOnStallTWithoutDataTimeout,m=this.audioBufferManager&&p<u&&o-d>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||m)&&s>this.tuning.dash.crashOnStallTWithoutDataTimeout||s>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${s} ms`);if(this.isLive$.getValue()&&s%5e3===0)this.seekLive(this.liveLastSeekOffset),n.liveLastSeekOffset=this.liveLastSeekOffset;else{let U=this.element.currentTime*1e3;(z=this.videoBufferManager)==null||z.maintain(U),(se=this.audioBufferManager)==null||se.maintain(U),n.position=U}this.tracer.log("stallIntervalCallback",(0,v.flattenObject)(n))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(i=this.audioBufferManager)==null||i.startAccumulateBuffer(),(r=this.stallWatchdogSubscription)==null||r.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(50).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return B(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)})}seek(e,t){var r,s,n,o,u,l;(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Yt(this.element.buffered,i)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(l=this.audioBufferManager)==null||l.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,v.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,v.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return B(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,r=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=i&&o.to+s>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r.push(1/0):r.push(o.to));if(r.length){let n=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=K($({},t),{gapEnds:r,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,v.flattenObject)(t)))}}};var Js=class{constructor(e,t){this.fov=e,this.orientation=t}};var Xs=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/ct(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed=$({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*ct(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Hb=`attribute vec2 a_vertex;
|
|
69
69
|
attribute vec2 a_texel;
|
|
70
70
|
|
|
71
71
|
varying vec2 v_texel;
|
|
@@ -76,7 +76,7 @@ void main(void) {
|
|
|
76
76
|
// save texel vector to pass to fragment shader
|
|
77
77
|
v_texel = a_texel;
|
|
78
78
|
}
|
|
79
|
-
`;var
|
|
79
|
+
`;var jb=`#ifdef GL_ES
|
|
80
80
|
precision highp float;
|
|
81
81
|
precision highp int;
|
|
82
82
|
#else
|
|
@@ -119,6 +119,5 @@ void main(void) {
|
|
|
119
119
|
// sample using new coordinates
|
|
120
120
|
gl_FragColor = texture2D(u_texture, tc);
|
|
121
121
|
}
|
|
122
|
-
`;var en=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Js(this.params.fov,this.params.orientation),this.cameraRotationManager=new Zs(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Gb,this.gl.VERTEX_SHADER),i=this.createShader(Qb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,p=t+r;return[s,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var ve=require("@vkontakte/videoplayer-shared"),Vu=class{constructor(){this.isSeeked$=new ve.ValueSubject(!1);this.isBuffering$=new ve.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new ve.Subscription}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add((0,ve.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,ve.filter)(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,ve.combine)({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:i})=>{if((0,ve.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:r,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),d=this.videoLastDataObtainedTimestamp$.getValue(),c=(0,ve.now)(),p=n&&this.currentStallsCount>=n,h=r&&!i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=r+u&&t>=r,m=s&&c-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&c-d>=s+u&&t>=s;(p||h||m)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,ve.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,ve.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Wb=Vu;var bi=class{constructor(e){this.subscription=new _.Subscription;this.videoState=new G("stopped");this.elementSize$=new _.ValueSubject(void 0);this.textTracksManager=new Ke;this.droppedFramesManager=new Ds;this.stallsManager=new Wb;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Vr;this.audioTrackSwitchHistory=new Vr;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(r.position-l,r.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,_.assertNever)(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new en(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=Re(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Xs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Me(this.video),r=this.constructor.name,s=o=>{e.error$.next({id:r,category:_.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){var d;let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,_.filter)(c=>!!c.length),(0,_.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,_.map)(c=>c.to.state!=="none"),(0,_.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,_.filterChanged)()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,_.filter)(_.isNonNullable),(0,_.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,_.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(Le(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),s((0,_.observeElementSize)(this.video),this.elementSize$),s(Xe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams();if((0,_.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of p.audio){m.push($u(g));let S=[];for(let x of g.representations){let T=Ob(x);S.push(T),this.audioTracksMap.set(T,{stream:g,representation:x})}this.audioStreamsMap.set(g,S)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of p.video){h.push(Lu(m));let g=[];for(let S of m.representations){let x=Bb(S);x&&(g.push(x),this.videoTracksMap.set(x,{stream:m,representation:S}))}this.videoStreamsMap.set(m,g)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let m of p.text)for(let g of m.representations){let S=_b(m,g);this.textTracksMap.set(S,{stream:m,representation:g})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=c=>e.error$.next({id:"RepresentationSwitch",category:_.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,_.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,_.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,g]=h,S=[...this.videoTracksMap.keys()].find(T=>{var E;return((E=this.videoTracksMap.get(T))==null?void 0:E.representation.id)===m.id});(0,_.isNonNullable)(S)&&(this.stallsManager.lastVideoTrackSelected=S);let x=this.params.desiredState.autoVideoTrackLimits.getTransition();if(x&&this.params.output.autoVideoTrackLimits$.next(x.to),c==="manifest_ready")this.player.initRepresentations(m.id,g==null?void 0:g.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",m.id).catch(o),g){let T=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",g.id,T).catch(o)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,_.filterChanged)()).subscribe(c=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=p,g=this.params.desiredState.videoStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.videoStream.setState(g.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Lu(m))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,_.filterChanged)()).subscribe(c=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,g=this.params.desiredState.audioStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.audioStream.setState(g.to),e.currentAudioStream$.next($u(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var p,h;if(c!=null&&c.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),(d=this.textTracksManager)==null||d.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe((0,_.map)(({to:c})=>c==="ready"),(0,_.filterChanged)());this.subscription.add((0,_.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,_.merge)(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,_.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,_.observableFrom)(["init"])).pipe((0,_.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var B,z,se,q,W,Z,N,te,H,ne,I,V,ie;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(B=e.videoTrack.getState())==null?void 0:B.id,n=[...this.videoTracksMap.keys()].find(({id:K})=>K===r),o=t.currentVideoTrack$.getValue(),u=((q=(se=e.videoStream.getState())!=null?se:n&&((z=this.videoTracksMap.get(n))==null?void 0:z.stream))!=null?q:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:K})=>K===u.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=gt(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(c/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=(W=e.audioStream.getState())!=null?W:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(Z=[...this.audioStreamsMap.keys()].find(({id:K})=>K===(m==null?void 0:m.id)))!=null?Z:this.audioStreamsMap.keys().next().value,S=0;if(g){if(n&&!i){let K=Ls(n,d,(N=this.audioStreamsMap.get(g))!=null?N:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,(te=K==null?void 0:K.bitrate)!=null?te:-1/0)}if(o){let K=Ls(o,d,(H=this.audioStreamsMap.get(g))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,(ne=K==null?void 0:K.bitrate)!=null?ne:-1/0)}}let x=Wt(d,{container:this.elementSize$.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),T=i?x!=null?x:n:n!=null?n:x,E=g&&Em(T,d,(I=this.audioStreamsMap.get(g))!=null?I:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=(V=this.videoTracksMap.get(T))==null?void 0:V.representation,w=E&&((ie=this.audioTracksMap.get(E))==null?void 0:ie.representation);if(A&&w)return[A,w];if(A&&!w&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){De(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.ErrorCategory.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),$e(this.video),this.tracer.end()}};var va=class extends bi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Xt=require("@vkontakte/videoplayer-shared");var ya=class extends bi{constructor(e){super(e),this.liveOffset=new At,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:i,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(i.isLowLatency.stateChangeEnded$.pipe((0,Xt.map)(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,Xt.combine)({interval:(0,Xt.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add((0,Xt.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Xt.map)(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Nb(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,r)})}};var Yb=Ge(ks(),1);var Y=require("@vkontakte/videoplayer-shared");var lt={};var Ji=(a,e)=>new Y.Observable(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),Ta=class{constructor(e){this.subscription=new Y.Subscription;this.videoState=new G("initializing");this.textTracksManager=new Ke;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,Y.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,Y.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,Y.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,Y.assertNever)(e)}break;default:(0,Y.assertNever)(t)}};this.video=Re(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),$e(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Y.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Yb.default)(import("hls.js").then(r=>{e||(lt.Hls=r.default,lt.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){(0,Y.assertNonNullable)(lt.Hls,"hls.js not loaded"),this.hls=new lt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,Y.assertNonNullable)(lt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:Y.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=Me(this.video),s=(l,d)=>this.subscription.add(l.subscribe(d,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(mt(this.video,e.isLooped,i)),this.subscription.add(Le(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ze(this.video,e.playbackRate,r.playbackRateState$,i)),s(Xe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,Y.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Ji(this.hls,lt.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Y.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)==null?void 0:d.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(Ji(this.hls,lt.Events.MANIFEST_PARSED).pipe((0,Y.map)(({levels:l})=>l.reduce((d,c)=>{var T,E;let p=c.name||c.height.toString(10),{width:h,height:m}=c,g=(E=Gt((T=c.attrs.QUALITY)!=null?T:""))!=null?E:(0,Y.videoSizeToQuality)({width:h,height:m});if(!g)return d;let S=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,x={id:p.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:h,height:m},fps:S};return this.trackLevels.set(p,{track:x,level:c}),d.push(x),d},[]))),t.availableVideoTracks$),s(Ji(this.hls,lt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let p=c.name,h=c.attrs.URI||"",m=c.lang;d.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(Ji(this.hls,lt.Events.LEVEL_LOADING).pipe((0,Y.map)(({url:l})=>ge(l))),t.hostname$),s(Ji(this.hls,lt.Events.FRAG_CHANGED),l=>{var p,h,m,g;let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=d==null?void 0:d.endPTS)!=null?p:0)-((h=d==null?void 0:d.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=c==null?void 0:c.endPTS)!=null?m:0)-((g=c==null?void 0:c.startPTS)!=null?g:0))*1e3)}),this.subscription.add(jt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:c})=>c===l))==null?void 0:d.track},o=Ji(this.hls,lt.Events.LEVEL_SWITCHED).pipe((0,Y.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,Y.filter)(Y.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(jt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if((0,Y.isNullable)(l))return;let d=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,Y.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,Y.observableFrom)(["init"])).pipe((0,Y.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return $(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield De(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Y.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0)}};var zb="X-Playback-Duration",Bu=a=>$(void 0,null,function*(){var r;let e=yield ot(a),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(zb)?parseInt(e.headers.get(zb),10):void 0});var Q=require("@vkontakte/videoplayer-shared");var _u=Ge(mo(),1);var tn=require("@vkontakte/videoplayer-shared");var wA=a=>{let e=null;if(a.QUALITY&&(e=Gt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,tn.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},kA=(a,e)=>{var s,n;let t=a.split(`
|
|
123
|
-
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,_u.default)(l[1].split(",").map(T=>T.split("="))),p=(s=c.QUALITY)!=null?s:`stream-${c.BANDWIDTH}`,h=wA(c),m;c.BANDWIDTH&&(m=parseInt(c.BANDWIDTH,10)/1e3||void 0),!m&&c["AVERAGE-BANDWIDTH"]&&(m=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,S;if(c.RESOLUTION){let[T,E]=c.RESOLUTION.split("x").map(A=>parseInt(A,10));T&&E&&(S={width:T,height:E})}let x=new URL(t[++o],e).toString();h&&i.push({id:p,quality:h,url:x,bandwidth:m,size:S,fps:g})}if(d){let c=(0,_u.default)(d[1].split(",").map(g=>{let S=g.indexOf("=");return[g.substring(0,S),g.substring(S+1)]}).map(([g,S])=>[g,S.replace(/^"|"$/g,"")])),p=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=c.LANGUAGE,m=c.NAME;p&&h&&r.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},RA=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Ou=0,Kb=(r,...s)=>$(void 0,[r,...s],function*(a,e=a,t,i){let o=yield(yield ot(a,i)).text();Ou+=1;try{let{qualityManifests:u,textTracks:l}=kA(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(Ou<=t.manifestRetryMaxCount)return yield RA((0,tn.getExponentialDelay)(Ou-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Kb(a,e,t)}return{qualityManifests:[],textTracks:[]}}),rn=Kb;var we=require("@vkontakte/videoplayer-shared");var an=class{constructor(e,t,i,r){this.subscription=new we.Subscription;this.abortControllers={destroy:new Ie,nextManifest:null};this.numberFormat=new Intl.NumberFormat("ru-RU",{maximumFractionDigits:2,minimumFractionDigits:2,useGrouping:!0});this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new we.ValueSubject(null);this.getCurrentTime$=new we.ValueSubject(null);this.error$=new we.Subject;this.logger=new we.Logger,this.log=this.logger.createComponentLog("LiveTextManager"),this.params={fetchManifestData:i,sourceUrl:r},this.subscription.add(e.pipe((0,we.throttle)(1e3)).subscribe(s=>{this.processLiveTime(s)})).add(this.logger.log$.subscribe(s=>{console.debug(`%c${s.component}`,"background:#258b6d;",s.message)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return $(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=yield this.fetchManifestData();yield this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return $(this,null,function*(){try{let i=yield this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}})}parseTextTracks(e,t){return $(this,null,function*(){for(let i of e){let r=new URL(i.url,t).toString();this.log({message:"[parseTextTracks]"}),this.log({message:r});let n=yield(yield ot(r,{signal:this.abortControllers.destroy.signal})).text();this.log({message:n});let o=this.parsePlaylist(n,r);return this.log({message:JSON.stringify(o,void 0,2)}),{textTrack:i,playlist:o}}})}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
124
|
-
`),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,we.isNonNullable)(e)&&this.currentTextTrackData){this.log({message:`[processLiveTime] ${e.toFixed(2)}, ${new Date(e).toISOString()}`});let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i){this.log({message:`[processLiveTime] out of bounds (before) ! ${i-e}`});return}if(e>r){this.log({message:`[processLiveTime] out of bounds (after) !' ${e-r}`});return}let s=r-e;this.log({message:`Current segments time left: ${this.numberFormat.format(s)} ms`}),s<4e3&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([j(R({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return $(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new Ie;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return $(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:we.ErrorCategory.WTF,thrown:t,message:e})}};var Ia=class{constructor(e){this.subscription=new Q.Subscription;this.videoState=new G("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Q.ValueSubject([]);this.liveOffset=new At;this.manifestStartTime$=new Q.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,Q.assertNever)(t)}};var i;this.params=e,this.video=Re(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Q.VideoQuality.INVARIANT,url:this.params.source.url};let t=(r,s)=>rn(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new an(this.params.output.liveTime$,this.video,t,this.params.source.url):this.textTracksManager=new Ke,t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Q.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Q.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Q.ValueSubject((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Q.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Me(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Xe(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,Q.filterChanged)(),(0,Q.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,Q.isNonNullable)(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ge(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,Q.combine)({startTime:this.manifestStartTime$.pipe((0,Q.filter)(Q.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,Q.map)(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,Q.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,Q.observableFrom)(["init"])).pipe((0,Q.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),$e(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if((0,Q.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[p,h]of[[d,"mq"],[c,"lq"]]){let m=String(parseFloat(p||""));h&&p&&r.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Te(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Bu(n).then(d=>{var c;if(!(0,Q.isNullable)(d))this.maxSeekBackTime$.next(d);else{let p=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();((0,Q.isNullable)(p)||!isFinite(p))&&ot(n).then(h=>h.text()).then(h=>{var g;let m=(g=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:g[1];if(m){let S=new URL(m,n).toString();Bu(S).then(x=>{(0,Q.isNullable)(x)||this.maxSeekBackTime$.next(x)})}}).catch(()=>{})}})}playIfAllowed(){De(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Q.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=Te(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};var J=require("@vkontakte/videoplayer-shared");var Ea=class{constructor(e){this.subscription=new J.Subscription;this.videoState=new G("stopped");this.textTracksManager=new Ke;this.manifests$=new J.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,J.assertNever)(t)}};this.params=e,this.video=Re(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:J.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),rn(Te(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:J.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:J.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Me(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,J.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,i)),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,J.isNonNullable)(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let g=this.manifests$.getValue().find(S=>S.id===m);g&&(this.params.output.currentVideoTrack$.next(g),this.params.output.hostname$.next(ge(g.url)))}let c=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(c!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(c),m.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe((0,J.map)(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!J.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,J.merge)((0,J.fromEvent)(o,"addtrack"),(0,J.fromEvent)(o,"removetrack"),(0,J.fromEvent)(o,"change"),(0,J.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,J.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,J.observableFrom)(["init"])).pipe((0,J.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),$e(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,J.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){De(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:J.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var ae=require("@vkontakte/videoplayer-shared");var xa=class{constructor(e){this.subscription=new ae.Subscription;this.videoState=new G("stopped");this.trackUrls={};this.textTracksManager=new Ke;this.syncPlayback=()=>{var u,l,d;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:c}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((d=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:d.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,ae.assertNever)(e)}};this.params=e,this.video=Re(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:ae.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Me(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,ae.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,i)),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Xe(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,ae.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=(0,ae.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ae.observableFrom)(["init"])).pipe((0,ae.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),$e(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,ae.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,ae.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=fa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ge(t))}playIfAllowed(){De(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ae.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var r,s,n,o;let t,i=e;if(e&&((r=this.params.output.currentVideoTrack$.getValue())==null?void 0:r.quality)!==e){let u=(s=Object.values(this.trackUrls).find(c=>!(0,ae.isInvariantQuality)(c.track.quality)&&(0,ae.isLowerOrEqual)(c.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,d=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&d&&(0,ae.isHigherOrEqual)(d.quality,u.quality)&&(t=u),!t){let c=Object.values(this.trackUrls).filter(h=>!(0,ae.isInvariantQuality)(h.track.quality)&&(0,ae.isHigher)(h.track.quality,e)),p=c.length;p&&(t=c[p-1].track)}t&&(i=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=Wt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};var ue=require("@vkontakte/videoplayer-shared");var Jb=require("@vkontakte/videoplayer-shared");var Xb=["stun:videostun.mycdn.me:80"],$A=1e3,LA=3,Nu=()=>null,sn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Nu;this.externalStopCallback=Nu;this.externalErrorCallback=Nu;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return $(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return $(this,null,function*(){try{let e={iceServers:[{urls:Xb}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return $(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return $(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:Jb.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return $(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return $(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),$A)}normalizeOptions(e={}){let t={stunServerList:Xb,maxRetryNumber:LA,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Pa=class{constructor(e){this.videoState=new G("stopped");this.maxSeekBackTime$=new ue.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,ue.assertNever)(e)}};this.subscription=new ue.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Re(e.container,e.tuning),this.liveStreamClient=new sn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),$e(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ue.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,ue.merge)(this.videoState.stateChangeStarted$.pipe((0,ue.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ue.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let r=Me(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Xe(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Le(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,ue.assertNever)(n.to)}},i)).add((0,ue.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ue.observableFrom)(["init"])).pipe((0,ue.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:ue.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:ue.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){De(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ue.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Aa=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var y=require("@vkontakte/videoplayer-shared");var Mt=require("@vkontakte/videoplayer-shared"),Zb=a=>new Mt.Observable(e=>{let t=new Mt.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Mt.map)(({from:l,to:d})=>`${l}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Mt.map)(({type:l})=>l!==void 0)),n=new Mt.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var et=require("@vkontakte/videoplayer-shared");function eg(){return new(window.AudioContext||window.webkitAudioContext)}var tg=require("@vkontakte/videoplayer-shared");var wa=class wa{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Ie;this.subscriptions=new et.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,et.filter)(s=>!!s.type),(0,et.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){tg.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,et.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,et.filter)(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,et.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return $(this,null,function*(){let{volumeMultiplier:t}=this,i=eg();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:wa.errorId,category:et.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${wa.errorId} exception`,thrown:e})}};wa.errorId="VolumeMultiplierManager";var Zi=wa;var MA={chunkDuration:5e3,maxParallelRequests:5},ka=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,soundProhibitedEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,loadedMetadataEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject(""),getCurrentTime$:new y.ValueSubject(null)};this.subscription=new y.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Gm([...Wm(this.params.tuning),...Qm(this.params.tuning)],this.params.tuning).filter(l=>(0,y.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new Aa(s);let n=[...mu(!0),...mu(!1)];this.chromecastFormatsIterator=new Aa(n.filter(l=>(0,y.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Zi.isSupported()&&(this.volumeMultiplierManager=new Zi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,y.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,y.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,s=this.providerOutput,n={container:i,source:null,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,y.assertNonNullable)(o),new va(j(R({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new ya(j(R({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),Qi||!this.params.tuning.useHlsJs?new Ea(j(R({},n),{source:o})):new Ta(j(R({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ia(j(R({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new xa(j(R({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new km(j(R({},n),{source:o,config:j(R({},MA),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Pa({container:i,source:o,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,y.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,y.assertNonNullable)(o),new Dr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,y.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return j(R({},e),{url:i(e.url)})}return(0,ig.default)(Object.entries(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,i=0;return e.add((0,y.merge)(this.providerOutput.error$.pipe((0,y.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),Zb({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(r=>({id:`ProviderHangup:${r}`,category:y.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,y.filter)(({to:s})=>s==="playing"),(0,y.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===y.ErrorCategory.NETWORK,u=r.category===y.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n=j(R({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d}),d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var F=require("@vkontakte/videoplayer-shared");var DA=5e3,rg="one_video_throughput",ag="one_video_rtt",Dt=window.navigator.connection,sg=()=>{let a=Dt==null?void 0:Dt.downlink;if((0,F.isNonNullable)(a)&&a!==10)return a*1e3},ng=()=>{let a=Dt==null?void 0:Dt.rtt;if((0,F.isNonNullable)(a)&&a!==3e3)return a},og=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Fu=class a{constructor(e){this.subscription=new F.Subscription;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(rg)||(e.useBrowserEstimation?sg():void 0)||DA,i=(s=(r=a.load(ag))!=null?r:e.useBrowserEstimation?ng():void 0)!=null?s:0;if(this.throughput$=new F.ValueSubject(t),this.rtt$=new F.ValueSubject(i),this.rttAdjustedThroughput$=new F.ValueSubject(og(t,i,e.rttPenaltyRequestSize)),this.throughput=mi.getSmoothedValue(t,-1,e),this.rtt=mi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=sg();u&&this.throughput.next(u);let l=ng();(0,F.isNonNullable)(l)&&this.rtt.next(l)};Dt&&"onchange"in Dt&&this.subscription.add((0,F.fromEvent)(Dt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{F.safeStorage.set(rg,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{F.safeStorage.set(ag,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,F.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,F.map)(({throughput:n,rtt:o})=>og(n,o,e.rttPenaltyRequestSize)),(0,F.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,F.now)(),r=new F.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,F.fromEvent)(e,"progress").pipe((0,F.once)()).subscribe(s=>{t=s.loaded,i=(0,F.now)()}));break;case 1:case 0:r.add((0,F.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,F.now)()}));break}r.add((0,F.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,F.now)(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=(0,F.now)(),n=0,o=(0,F.now)(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=p=>$(this,[p],function*({done:d,value:c}){if(d)!t&&this.addRawSpeed(r,(0,F.now)()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=(0,F.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let g=o-s;g&&this.addRawSpeed(n,g,1,t),n=c.byteLength,s=(0,F.now)()}else n+=c.byteLength;o=(0,F.now)()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,F.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,F.now)()-o,this.concurrentDownloads.size),n=0,o=(0,F.now)());yield i==null?void 0:i.read().then(l,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=F.safeStorage.get(e);if((0,F.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},ug=Fu;var Ra=require("@vkontakte/videoplayer-shared");var lg={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Ra.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ra.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,accumulationBufferStallSize:{shortVideoDuration:2*6e4,shortVideoBufferStallSize:0,longVideoBufferStallSize:0},qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1},cg=a=>{var e;return j(R({},(0,Ra.fillWithDefault)(a,lg)),{configName:[...(e=a.configName)!=null?e:[],...lg.configName]})};var f=require("@vkontakte/videoplayer-shared");var Ct=require("@vkontakte/videoplayer-shared"),Uu=({seekState:a,position$:e})=>(0,Ct.merge)(a.stateChangeEnded$.pipe((0,Ct.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,Ct.filter)(Ct.isNonNullable)),e.pipe((0,Ct.filter)(()=>a.getState().state==="none")));var dg=require("@vkontakte/videoplayer-shared"),pg=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,dg.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var nn=require("@vkontakte/videoplayer-shared"),hg=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,nn.filter)(r=>r.length>0),(0,nn.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var $a=class{constructor(e={configName:[]},t=f.Tracer.createRootTracer(!1)){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new G("stopped"),seekState:new G({state:"none"}),volume:new G({volume:1,muted:!1}),videoTrack:new G(void 0),videoStream:new G(void 0),audioStream:new G(void 0),autoVideoTrackSwitching:new G(!0),autoVideoTrackLimits:new G({}),isLooped:new G(!1),isLowLatency:new G(!1),playbackRate:new G(1),externalTextTracks:new G([]),internalTextTracks:new G([]),currentTextTrack:new G(void 0),textTrackCuesSettings:new G({}),cameraOrientation:new G({x:0,y:0})};this.info={playbackState$:new f.ValueSubject("stopped"),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:Sm,getCurrentTime$:new f.ValueSubject(null)};if(this.initLogs(),this.tuning=cg(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Wa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ug(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let g=typeof m;return["number","string","boolean"].includes(g)?m:m===null?null:`<${g}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:f.ErrorCategory.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var s,n,o;this.config=e;let r=e,{container:t}=r,i=El(r,["container"]);return this.tracer.log("initVideo",(0,f.flattenObject)(i)),this.domContainer=pg(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new ka({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Nr()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;return e>=i&&!r&&(s=i-.1),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var i;(0,f.assertNonNullable)(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",(0,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>R({type:"external"},t))),this}selectTextTrack(e){var t;return hg(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",R({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState(j(R({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe((0,f.map)(n=>n.map(({quality:o})=>o).sort((o,u)=>(0,f.isInvariantQuality)(o)?1:(0,f.isInvariantQuality)(u)?-1:(0,f.isHigher)(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,f.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,f.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Uu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(Uu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe((0,f.once)(),(0,f.map)(n=>n!=null?n:(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>i.next(!1)));let r=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,f.filterChanged)());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,f.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r,s;let t;this.wasSetStartedQuality=!0;let i=(s=this.explicitInitialQuality)!=null?s:(r=this.desiredState.videoTrack.getState())==null?void 0:r.quality;i&&(t=e.find(({quality:n})=>n===i),t||this.setAutoQuality(!0)),t||(t=Wt(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),gm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>bm(i)),this.providerContainer.current$.subscribe(({type:i})=>Cr("provider",i)),e.duration$.subscribe(i=>Cr("duration",i)),e.availableVideoTracks$.pipe((0,f.filter)(i=>!!i.length),(0,f.once)()).subscribe(i=>Cr("tracks",i)),this.events.fatalError$.subscribe(new Ae("fatalError")),this.events.managedError$.subscribe(new Ae("managedError")),e.position$.subscribe(new Ae("position")),e.currentVideoTrack$.pipe((0,f.map)(i=>i==null?void 0:i.quality)).subscribe(new Ae("quality")),this.info.currentBuffer$.subscribe(new Ae("buffer")),e.isBuffering$.subscribe(new Ae("isBuffering"))].forEach(i=>this.subscription.add(i)),Cr("codecs",jm())}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,f.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,f.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(i=>i.end>0),(0,f.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=()=>$(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(r)})})});this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var vt=require("@vkontakte/videoplayer-shared"),CA=`@vkontakte/videoplayer-core@${fn}`;
|
|
122
|
+
`;var Zs=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Js(this.params.fov,this.params.orientation),this.cameraRotationManager=new Xs(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Hb,this.gl.VERTEX_SHADER),i=this.createShader(jb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,p=t+r;return[s,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Se=require("@vkontakte/videoplayer-shared"),Cu=class{constructor(){this.isSeeked$=new Se.ValueSubject(!1);this.isBuffering$=new Se.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Se.Subscription}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add((0,Se.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,Se.filter)(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,Se.combine)({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:i})=>{if((0,Se.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:r,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),d=this.videoLastDataObtainedTimestamp$.getValue(),c=(0,Se.now)(),p=n&&this.currentStallsCount>=n,h=r&&!i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=r+u&&t>=r,m=s&&c-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&c-d>=s+u&&t>=s;(p||h||m)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Se.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,Se.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Gb=Cu;var mi=class{constructor(e){this.subscription=new _.Subscription;this.videoState=new j("stopped");this.elementSize$=new _.ValueSubject(void 0);this.textTracksManager=new ze;this.droppedFramesManager=new Ms;this.stallsManager=new Gb;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Dr;this.audioTrackSwitchHistory=new Dr;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(r.position-l,r.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,_.assertNever)(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Zs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=ke(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(be(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Ks({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Le(this.video),r=this.constructor.name,s=o=>{e.error$.next({id:r,category:_.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){var d;let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,_.filter)(c=>!!c.length),(0,_.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,_.map)(c=>c.to.state!=="none"),(0,_.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,_.filterChanged)()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,_.filter)(_.isNonNullable),(0,_.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,_.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ht(this.video,t.isLooped,r)),this.subscription.add($e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ye(this.video,t.playbackRate,i.playbackRateState$,r)),s((0,_.observeElementSize)(this.video),this.elementSize$),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams();if((0,_.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of p.audio){m.push(ku(g));let S=[];for(let x of g.representations){let T=Bb(x);S.push(T),this.audioTracksMap.set(T,{stream:g,representation:x})}this.audioStreamsMap.set(g,S)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of p.video){h.push(Ru(m));let g=[];for(let S of m.representations){let x=Db(S);x&&(g.push(x),this.videoTracksMap.set(x,{stream:m,representation:S}))}this.videoStreamsMap.set(m,g)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let m of p.text)for(let g of m.representations){let S=Vb(m,g);this.textTracksMap.set(S,{stream:m,representation:g})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=c=>e.error$.next({id:"RepresentationSwitch",category:_.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,_.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,_.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,g]=h,S=[...this.videoTracksMap.keys()].find(T=>{var I;return((I=this.videoTracksMap.get(T))==null?void 0:I.representation.id)===m.id});(0,_.isNonNullable)(S)&&(this.stallsManager.lastVideoTrackSelected=S);let x=this.params.desiredState.autoVideoTrackLimits.getTransition();if(x&&this.params.output.autoVideoTrackLimits$.next(x.to),c==="manifest_ready")this.player.initRepresentations(m.id,g==null?void 0:g.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",m.id).catch(o),g){let T=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",g.id,T).catch(o)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,_.filterChanged)()).subscribe(c=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=p,g=this.params.desiredState.videoStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.videoStream.setState(g.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Ru(m))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,_.filterChanged)()).subscribe(c=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,g=this.params.desiredState.audioStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.audioStream.setState(g.to),e.currentAudioStream$.next(ku(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var p,h;if(c!=null&&c.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),(d=this.textTracksManager)==null||d.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe((0,_.map)(({to:c})=>c==="ready"),(0,_.filterChanged)());this.subscription.add((0,_.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,_.merge)(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,_.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,_.observableFrom)(["init"])).pipe((0,_.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var V,z,se,U,Q,ee,N,ie,H,ne,R,P,J;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(V=e.videoTrack.getState())==null?void 0:V.id,n=[...this.videoTracksMap.keys()].find(({id:W})=>W===r),o=t.currentVideoTrack$.getValue(),u=((U=(se=e.videoStream.getState())!=null?se:n&&((z=this.videoTracksMap.get(n))==null?void 0:z.stream))!=null?U:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:W})=>W===u.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=mt(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(c/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=(Q=e.audioStream.getState())!=null?Q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(ee=[...this.audioStreamsMap.keys()].find(({id:W})=>W===(m==null?void 0:m.id)))!=null?ee:this.audioStreamsMap.keys().next().value,S=0;if(g){if(n&&!i){let W=$s(n,d,(N=this.audioStreamsMap.get(g))!=null?N:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,(ie=W==null?void 0:W.bitrate)!=null?ie:-1/0)}if(o){let W=$s(o,d,(H=this.audioStreamsMap.get(g))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,(ne=W==null?void 0:W.bitrate)!=null?ne:-1/0)}}let x=Wt(d,{container:this.elementSize$.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),T=i?x!=null?x:n:n!=null?n:x,I=g&&Tm(T,d,(R=this.audioStreamsMap.get(g))!=null?R:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=(P=this.videoTracksMap.get(T))==null?void 0:P.representation,w=I&&((J=this.audioTracksMap.get(I))==null?void 0:J.representation);if(A&&w)return[A,w];if(A&&!w&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.ErrorCategory.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Re(this.video),this.tracer.end()}};var Sa=class extends mi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Jt=require("@vkontakte/videoplayer-shared");var va=class extends mi{constructor(e){super(e),this.liveOffset=new xt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:i,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(i.isLowLatency.stateChangeEnded$.pipe((0,Jt.map)(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,Jt.combine)({interval:(0,Jt.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add((0,Jt.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Jt.map)(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Ob(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,r)})}};var Qb=je(ws(),1);var Y=require("@vkontakte/videoplayer-shared");var ot={};var Xi=(a,e)=>new Y.Observable(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),ya=class{constructor(e){this.subscription=new Y.Subscription;this.videoState=new j("initializing");this.textTracksManager=new ze;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,Y.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,Y.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,Y.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,Y.assertNever)(e)}break;default:(0,Y.assertNever)(t)}};this.video=ke(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(be(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),Re(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Y.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Qb.default)(import("hls.js").then(r=>{e||(ot.Hls=r.default,ot.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){(0,Y.assertNonNullable)(ot.Hls,"hls.js not loaded"),this.hls=new ot.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,Y.assertNonNullable)(ot.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:Y.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=Le(this.video),s=(l,d)=>this.subscription.add(l.subscribe(d,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(ht(this.video,e.isLooped,i)),this.subscription.add($e(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ye(this.video,e.playbackRate,r.playbackRateState$,i)),s(Ke(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,Y.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Xi(this.hls,ot.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Y.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)==null?void 0:d.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(Xi(this.hls,ot.Events.MANIFEST_PARSED).pipe((0,Y.map)(({levels:l})=>l.reduce((d,c)=>{var T,I;let p=c.name||c.height.toString(10),{width:h,height:m}=c,g=(I=Gt((T=c.attrs.QUALITY)!=null?T:""))!=null?I:(0,Y.videoSizeToQuality)({width:h,height:m});if(!g)return d;let S=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,x={id:p.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:h,height:m},fps:S};return this.trackLevels.set(p,{track:x,level:c}),d.push(x),d},[]))),t.availableVideoTracks$),s(Xi(this.hls,ot.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let p=c.name,h=c.attrs.URI||"",m=c.lang;d.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(Xi(this.hls,ot.Events.LEVEL_LOADING).pipe((0,Y.map)(({url:l})=>be(l))),t.hostname$),s(Xi(this.hls,ot.Events.FRAG_CHANGED),l=>{var p,h,m,g;let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=d==null?void 0:d.endPTS)!=null?p:0)-((h=d==null?void 0:d.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=c==null?void 0:c.endPTS)!=null?m:0)-((g=c==null?void 0:c.startPTS)!=null?g:0))*1e3)}),this.subscription.add(jt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:c})=>c===l))==null?void 0:d.track},o=Xi(this.hls,ot.Events.LEVEL_SWITCHED).pipe((0,Y.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,Y.filter)(Y.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(jt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if((0,Y.isNullable)(l))return;let d=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,Y.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,Y.observableFrom)(["init"])).pipe((0,Y.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return B(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Y.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0)}};var Wb="X-Playback-Duration",Du=a=>B(void 0,null,function*(){var r;let e=yield wt(a),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Wb)?parseInt(e.headers.get(Wb),10):void 0});var G=require("@vkontakte/videoplayer-shared");var Vu=je(ho(),1);var en=require("@vkontakte/videoplayer-shared");var PA=a=>{let e=null;if(a.QUALITY&&(e=Gt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,en.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},AA=(a,e)=>{var s,n;let t=a.split(`
|
|
123
|
+
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,Vu.default)(l[1].split(",").map(T=>T.split("="))),p=(s=c.QUALITY)!=null?s:`stream-${c.BANDWIDTH}`,h=PA(c),m;c.BANDWIDTH&&(m=parseInt(c.BANDWIDTH,10)/1e3||void 0),!m&&c["AVERAGE-BANDWIDTH"]&&(m=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,S;if(c.RESOLUTION){let[T,I]=c.RESOLUTION.split("x").map(A=>parseInt(A,10));T&&I&&(S={width:T,height:I})}let x=new URL(t[++o],e).toString();h&&i.push({id:p,quality:h,url:x,bandwidth:m,size:S,fps:g})}if(d){let c=(0,Vu.default)(d[1].split(",").map(g=>g.split("=")).map(([g,S])=>[g,S.replace(/^"|"$/g,"")])),p=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=c.LANGUAGE,m=c.NAME;p&&h&&r.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},wA=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Bu=0,Yb=(i,...r)=>B(void 0,[i,...r],function*(a,e=a,t){let n=yield(yield wt(a)).text();Bu+=1;try{let{qualityManifests:o,textTracks:u}=AA(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(Bu<=t.manifestRetryMaxCount)return yield wA((0,en.getExponentialDelay)(Bu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Yb(a,e,t)}return{qualityManifests:[],textTracks:[]}}),tn=Yb;var Ta=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new j("stopped");this.textTracksManager=new ze;this.manifests$=new G.ValueSubject([]);this.liveOffset=new xt;this.manifestStartTime$=new G.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,G.assertNever)(t)}};var t;this.params=e,this.video=ke(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:G.VideoQuality.INVARIANT,url:this.params.source.url},tn(Ie(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:i})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:G.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:G.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(be(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new G.ValueSubject((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:G.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Le(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add($e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ye(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe((0,G.filterChanged)(),(0,G.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,G.isNonNullable)(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(be(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,G.combine)({startTime:this.manifestStartTime$.pipe((0,G.filter)(G.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,G.map)(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,G.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Re(this.video)}prepare(){var o,u;let e=this.selectManifest();if((0,G.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:l,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[c,p]of[[l,"mq"],[d,"lq"]]){let h=String(parseFloat(c||""));p&&c&&r.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ie(r.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Du(n).then(l=>{var d;if(!(0,G.isNullable)(l))this.maxSeekBackTime$.next(l);else{let c=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();if((0,G.isNullable)(c)||!isFinite(c))try{wt(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let g=new URL(h,n).toString();Du(g).then(S=>{(0,G.isNullable)(S)||this.maxSeekBackTime$.next(S)})}})}catch(p){}}})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}};var Z=require("@vkontakte/videoplayer-shared");var Ia=class{constructor(e){this.subscription=new Z.Subscription;this.videoState=new j("stopped");this.textTracksManager=new ze;this.manifests$=new Z.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,Z.assertNever)(t)}};this.params=e,this.video=ke(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Z.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(be(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),tn(Ie(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Z.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Z.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Le(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,Z.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ht(this.video,t.isLooped,i)),this.subscription.add($e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ye(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,Z.isNonNullable)(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let g=this.manifests$.getValue().find(S=>S.id===m);g&&(this.params.output.currentVideoTrack$.next(g),this.params.output.hostname$.next(be(g.url)))}let c=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(c!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(c),m.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe((0,Z.map)(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!Z.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,Z.merge)((0,Z.fromEvent)(o,"addtrack"),(0,Z.fromEvent)(o,"removetrack"),(0,Z.fromEvent)(o,"change"),(0,Z.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,Z.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,Z.observableFrom)(["init"])).pipe((0,Z.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Re(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,Z.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Z.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var ae=require("@vkontakte/videoplayer-shared");var Ea=class{constructor(e){this.subscription=new ae.Subscription;this.videoState=new j("stopped");this.trackUrls={};this.textTracksManager=new ze;this.syncPlayback=()=>{var u,l,d;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:c}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((d=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:d.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,ae.assertNever)(e)}};this.params=e,this.video=ke(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:ae.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Le(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,ae.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ht(this.video,t.isLooped,i)),this.subscription.add($e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ye(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,ae.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=(0,ae.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ae.observableFrom)(["init"])).pipe((0,ae.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Re(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,ae.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,ae.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ha(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(be(t))}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ae.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var r,s,n,o;let t,i=e;if(e&&((r=this.params.output.currentVideoTrack$.getValue())==null?void 0:r.quality)!==e){let u=(s=Object.values(this.trackUrls).find(c=>!(0,ae.isInvariantQuality)(c.track.quality)&&(0,ae.isLowerOrEqual)(c.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,d=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&d&&(0,ae.isHigherOrEqual)(d.quality,u.quality)&&(t=u),!t){let c=Object.values(this.trackUrls).filter(h=>!(0,ae.isInvariantQuality)(h.track.quality)&&(0,ae.isHigher)(h.track.quality,e)),p=c.length;p&&(t=c[p-1].track)}t&&(i=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=Wt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};var ue=require("@vkontakte/videoplayer-shared");var Kb=require("@vkontakte/videoplayer-shared");var zb=["stun:videostun.mycdn.me:80"],kA=1e3,RA=3,Ou=()=>null,rn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Ou;this.externalStopCallback=Ou;this.externalErrorCallback=Ou;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return B(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return B(this,null,function*(){try{let e={iceServers:[{urls:zb}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return B(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return B(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:Kb.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return B(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return B(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),kA)}normalizeOptions(e={}){let t={stunServerList:zb,maxRetryNumber:RA,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var xa=class{constructor(e){this.videoState=new j("stopped");this.maxSeekBackTime$=new ue.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,ue.assertNever)(e)}};this.subscription=new ue.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ke(e.container,e.tuning),this.liveStreamClient=new rn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Re(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ue.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,ue.merge)(this.videoState.stateChangeStarted$.pipe((0,ue.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ue.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let r=Le(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Ke(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add($e(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,ue.assertNever)(n.to)}},i)).add((0,ue.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ue.observableFrom)(["init"])).pipe((0,ue.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(be(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:ue.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:ue.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ue.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Pa=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var y=require("@vkontakte/videoplayer-shared");var Lt=require("@vkontakte/videoplayer-shared"),Jb=a=>new Lt.Observable(e=>{let t=new Lt.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Lt.map)(({from:l,to:d})=>`${l}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Lt.map)(({type:l})=>l!==void 0)),n=new Lt.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Ze=require("@vkontakte/videoplayer-shared");function Xb(){return new(window.AudioContext||window.webkitAudioContext)}var Zb=require("@vkontakte/videoplayer-shared");var Aa=class Aa{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Ne;this.subscriptions=new Ze.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Ze.filter)(s=>!!s.type),(0,Ze.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){Zb.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Ze.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Ze.filter)(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,Ze.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return B(this,null,function*(){let{volumeMultiplier:t}=this,i=Xb();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Aa.errorId,category:Ze.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Aa.errorId} exception`,thrown:e})}};Aa.errorId="VolumeMultiplierManager";var Zi=Aa;var $A={chunkDuration:5e3,maxParallelRequests:5},wa=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,soundProhibitedEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,loadedMetadataEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject("")};this.subscription=new y.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Hm([...Gm(this.params.tuning),...jm(this.params.tuning)],this.params.tuning).filter(l=>(0,y.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new Pa(s);let n=[...hu(!0),...hu(!1)];this.chromecastFormatsIterator=new Pa(n.filter(l=>(0,y.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Zi.isSupported()&&(this.volumeMultiplierManager=new Zi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,y.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,y.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,s=this.providerOutput,n={container:i,source:null,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,y.assertNonNullable)(o),new Sa(K($({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new va(K($({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),Qi||!this.params.tuning.useHlsJs?new Ia(K($({},n),{source:o})):new ya(K($({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ta(K($({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ea(K($({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Am(K($({},n),{source:o,config:K($({},$A),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new xa({container:i,source:o,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,y.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,y.assertNonNullable)(o),new Mr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,y.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return K($({},e),{url:i(e.url)})}return(0,eg.default)(Object.entries(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,i=0;return e.add((0,y.merge)(this.providerOutput.error$.pipe((0,y.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),Jb({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(r=>({id:`ProviderHangup:${r}`,category:y.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,y.filter)(({to:s})=>s==="playing"),(0,y.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===y.ErrorCategory.NETWORK,u=r.category===y.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n=K($({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d}),d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var F=require("@vkontakte/videoplayer-shared");var LA=5e3,tg="one_video_throughput",ig="one_video_rtt",Mt=window.navigator.connection,rg=()=>{let a=Mt==null?void 0:Mt.downlink;if((0,F.isNonNullable)(a)&&a!==10)return a*1e3},ag=()=>{let a=Mt==null?void 0:Mt.rtt;if((0,F.isNonNullable)(a)&&a!==3e3)return a},sg=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},_u=class a{constructor(e){this.subscription=new F.Subscription;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(tg)||(e.useBrowserEstimation?rg():void 0)||LA,i=(s=(r=a.load(ig))!=null?r:e.useBrowserEstimation?ag():void 0)!=null?s:0;if(this.throughput$=new F.ValueSubject(t),this.rtt$=new F.ValueSubject(i),this.rttAdjustedThroughput$=new F.ValueSubject(sg(t,i,e.rttPenaltyRequestSize)),this.throughput=fi.getSmoothedValue(t,-1,e),this.rtt=fi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=rg();u&&this.throughput.next(u);let l=ag();(0,F.isNonNullable)(l)&&this.rtt.next(l)};Mt&&"onchange"in Mt&&this.subscription.add((0,F.fromEvent)(Mt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{F.safeStorage.set(tg,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{F.safeStorage.set(ig,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,F.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,F.map)(({throughput:n,rtt:o})=>sg(n,o,e.rttPenaltyRequestSize)),(0,F.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,F.now)(),r=new F.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,F.fromEvent)(e,"progress").pipe((0,F.once)()).subscribe(s=>{t=s.loaded,i=(0,F.now)()}));break;case 1:case 0:r.add((0,F.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,F.now)()}));break}r.add((0,F.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,F.now)(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=(0,F.now)(),n=0,o=(0,F.now)(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=p=>B(this,[p],function*({done:d,value:c}){if(d)!t&&this.addRawSpeed(r,(0,F.now)()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=(0,F.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let g=o-s;g&&this.addRawSpeed(n,g,1,t),n=c.byteLength,s=(0,F.now)()}else n+=c.byteLength;o=(0,F.now)()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,F.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,F.now)()-o,this.concurrentDownloads.size),n=0,o=(0,F.now)());yield i==null?void 0:i.read().then(l,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=F.safeStorage.get(e);if((0,F.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},ng=_u;var ka=require("@vkontakte/videoplayer-shared");var og={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:ka.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ka.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,accumulationBufferStallSize:{shortVideoDuration:2*6e4,shortVideoBufferStallSize:0,longVideoBufferStallSize:0},qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1},ug=a=>{var e;return K($({},(0,ka.fillWithDefault)(a,og)),{configName:[...(e=a.configName)!=null?e:[],...og.configName]})};var f=require("@vkontakte/videoplayer-shared");var Ct=require("@vkontakte/videoplayer-shared"),Nu=({seekState:a,position$:e})=>(0,Ct.merge)(a.stateChangeEnded$.pipe((0,Ct.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,Ct.filter)(Ct.isNonNullable)),e.pipe((0,Ct.filter)(()=>a.getState().state==="none")));var lg=require("@vkontakte/videoplayer-shared"),cg=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,lg.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var an=require("@vkontakte/videoplayer-shared"),dg=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,an.filter)(r=>r.length>0),(0,an.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var Ra=class{constructor(e={configName:[]},t=f.Tracer.createRootTracer(!1)){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new j("stopped"),seekState:new j({state:"none"}),volume:new j({volume:1,muted:!1}),videoTrack:new j(void 0),videoStream:new j(void 0),audioStream:new j(void 0),autoVideoTrackSwitching:new j(!0),autoVideoTrackLimits:new j({}),isLooped:new j(!1),isLowLatency:new j(!1),playbackRate:new j(1),externalTextTracks:new j([]),internalTextTracks:new j([]),currentTextTrack:new j(void 0),textTrackCuesSettings:new j({}),cameraOrientation:new j({x:0,y:0})};this.info={playbackState$:new f.ValueSubject("stopped"),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:bm};if(this.initLogs(),this.tuning=ug(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Qa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ng(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let g=typeof m;return["number","string","boolean"].includes(g)?m:m===null?null:`<${g}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:f.ErrorCategory.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var s,n,o;this.config=e;let r=e,{container:t}=r,i=Tl(r,["container"]);return this.tracer.log("initVideo",(0,f.flattenObject)(i)),this.domContainer=cg(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new wa({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!_r()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;return e>=i&&!r&&(s=i-.1),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var i;(0,f.assertNonNullable)(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",(0,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>$({type:"external"},t))),this}selectTextTrack(e){var t;return dg(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",$({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState(K($({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe((0,f.map)(n=>n.map(({quality:o})=>o).sort((o,u)=>(0,f.isInvariantQuality)(o)?1:(0,f.isInvariantQuality)(u)?-1:(0,f.isHigher)(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,f.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,f.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Nu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(Nu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe((0,f.once)(),(0,f.map)(n=>n!=null?n:(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>i.next(!1)));let r=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,f.filterChanged)());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,f.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r,s;let t;this.wasSetStartedQuality=!0;let i=(s=this.explicitInitialQuality)!=null?s:(r=this.desiredState.videoTrack.getState())==null?void 0:r.quality;i&&(t=e.find(({quality:n})=>n===i),t||this.setAutoQuality(!0)),t||(t=Wt(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),mm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>fm(i)),this.providerContainer.current$.subscribe(({type:i})=>Cr("provider",i)),e.duration$.subscribe(i=>Cr("duration",i)),e.availableVideoTracks$.pipe((0,f.filter)(i=>!!i.length),(0,f.once)()).subscribe(i=>Cr("tracks",i)),this.events.fatalError$.subscribe(new Ae("fatalError")),this.events.managedError$.subscribe(new Ae("managedError")),e.position$.subscribe(new Ae("position")),e.currentVideoTrack$.pipe((0,f.map)(i=>i==null?void 0:i.quality)).subscribe(new Ae("quality")),this.info.currentBuffer$.subscribe(new Ae("buffer")),e.isBuffering$.subscribe(new Ae("isBuffering"))].forEach(i=>this.subscription.add(i)),Cr("codecs",Um())}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,f.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,f.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(i=>i.end>0),(0,f.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=()=>B(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(r)})})});this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var gt=require("@vkontakte/videoplayer-shared"),MA=`@vkontakte/videoplayer-core@${pn}`;
|