@vkontakte/videoplayer-core 2.0.151-dev.6dd94264.0 → 2.0.151-dev.96546ef5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esnext.cjs CHANGED
@@ -1,10 +1,10 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.151-dev.6dd94264.0
3
- * Mon, 02 Feb 2026 12:05:46 GMT
2
+ * @vkontakte/videoplayer-core v2.0.151-dev.96546ef5.0
3
+ * Mon, 02 Feb 2026 13:51:44 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-151/doc/
5
5
  */
6
- "use strict";var iy=Object.create;var ks=Object.defineProperty;var ry=Object.getOwnPropertyDescriptor;var ay=Object.getOwnPropertyNames;var sy=Object.getPrototypeOf,ny=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),oy=(a,e)=>{for(var t in e)ks(a,t,{get:e[t],enumerable:!0})},xl=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ay(e))!ny.call(a,r)&&r!==t&&ks(a,r,{get:()=>e[r],enumerable:!(i=ry(e,r))||i.enumerable});return a};var j=(a,e,t)=>(t=a!=null?iy(sy(a)):{},xl(e||!a||!a.__esModule?ks(t,"default",{value:a,enumerable:!0}):t,a)),uy=a=>xl(ks({},"__esModule",{value:!0}),a);var Te=b((xo,Pl)=>{"use strict";var qr=function(a){return a&&a.Math===Math&&a};Pl.exports=qr(typeof globalThis=="object"&&globalThis)||qr(typeof window=="object"&&window)||qr(typeof self=="object"&&self)||qr(typeof global=="object"&&global)||qr(typeof xo=="object"&&xo)||function(){return this}()||Function("return this")()});var Ae=b((i$,kl)=>{"use strict";kl.exports=function(a){try{return!!a()}catch{return!0}}});var Ur=b((r$,Al)=>{"use strict";var cy=Ae();Al.exports=!cy(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Po=b((a$,Cl)=>{"use strict";var ly=Ur(),$l=Function.prototype,Rl=$l.apply,Ml=$l.call;Cl.exports=typeof Reflect=="object"&&Reflect.apply||(ly?Ml.bind(Rl):function(){return Ml.apply(Rl,arguments)})});var Re=b((s$,Bl)=>{"use strict";var Ll=Ur(),Dl=Function.prototype,ko=Dl.call,dy=Ll&&Dl.bind.bind(ko,ko);Bl.exports=Ll?dy:function(a){return function(){return ko.apply(a,arguments)}}});var xi=b((n$,_l)=>{"use strict";var Vl=Re(),py=Vl({}.toString),hy=Vl("".slice);_l.exports=function(a){return hy(py(a),8,-1)}});var Ao=b((o$,Ol)=>{"use strict";var my=xi(),fy=Re();Ol.exports=function(a){if(my(a)==="Function")return fy(a)}});var Ie=b((u$,Nl)=>{"use strict";var Ro=typeof document=="object"&&document.all;Nl.exports=typeof Ro>"u"&&Ro!==void 0?function(a){return typeof a=="function"||a===Ro}:function(a){return typeof a=="function"}});var rt=b((c$,Fl)=>{"use strict";var by=Ae();Fl.exports=!by(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var at=b((l$,ql)=>{"use strict";var gy=Ur(),Ms=Function.prototype.call;ql.exports=gy?Ms.bind(Ms):function(){return Ms.apply(Ms,arguments)}});var Mo=b(jl=>{"use strict";var Ul={}.propertyIsEnumerable,Hl=Object.getOwnPropertyDescriptor,vy=Hl&&!Ul.call({1:2},1);jl.f=vy?function(e){var t=Hl(this,e);return!!t&&t.enumerable}:Ul});var Hr=b((p$,Ql)=>{"use strict";Ql.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Wl=b((h$,zl)=>{"use strict";var Sy=Re(),yy=Ae(),Ty=xi(),$o=Object,Iy=Sy("".split);zl.exports=yy(function(){return!$o("z").propertyIsEnumerable(0)})?function(a){return Ty(a)==="String"?Iy(a,""):$o(a)}:$o});var jr=b((m$,Gl)=>{"use strict";Gl.exports=function(a){return a==null}});var ri=b((f$,Yl)=>{"use strict";var Ey=jr(),wy=TypeError;Yl.exports=function(a){if(Ey(a))throw new wy("Can't call method on "+a);return a}});var Pi=b((b$,Kl)=>{"use strict";var xy=Wl(),Py=ri();Kl.exports=function(a){return xy(Py(a))}});var We=b((g$,Xl)=>{"use strict";var ky=Ie();Xl.exports=function(a){return typeof a=="object"?a!==null:ky(a)}});var ki=b((v$,Jl)=>{"use strict";Jl.exports={}});var Ut=b((S$,ed)=>{"use strict";var Co=ki(),Lo=Te(),Ay=Ie(),Zl=function(a){return Ay(a)?a:void 0};ed.exports=function(a,e){return arguments.length<2?Zl(Co[a])||Zl(Lo[a]):Co[a]&&Co[a][e]||Lo[a]&&Lo[a][e]}});var Qr=b((y$,td)=>{"use strict";var Ry=Re();td.exports=Ry({}.isPrototypeOf)});var Ai=b((T$,ad)=>{"use strict";var My=Te(),id=My.navigator,rd=id&&id.userAgent;ad.exports=rd?String(rd):""});var Bo=b((I$,ld)=>{"use strict";var cd=Te(),Do=Ai(),sd=cd.process,nd=cd.Deno,od=sd&&sd.versions||nd&&nd.version,ud=od&&od.v8,It,$s;ud&&(It=ud.split("."),$s=It[0]>0&&It[0]<4?1:+(It[0]+It[1]));!$s&&Do&&(It=Do.match(/Edge\/(\d+)/),(!It||It[1]>=74)&&(It=Do.match(/Chrome\/(\d+)/),It&&($s=+It[1])));ld.exports=$s});var Vo=b((E$,pd)=>{"use strict";var dd=Bo(),$y=Ae(),Cy=Te(),Ly=Cy.String;pd.exports=!!Object.getOwnPropertySymbols&&!$y(function(){var a=Symbol("symbol detection");return!Ly(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&dd&&dd<41})});var _o=b((w$,hd)=>{"use strict";var Dy=Vo();hd.exports=Dy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Oo=b((x$,md)=>{"use strict";var By=Ut(),Vy=Ie(),_y=Qr(),Oy=_o(),Ny=Object;md.exports=Oy?function(a){return typeof a=="symbol"}:function(a){var e=By("Symbol");return Vy(e)&&_y(e.prototype,Ny(a))}});var zr=b((P$,fd)=>{"use strict";var Fy=String;fd.exports=function(a){try{return Fy(a)}catch{return"Object"}}});var Ct=b((k$,bd)=>{"use strict";var qy=Ie(),Uy=zr(),Hy=TypeError;bd.exports=function(a){if(qy(a))return a;throw new Hy(Uy(a)+" is not a function")}});var Wr=b((A$,gd)=>{"use strict";var jy=Ct(),Qy=jr();gd.exports=function(a,e){var t=a[e];return Qy(t)?void 0:jy(t)}});var Sd=b((R$,vd)=>{"use strict";var No=at(),Fo=Ie(),qo=We(),zy=TypeError;vd.exports=function(a,e){var t,i;if(e==="string"&&Fo(t=a.toString)&&!qo(i=No(t,a))||Fo(t=a.valueOf)&&!qo(i=No(t,a))||e!=="string"&&Fo(t=a.toString)&&!qo(i=No(t,a)))return i;throw new zy("Can't convert object to primitive value")}});var Et=b((M$,yd)=>{"use strict";yd.exports=!0});var Ed=b(($$,Id)=>{"use strict";var Td=Te(),Wy=Object.defineProperty;Id.exports=function(a,e){try{Wy(Td,a,{value:e,configurable:!0,writable:!0})}catch{Td[a]=e}return e}});var Gr=b((C$,Pd)=>{"use strict";var Gy=Et(),Yy=Te(),Ky=Ed(),wd="__core-js_shared__",xd=Pd.exports=Yy[wd]||Ky(wd,{});(xd.versions||(xd.versions=[])).push({version:"3.43.0",mode:Gy?"pure":"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Uo=b((L$,Ad)=>{"use strict";var kd=Gr();Ad.exports=function(a,e){return kd[a]||(kd[a]=e||{})}});var ir=b((D$,Rd)=>{"use strict";var Xy=ri(),Jy=Object;Rd.exports=function(a){return Jy(Xy(a))}});var wt=b((B$,Md)=>{"use strict";var Zy=Re(),eT=ir(),tT=Zy({}.hasOwnProperty);Md.exports=Object.hasOwn||function(e,t){return tT(eT(e),t)}});var Ho=b((V$,$d)=>{"use strict";var iT=Re(),rT=0,aT=Math.random(),sT=iT(1.1.toString);$d.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+sT(++rT+aT,36)}});var _e=b((_$,Ld)=>{"use strict";var nT=Te(),oT=Uo(),Cd=wt(),uT=Ho(),cT=Vo(),lT=_o(),rr=nT.Symbol,jo=oT("wks"),dT=lT?rr.for||rr:rr&&rr.withoutSetter||uT;Ld.exports=function(a){return Cd(jo,a)||(jo[a]=cT&&Cd(rr,a)?rr[a]:dT("Symbol."+a)),jo[a]}});var _d=b((O$,Vd)=>{"use strict";var pT=at(),Dd=We(),Bd=Oo(),hT=Wr(),mT=Sd(),fT=_e(),bT=TypeError,gT=fT("toPrimitive");Vd.exports=function(a,e){if(!Dd(a)||Bd(a))return a;var t=hT(a,gT),i;if(t){if(e===void 0&&(e="default"),i=pT(t,a,e),!Dd(i)||Bd(i))return i;throw new bT("Can't convert object to primitive value")}return e===void 0&&(e="number"),mT(a,e)}});var Qo=b((N$,Od)=>{"use strict";var vT=_d(),ST=Oo();Od.exports=function(a){var e=vT(a,"string");return ST(e)?e:e+""}});var Cs=b((F$,Fd)=>{"use strict";var yT=Te(),Nd=We(),zo=yT.document,TT=Nd(zo)&&Nd(zo.createElement);Fd.exports=function(a){return TT?zo.createElement(a):{}}});var Wo=b((q$,qd)=>{"use strict";var IT=rt(),ET=Ae(),wT=Cs();qd.exports=!IT&&!ET(function(){return Object.defineProperty(wT("div"),"a",{get:function(){return 7}}).a!==7})});var jd=b(Hd=>{"use strict";var xT=rt(),PT=at(),kT=Mo(),AT=Hr(),RT=Pi(),MT=Qo(),$T=wt(),CT=Wo(),Ud=Object.getOwnPropertyDescriptor;Hd.f=xT?Ud:function(e,t){if(e=RT(e),t=MT(t),CT)try{return Ud(e,t)}catch{}if($T(e,t))return AT(!PT(kT.f,e,t),e[t])}});var Go=b((H$,Qd)=>{"use strict";var LT=Ae(),DT=Ie(),BT=/#|\.prototype\./,Yr=function(a,e){var t=_T[VT(a)];return t===NT?!0:t===OT?!1:DT(e)?LT(e):!!e},VT=Yr.normalize=function(a){return String(a).replace(BT,".").toLowerCase()},_T=Yr.data={},OT=Yr.NATIVE="N",NT=Yr.POLYFILL="P";Qd.exports=Yr});var ar=b((j$,Wd)=>{"use strict";var zd=Ao(),FT=Ct(),qT=Ur(),UT=zd(zd.bind);Wd.exports=function(a,e){return FT(a),e===void 0?a:qT?UT(a,e):function(){return a.apply(e,arguments)}}});var Yo=b((Q$,Gd)=>{"use strict";var HT=rt(),jT=Ae();Gd.exports=HT&&jT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Lt=b((z$,Yd)=>{"use strict";var QT=We(),zT=String,WT=TypeError;Yd.exports=function(a){if(QT(a))return a;throw new WT(zT(a)+" is not an object")}});var Ri=b(Xd=>{"use strict";var GT=rt(),YT=Wo(),KT=Yo(),Ls=Lt(),Kd=Qo(),XT=TypeError,Ko=Object.defineProperty,JT=Object.getOwnPropertyDescriptor,Xo="enumerable",Jo="configurable",Zo="writable";Xd.f=GT?KT?function(e,t,i){if(Ls(e),t=Kd(t),Ls(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Zo in i&&!i[Zo]){var r=JT(e,t);r&&r[Zo]&&(e[t]=i.value,i={configurable:Jo in i?i[Jo]:r[Jo],enumerable:Xo in i?i[Xo]:r[Xo],writable:!1})}return Ko(e,t,i)}:Ko:function(e,t,i){if(Ls(e),t=Kd(t),Ls(i),YT)try{return Ko(e,t,i)}catch{}if("get"in i||"set"in i)throw new XT("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var sr=b((G$,Jd)=>{"use strict";var ZT=rt(),eI=Ri(),tI=Hr();Jd.exports=ZT?function(a,e,t){return eI.f(a,e,tI(1,t))}:function(a,e,t){return a[e]=t,a}});var Ee=b((Y$,ep)=>{"use strict";var Kr=Te(),iI=Po(),rI=Ao(),aI=Ie(),sI=jd().f,nI=Go(),nr=ki(),oI=ar(),or=sr(),Zd=wt();Gr();var uI=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 iI(a,this,arguments)};return e.prototype=a.prototype,e};ep.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?Kr:r?Kr[t]:Kr[t]&&Kr[t].prototype,o=i?nr:nr[t]||or(nr,t,{})[t],u=o.prototype,c,d,l,p,m,f,g,v,S;for(p in e)c=nI(i?p:t+(r?".":"#")+p,a.forced),d=!c&&n&&Zd(n,p),f=o[p],d&&(a.dontCallGetSet?(S=sI(n,p),g=S&&S.value):g=n[p]),m=d&&g?g:e[p],!(!c&&!s&&typeof f==typeof m)&&(a.bind&&d?v=oI(m,Kr):a.wrap&&d?v=uI(m):s&&aI(m)?v=rI(m):v=m,(a.sham||m&&m.sham||f&&f.sham)&&or(v,"sham",!0),or(o,p,v),s&&(l=t+"Prototype",Zd(nr,l)||or(nr,l,{}),or(nr[l],p,m),a.real&&u&&(c||!u[p])&&or(u,p,m)))}});var Ds=b((K$,ip)=>{"use strict";var cI=Uo(),lI=Ho(),tp=cI("keys");ip.exports=function(a){return tp[a]||(tp[a]=lI(a))}});var ap=b((X$,rp)=>{"use strict";var dI=Ae();rp.exports=!dI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Bs=b((J$,np)=>{"use strict";var pI=wt(),hI=Ie(),mI=ir(),fI=Ds(),bI=ap(),sp=fI("IE_PROTO"),eu=Object,gI=eu.prototype;np.exports=bI?eu.getPrototypeOf:function(a){var e=mI(a);if(pI(e,sp))return e[sp];var t=e.constructor;return hI(t)&&e instanceof t?t.prototype:e instanceof eu?gI:null}});var up=b((Z$,op)=>{"use strict";var vI=Math.ceil,SI=Math.floor;op.exports=Math.trunc||function(e){var t=+e;return(t>0?SI:vI)(t)}});var Xr=b((eC,cp)=>{"use strict";var yI=up();cp.exports=function(a){var e=+a;return e!==e||e===0?0:yI(e)}});var dp=b((tC,lp)=>{"use strict";var TI=Xr(),II=Math.max,EI=Math.min;lp.exports=function(a,e){var t=TI(a);return t<0?II(t+e,0):EI(t,e)}});var tu=b((iC,pp)=>{"use strict";var wI=Xr(),xI=Math.min;pp.exports=function(a){var e=wI(a);return e>0?xI(e,9007199254740991):0}});var ur=b((rC,hp)=>{"use strict";var PI=tu();hp.exports=function(a){return PI(a.length)}});var iu=b((aC,fp)=>{"use strict";var kI=Pi(),AI=dp(),RI=ur(),mp=function(a){return function(e,t,i){var r=kI(e),s=RI(r);if(s===0)return!a&&-1;var n=AI(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}};fp.exports={includes:mp(!0),indexOf:mp(!1)}});var Vs=b((sC,bp)=>{"use strict";bp.exports={}});var Sp=b((nC,vp)=>{"use strict";var MI=Re(),ru=wt(),$I=Pi(),CI=iu().indexOf,LI=Vs(),gp=MI([].push);vp.exports=function(a,e){var t=$I(a),i=0,r=[],s;for(s in t)!ru(LI,s)&&ru(t,s)&&gp(r,s);for(;e.length>i;)ru(t,s=e[i++])&&(~CI(r,s)||gp(r,s));return r}});var au=b((oC,yp)=>{"use strict";yp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var su=b((uC,Tp)=>{"use strict";var DI=Sp(),BI=au();Tp.exports=Object.keys||function(e){return DI(e,BI)}});var nu=b((cC,Pp)=>{"use strict";var Ep=rt(),VI=Ae(),wp=Re(),_I=Bs(),OI=su(),NI=Pi(),FI=Mo().f,xp=wp(FI),qI=wp([].push),UI=Ep&&VI(function(){var a=Object.create(null);return a[2]=2,!xp(a,2)}),Ip=function(a){return function(e){for(var t=NI(e),i=OI(t),r=UI&&_I(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Ep||(r?u in t:xp(t,u)))&&qI(o,a?[u,t[u]]:t[u]);return o}};Pp.exports={entries:Ip(!0),values:Ip(!1)}});var kp=b(()=>{"use strict";var HI=Ee(),jI=nu().values;HI({target:"Object",stat:!0},{values:function(e){return jI(e)}})});var Rp=b((pC,Ap)=>{"use strict";kp();var QI=ki();Ap.exports=QI.Object.values});var $p=b((hC,Mp)=>{"use strict";var zI=Rp();Mp.exports=zI});var Mi=b((mC,Cp)=>{"use strict";var WI=$p();Cp.exports=WI});var Jr=b((fC,Lp)=>{"use strict";Lp.exports=function(){}});var Dp=b(()=>{"use strict";var GI=Ee(),YI=iu().includes,KI=Ae(),XI=Jr(),JI=KI(function(){return!Array(1).includes()});GI({target:"Array",proto:!0,forced:JI},{includes:function(e){return YI(this,e,arguments.length>1?arguments[1]:void 0)}});XI("includes")});var ai=b((vC,Bp)=>{"use strict";var ZI=Ut();Bp.exports=ZI});var _p=b((SC,Vp)=>{"use strict";Dp();var eE=ai();Vp.exports=eE("Array","includes")});var Np=b((yC,Op)=>{"use strict";var tE=_p();Op.exports=tE});var Ge=b((TC,Fp)=>{"use strict";var iE=Np();Fp.exports=iE});var eh=b(()=>{"use strict";var pE=Ee(),hE=nu().entries;pE({target:"Object",stat:!0},{entries:function(e){return hE(e)}})});var ih=b((uD,th)=>{"use strict";eh();var mE=ki();th.exports=mE.Object.entries});var ah=b((cD,rh)=>{"use strict";var fE=ih();rh.exports=fE});var oi=b((lD,sh)=>{"use strict";var bE=ah();sh.exports=bE});var Ci=b((dD,nh)=>{"use strict";nh.exports={}});var ch=b((pD,uh)=>{"use strict";var gE=Te(),vE=Ie(),oh=gE.WeakMap;uh.exports=vE(oh)&&/native code/.test(String(oh))});var mu=b((hD,ph)=>{"use strict";var SE=ch(),dh=Te(),yE=We(),TE=sr(),du=wt(),pu=Gr(),IE=Ds(),EE=Vs(),lh="Object already initialized",hu=dh.TypeError,wE=dh.WeakMap,Ks,ra,Xs,xE=function(a){return Xs(a)?ra(a):Ks(a,{})},PE=function(a){return function(e){var t;if(!yE(e)||(t=ra(e)).type!==a)throw new hu("Incompatible receiver, "+a+" required");return t}};SE||pu.state?(xt=pu.state||(pu.state=new wE),xt.get=xt.get,xt.has=xt.has,xt.set=xt.set,Ks=function(a,e){if(xt.has(a))throw new hu(lh);return e.facade=a,xt.set(a,e),e},ra=function(a){return xt.get(a)||{}},Xs=function(a){return xt.has(a)}):(Li=IE("state"),EE[Li]=!0,Ks=function(a,e){if(du(a,Li))throw new hu(lh);return e.facade=a,TE(a,Li,e),e},ra=function(a){return du(a,Li)?a[Li]:{}},Xs=function(a){return du(a,Li)});var xt,Li;ph.exports={set:Ks,get:ra,has:Xs,enforce:xE,getterFor:PE}});var gu=b((mD,mh)=>{"use strict";var fu=rt(),kE=wt(),hh=Function.prototype,AE=fu&&Object.getOwnPropertyDescriptor,bu=kE(hh,"name"),RE=bu&&function(){}.name==="something",ME=bu&&(!fu||fu&&AE(hh,"name").configurable);mh.exports={EXISTS:bu,PROPER:RE,CONFIGURABLE:ME}});var bh=b(fh=>{"use strict";var $E=rt(),CE=Yo(),LE=Ri(),DE=Lt(),BE=Pi(),VE=su();fh.f=$E&&!CE?Object.defineProperties:function(e,t){DE(e);for(var i=BE(t),r=VE(t),s=r.length,n=0,o;s>n;)LE.f(e,o=r[n++],i[o]);return e}});var vu=b((bD,gh)=>{"use strict";var _E=Ut();gh.exports=_E("document","documentElement")});var Iu=b((gD,wh)=>{"use strict";var OE=Lt(),NE=bh(),vh=au(),FE=Vs(),qE=vu(),UE=Cs(),HE=Ds(),Sh=">",yh="<",yu="prototype",Tu="script",Ih=HE("IE_PROTO"),Su=function(){},Eh=function(a){return yh+Tu+Sh+a+yh+"/"+Tu+Sh},Th=function(a){a.write(Eh("")),a.close();var e=a.parentWindow.Object;return a=null,e},jE=function(){var a=UE("iframe"),e="java"+Tu+":",t;return a.style.display="none",qE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Eh("document.F=Object")),t.close(),t.F},Js,Zs=function(){try{Js=new ActiveXObject("htmlfile")}catch{}Zs=typeof document<"u"?document.domain&&Js?Th(Js):jE():Th(Js);for(var a=vh.length;a--;)delete Zs[yu][vh[a]];return Zs()};FE[Ih]=!0;wh.exports=Object.create||function(e,t){var i;return e!==null?(Su[yu]=OE(e),i=new Su,Su[yu]=null,i[Ih]=e):i=Zs(),t===void 0?i:NE.f(i,t)}});var lr=b((vD,xh)=>{"use strict";var QE=sr();xh.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:QE(a,e,t),a}});var Pu=b((SD,Ah)=>{"use strict";var zE=Ae(),WE=Ie(),GE=We(),YE=Iu(),Ph=Bs(),KE=lr(),XE=_e(),JE=Et(),xu=XE("iterator"),kh=!1,jt,Eu,wu;[].keys&&(wu=[].keys(),"next"in wu?(Eu=Ph(Ph(wu)),Eu!==Object.prototype&&(jt=Eu)):kh=!0);var ZE=!GE(jt)||zE(function(){var a={};return jt[xu].call(a)!==a});ZE?jt={}:JE&&(jt=YE(jt));WE(jt[xu])||KE(jt,xu,function(){return this});Ah.exports={IteratorPrototype:jt,BUGGY_SAFARI_ITERATORS:kh}});var en=b((yD,Mh)=>{"use strict";var ew=_e(),tw=ew("toStringTag"),Rh={};Rh[tw]="z";Mh.exports=String(Rh)==="[object z]"});var aa=b((TD,$h)=>{"use strict";var iw=en(),rw=Ie(),tn=xi(),aw=_e(),sw=aw("toStringTag"),nw=Object,ow=tn(function(){return arguments}())==="Arguments",uw=function(a,e){try{return a[e]}catch{}};$h.exports=iw?tn:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=uw(e=nw(a),sw))=="string"?t:ow?tn(e):(i=tn(e))==="Object"&&rw(e.callee)?"Arguments":i}});var Lh=b((ID,Ch)=>{"use strict";var cw=en(),lw=aa();Ch.exports=cw?{}.toString:function(){return"[object "+lw(this)+"]"}});var sa=b((ED,Bh)=>{"use strict";var dw=en(),pw=Ri().f,hw=sr(),mw=wt(),fw=Lh(),bw=_e(),Dh=bw("toStringTag");Bh.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(mw(r,Dh)||pw(r,Dh,{configurable:!0,value:e}),i&&!dw&&hw(r,"toString",fw))}});var _h=b((wD,Vh)=>{"use strict";var gw=Pu().IteratorPrototype,vw=Iu(),Sw=Hr(),yw=sa(),Tw=Ci(),Iw=function(){return this};Vh.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=vw(gw,{next:Sw(+!i,t)}),yw(a,r,!1,!0),Tw[r]=Iw,a}});var Nh=b((xD,Oh)=>{"use strict";var Ew=Re(),ww=Ct();Oh.exports=function(a,e,t){try{return Ew(ww(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var qh=b((PD,Fh)=>{"use strict";var xw=We();Fh.exports=function(a){return xw(a)||a===null}});var Hh=b((kD,Uh)=>{"use strict";var Pw=qh(),kw=String,Aw=TypeError;Uh.exports=function(a){if(Pw(a))return a;throw new Aw("Can't set "+kw(a)+" as a prototype")}});var ku=b((AD,jh)=>{"use strict";var Rw=Nh(),Mw=We(),$w=ri(),Cw=Hh();jh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Rw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return $w(r),Cw(s),Mw(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var tm=b((RD,em)=>{"use strict";var Lw=Ee(),Dw=at(),rn=Et(),Jh=gu(),Bw=Ie(),Vw=_h(),Qh=Bs(),zh=ku(),_w=sa(),Ow=sr(),Au=lr(),Nw=_e(),Wh=Ci(),Zh=Pu(),Fw=Jh.PROPER,qw=Jh.CONFIGURABLE,Gh=Zh.IteratorPrototype,an=Zh.BUGGY_SAFARI_ITERATORS,na=Nw("iterator"),Yh="keys",oa="values",Kh="entries",Xh=function(){return this};em.exports=function(a,e,t,i,r,s,n){Vw(t,e,i);var o=function(S){if(S===r&&p)return p;if(!an&&S&&S in d)return d[S];switch(S){case Yh:return function(){return new t(this,S)};case oa:return function(){return new t(this,S)};case Kh:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,d=a.prototype,l=d[na]||d["@@iterator"]||r&&d[r],p=!an&&l||o(r),m=e==="Array"&&d.entries||l,f,g,v;if(m&&(f=Qh(m.call(new a)),f!==Object.prototype&&f.next&&(!rn&&Qh(f)!==Gh&&(zh?zh(f,Gh):Bw(f[na])||Au(f,na,Xh)),_w(f,u,!0,!0),rn&&(Wh[u]=Xh))),Fw&&r===oa&&l&&l.name!==oa&&(!rn&&qw?Ow(d,"name",oa):(c=!0,p=function(){return Dw(l,this)})),r)if(g={values:o(oa),keys:s?p:o(Yh),entries:o(Kh)},n)for(v in g)(an||c||!(v in d))&&Au(d,v,g[v]);else Lw({target:e,proto:!0,forced:an||c},g);return(!rn||n)&&d[na]!==p&&Au(d,na,p,{name:r}),Wh[e]=p,g}});var rm=b((MD,im)=>{"use strict";im.exports=function(a,e){return{value:a,done:e}}});var Mu=b(($D,um)=>{"use strict";var Uw=Pi(),Ru=Jr(),am=Ci(),nm=mu(),Hw=Ri().f,jw=tm(),sn=rm(),Qw=Et(),zw=rt(),om="Array Iterator",Ww=nm.set,Gw=nm.getterFor(om);um.exports=jw(Array,"Array",function(a,e){Ww(this,{type:om,target:Uw(a),index:0,kind:e})},function(){var a=Gw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,sn(void 0,!0);switch(a.kind){case"keys":return sn(t,!1);case"values":return sn(e[t],!1)}return sn([t,e[t]],!1)},"values");var sm=am.Arguments=am.Array;Ru("keys");Ru("values");Ru("entries");if(!Qw&&zw&&sm.name!=="values")try{Hw(sm,"name",{value:"values"})}catch{}});var lm=b((CD,cm)=>{"use strict";var Yw=_e(),Kw=Ci(),Xw=Yw("iterator"),Jw=Array.prototype;cm.exports=function(a){return a!==void 0&&(Kw.Array===a||Jw[Xw]===a)}});var $u=b((LD,pm)=>{"use strict";var Zw=aa(),dm=Wr(),ex=jr(),tx=Ci(),ix=_e(),rx=ix("iterator");pm.exports=function(a){if(!ex(a))return dm(a,rx)||dm(a,"@@iterator")||tx[Zw(a)]}});var mm=b((DD,hm)=>{"use strict";var ax=at(),sx=Ct(),nx=Lt(),ox=zr(),ux=$u(),cx=TypeError;hm.exports=function(a,e){var t=arguments.length<2?ux(a):e;if(sx(t))return nx(ax(t,a));throw new cx(ox(a)+" is not iterable")}});var gm=b((BD,bm)=>{"use strict";var lx=at(),fm=Lt(),dx=Wr();bm.exports=function(a,e,t){var i,r;fm(a);try{if(i=dx(a,"return"),!i){if(e==="throw")throw t;return t}i=lx(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return fm(i),t}});var on=b((VD,Tm)=>{"use strict";var px=ar(),hx=at(),mx=Lt(),fx=zr(),bx=lm(),gx=ur(),vm=Qr(),vx=mm(),Sx=$u(),Sm=gm(),yx=TypeError,nn=function(a,e){this.stopped=a,this.result=e},ym=nn.prototype;Tm.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=px(e,i),c,d,l,p,m,f,g,v=function(E){return c&&Sm(c,"normal"),new nn(!0,E)},S=function(E){return r?(mx(E),o?u(E[0],E[1],v):u(E[0],E[1])):o?u(E,v):u(E)};if(s)c=a.iterator;else if(n)c=a;else{if(d=Sx(a),!d)throw new yx(fx(a)+" is not iterable");if(bx(d)){for(l=0,p=gx(a);p>l;l++)if(m=S(a[l]),m&&vm(ym,m))return m;return new nn(!1)}c=vx(a,d)}for(f=s?a.next:c.next;!(g=hx(f,c)).done;){try{m=S(g.value)}catch(E){Sm(c,"throw",E)}if(typeof m=="object"&&m&&vm(ym,m))return m}return new nn(!1)}});var Em=b((_D,Im)=>{"use strict";var Tx=rt(),Ix=Ri(),Ex=Hr();Im.exports=function(a,e,t){Tx?Ix.f(a,e,Ex(0,t)):a[e]=t}});var wm=b(()=>{"use strict";var wx=Ee(),xx=on(),Px=Em();wx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return xx(e,function(i,r){Px(t,i,r)},{AS_ENTRIES:!0}),t}})});var Pm=b((FD,xm)=>{"use strict";Mu();wm();var kx=ki();xm.exports=kx.Object.fromEntries});var Am=b((qD,km)=>{"use strict";km.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 Mm=b(()=>{"use strict";Mu();var Ax=Am(),Rx=Te(),Mx=sa(),Rm=Ci();for(un in Ax)Mx(Rx[un],un),Rm[un]=Rm.Array;var un});var Cm=b((jD,$m)=>{"use strict";var $x=Pm();Mm();$m.exports=$x});var Cu=b((QD,Lm)=>{"use strict";var Cx=Cm();Lm.exports=Cx});var Dm=b(()=>{"use strict"});var Lu=b((GD,Bm)=>{"use strict";var ua=Te(),Lx=Ai(),Dx=xi(),cn=function(a){return Lx.slice(0,a.length)===a};Bm.exports=function(){return cn("Bun/")?"BUN":cn("Cloudflare-Workers")?"CLOUDFLARE":cn("Deno/")?"DENO":cn("Node.js/")?"NODE":ua.Bun&&typeof Bun.version=="string"?"BUN":ua.Deno&&typeof Deno.version=="object"?"DENO":Dx(ua.process)==="process"?"NODE":ua.window&&ua.document?"BROWSER":"REST"}()});var ln=b((YD,Vm)=>{"use strict";var Bx=Lu();Vm.exports=Bx==="NODE"});var Om=b((KD,_m)=>{"use strict";var Vx=Ri();_m.exports=function(a,e,t){return Vx.f(a,e,t)}});var qm=b((XD,Fm)=>{"use strict";var _x=Ut(),Ox=Om(),Nx=_e(),Fx=rt(),Nm=Nx("species");Fm.exports=function(a){var e=_x(a);Fx&&e&&!e[Nm]&&Ox(e,Nm,{configurable:!0,get:function(){return this}})}});var Hm=b((JD,Um)=>{"use strict";var qx=Qr(),Ux=TypeError;Um.exports=function(a,e){if(qx(e,a))return a;throw new Ux("Incorrect invocation")}});var Bu=b((ZD,jm)=>{"use strict";var Hx=Re(),jx=Ie(),Du=Gr(),Qx=Hx(Function.toString);jx(Du.inspectSource)||(Du.inspectSource=function(a){return Qx(a)});jm.exports=Du.inspectSource});var _u=b((e0,Ym)=>{"use strict";var zx=Re(),Wx=Ae(),Qm=Ie(),Gx=aa(),Yx=Ut(),Kx=Bu(),zm=function(){},Wm=Yx("Reflect","construct"),Vu=/^\s*(?:class|function)\b/,Xx=zx(Vu.exec),Jx=!Vu.test(zm),ca=function(e){if(!Qm(e))return!1;try{return Wm(zm,[],e),!0}catch{return!1}},Gm=function(e){if(!Qm(e))return!1;switch(Gx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Jx||!!Xx(Vu,Kx(e))}catch{return!0}};Gm.sham=!0;Ym.exports=!Wm||Wx(function(){var a;return ca(ca.call)||!ca(Object)||!ca(function(){a=!0})||a})?Gm:ca});var Xm=b((t0,Km)=>{"use strict";var Zx=_u(),eP=zr(),tP=TypeError;Km.exports=function(a){if(Zx(a))return a;throw new tP(eP(a)+" is not a constructor")}});var Ou=b((i0,Zm)=>{"use strict";var Jm=Lt(),iP=Xm(),rP=jr(),aP=_e(),sP=aP("species");Zm.exports=function(a,e){var t=Jm(a).constructor,i;return t===void 0||rP(i=Jm(t)[sP])?e:iP(i)}});var tf=b((r0,ef)=>{"use strict";var nP=Re();ef.exports=nP([].slice)});var af=b((a0,rf)=>{"use strict";var oP=TypeError;rf.exports=function(a,e){if(a<e)throw new oP("Not enough arguments");return a}});var Nu=b((s0,sf)=>{"use strict";var uP=Ai();sf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(uP)});var Gu=b((n0,mf)=>{"use strict";var nt=Te(),cP=Po(),lP=ar(),nf=Ie(),dP=wt(),hf=Ae(),of=vu(),pP=tf(),uf=Cs(),hP=af(),mP=Nu(),fP=ln(),Qu=nt.setImmediate,zu=nt.clearImmediate,bP=nt.process,Fu=nt.Dispatch,gP=nt.Function,cf=nt.MessageChannel,vP=nt.String,qu=0,la={},lf="onreadystatechange",da,Di,Uu,Hu;hf(function(){da=nt.location});var Wu=function(a){if(dP(la,a)){var e=la[a];delete la[a],e()}},ju=function(a){return function(){Wu(a)}},df=function(a){Wu(a.data)},pf=function(a){nt.postMessage(vP(a),da.protocol+"//"+da.host)};(!Qu||!zu)&&(Qu=function(e){hP(arguments.length,1);var t=nf(e)?e:gP(e),i=pP(arguments,1);return la[++qu]=function(){cP(t,void 0,i)},Di(qu),qu},zu=function(e){delete la[e]},fP?Di=function(a){bP.nextTick(ju(a))}:Fu&&Fu.now?Di=function(a){Fu.now(ju(a))}:cf&&!mP?(Uu=new cf,Hu=Uu.port2,Uu.port1.onmessage=df,Di=lP(Hu.postMessage,Hu)):nt.addEventListener&&nf(nt.postMessage)&&!nt.importScripts&&da&&da.protocol!=="file:"&&!hf(pf)?(Di=pf,nt.addEventListener("message",df,!1)):lf in uf("script")?Di=function(a){of.appendChild(uf("script"))[lf]=function(){of.removeChild(this),Wu(a)}}:Di=function(a){setTimeout(ju(a),0)});mf.exports={set:Qu,clear:zu}});var gf=b((o0,bf)=>{"use strict";var ff=Te(),SP=rt(),yP=Object.getOwnPropertyDescriptor;bf.exports=function(a){if(!SP)return ff[a];var e=yP(ff,a);return e&&e.value}});var Yu=b((u0,Sf)=>{"use strict";var vf=function(){this.head=null,this.tail=null};vf.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}}};Sf.exports=vf});var Tf=b((c0,yf)=>{"use strict";var TP=Ai();yf.exports=/ipad|iphone|ipod/i.test(TP)&&typeof Pebble<"u"});var Ef=b((l0,If)=>{"use strict";var IP=Ai();If.exports=/web0s(?!.*chrome)/i.test(IP)});var Mf=b((d0,Rf)=>{"use strict";var pr=Te(),EP=gf(),wf=ar(),Ku=Gu().set,wP=Yu(),xP=Nu(),PP=Tf(),kP=Ef(),Xu=ln(),xf=pr.MutationObserver||pr.WebKitMutationObserver,Pf=pr.document,kf=pr.process,dn=pr.Promise,ec=EP("queueMicrotask"),dr,Ju,Zu,pn,Af;ec||(pa=new wP,ha=function(){var a,e;for(Xu&&(a=kf.domain)&&a.exit();e=pa.get();)try{e()}catch(t){throw pa.head&&dr(),t}a&&a.enter()},!xP&&!Xu&&!kP&&xf&&Pf?(Ju=!0,Zu=Pf.createTextNode(""),new xf(ha).observe(Zu,{characterData:!0}),dr=function(){Zu.data=Ju=!Ju}):!PP&&dn&&dn.resolve?(pn=dn.resolve(void 0),pn.constructor=dn,Af=wf(pn.then,pn),dr=function(){Af(ha)}):Xu?dr=function(){kf.nextTick(ha)}:(Ku=wf(Ku,pr),dr=function(){Ku(ha)}),ec=function(a){pa.head||dr(),pa.add(a)});var pa,ha;Rf.exports=ec});var Cf=b((p0,$f)=>{"use strict";$f.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var hn=b((h0,Lf)=>{"use strict";Lf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Bi=b((m0,Df)=>{"use strict";var AP=Te();Df.exports=AP.Promise});var hr=b((f0,Of)=>{"use strict";var RP=Te(),ma=Bi(),MP=Ie(),$P=Go(),CP=Bu(),LP=_e(),Bf=Lu(),DP=Et(),tc=Bo(),Vf=ma&&ma.prototype,BP=LP("species"),ic=!1,_f=MP(RP.PromiseRejectionEvent),VP=$P("Promise",function(){var a=CP(ma),e=a!==String(ma);if(!e&&tc===66||DP&&!(Vf.catch&&Vf.finally))return!0;if(!tc||tc<51||!/native code/.test(a)){var t=new ma(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[BP]=i,ic=t.then(function(){})instanceof i,!ic)return!0}return!e&&(Bf==="BROWSER"||Bf==="DENO")&&!_f});Of.exports={CONSTRUCTOR:VP,REJECTION_EVENT:_f,SUBCLASSING:ic}});var mr=b((b0,Ff)=>{"use strict";var Nf=Ct(),_P=TypeError,OP=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new _P("Bad Promise constructor");e=i,t=r}),this.resolve=Nf(e),this.reject=Nf(t)};Ff.exports.f=function(a){return new OP(a)}});var nb=b(()=>{"use strict";var NP=Ee(),FP=Et(),gn=ln(),ui=Te(),qP=ki(),vr=at(),qf=lr(),Uf=ku(),UP=sa(),HP=qm(),jP=Ct(),bn=Ie(),QP=We(),zP=Hm(),WP=Ou(),Wf=Gu().set,oc=Mf(),GP=Cf(),YP=hn(),KP=Yu(),Gf=mu(),vn=Bi(),uc=hr(),Yf=mr(),Sn="Promise",Kf=uc.CONSTRUCTOR,XP=uc.REJECTION_EVENT,JP=uc.SUBCLASSING,rc=Gf.getterFor(Sn),ZP=Gf.set,fr=vn&&vn.prototype,Vi=vn,mn=fr,Xf=ui.TypeError,ac=ui.document,cc=ui.process,sc=Yf.f,ek=sc,tk=!!(ac&&ac.createEvent&&ui.dispatchEvent),Jf="unhandledrejection",ik="rejectionhandled",Hf=0,Zf=1,rk=2,lc=1,eb=2,fn,jf,tb,Qf,ib=function(a){var e;return QP(a)&&bn(e=a.then)?e:!1},rb=function(a,e){var t=e.value,i=e.state===Zf,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,d;try{r?(i||(e.rejection===eb&&sk(e),e.rejection=lc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===a.promise?n(new Xf("Promise-chain cycle")):(c=ib(u))?vr(c,u,s,n):s(u)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},ab=function(a,e){a.notified||(a.notified=!0,oc(function(){for(var t=a.reactions,i;i=t.get();)rb(i,a);a.notified=!1,e&&!a.rejection&&ak(a)}))},sb=function(a,e,t){var i,r;tk?(i=ac.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),ui.dispatchEvent(i)):i={promise:e,reason:t},!XP&&(r=ui["on"+a])?r(i):a===Jf&&GP("Unhandled promise rejection",t)},ak=function(a){vr(Wf,ui,function(){var e=a.facade,t=a.value,i=zf(a),r;if(i&&(r=YP(function(){gn?cc.emit("unhandledRejection",t,e):sb(Jf,e,t)}),a.rejection=gn||zf(a)?eb:lc,r.error))throw r.value})},zf=function(a){return a.rejection!==lc&&!a.parent},sk=function(a){vr(Wf,ui,function(){var e=a.facade;gn?cc.emit("rejectionHandled",e):sb(ik,e,a.value)})},br=function(a,e,t){return function(i){a(e,i,t)}},gr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=rk,ab(a,!0))},nc=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Xf("Promise can't be resolved itself");var i=ib(e);i?oc(function(){var r={done:!1};try{vr(i,e,br(nc,r,a),br(gr,r,a))}catch(s){gr(r,s,a)}}):(a.value=e,a.state=Zf,ab(a,!1))}catch(r){gr({done:!1},r,a)}}};if(Kf&&(Vi=function(e){zP(this,mn),jP(e),vr(fn,this);var t=rc(this);try{e(br(nc,t),br(gr,t))}catch(i){gr(t,i)}},mn=Vi.prototype,fn=function(e){ZP(this,{type:Sn,done:!1,notified:!1,parent:!1,reactions:new KP,rejection:!1,state:Hf,value:null})},fn.prototype=qf(mn,"then",function(e,t){var i=rc(this),r=sc(WP(this,Vi));return i.parent=!0,r.ok=bn(e)?e:!0,r.fail=bn(t)&&t,r.domain=gn?cc.domain:void 0,i.state===Hf?i.reactions.add(r):oc(function(){rb(r,i)}),r.promise}),jf=function(){var a=new fn,e=rc(a);this.promise=a,this.resolve=br(nc,e),this.reject=br(gr,e)},Yf.f=sc=function(a){return a===Vi||a===tb?new jf(a):ek(a)},!FP&&bn(vn)&&fr!==Object.prototype)){Qf=fr.then,JP||qf(fr,"then",function(e,t){var i=this;return new Vi(function(r,s){vr(Qf,i,r,s)}).then(e,t)},{unsafe:!0});try{delete fr.constructor}catch{}Uf&&Uf(fr,mn)}NP({global:!0,constructor:!0,wrap:!0,forced:Kf},{Promise:Vi});tb=qP.Promise;UP(Vi,Sn,!1,!0);HP(Sn)});var db=b((S0,lb)=>{"use strict";var nk=_e(),ub=nk("iterator"),cb=!1;try{ob=0,dc={next:function(){return{done:!!ob++}},return:function(){cb=!0}},dc[ub]=function(){return this},Array.from(dc,function(){throw 2})}catch{}var ob,dc;lb.exports=function(a,e){try{if(!e&&!cb)return!1}catch{return!1}var t=!1;try{var i={};i[ub]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var pc=b((y0,pb)=>{"use strict";var ok=Bi(),uk=db(),ck=hr().CONSTRUCTOR;pb.exports=ck||!uk(function(a){ok.all(a).then(void 0,function(){})})});var hb=b(()=>{"use strict";var lk=Ee(),dk=at(),pk=Ct(),hk=mr(),mk=hn(),fk=on(),bk=pc();lk({target:"Promise",stat:!0,forced:bk},{all:function(e){var t=this,i=hk.f(t),r=i.resolve,s=i.reject,n=mk(function(){var o=pk(t.resolve),u=[],c=0,d=1;fk(e,function(l){var p=c++,m=!1;d++,dk(o,t,l).then(function(f){m||(m=!0,u[p]=f,--d||r(u))},s)}),--d||r(u)});return n.error&&s(n.value),i.promise}})});var fb=b(()=>{"use strict";var gk=Ee(),vk=Et(),Sk=hr().CONSTRUCTOR,mc=Bi(),yk=Ut(),Tk=Ie(),Ik=lr(),mb=mc&&mc.prototype;gk({target:"Promise",proto:!0,forced:Sk,real:!0},{catch:function(a){return this.then(void 0,a)}});!vk&&Tk(mc)&&(hc=yk("Promise").prototype.catch,mb.catch!==hc&&Ik(mb,"catch",hc,{unsafe:!0}));var hc});var bb=b(()=>{"use strict";var Ek=Ee(),wk=at(),xk=Ct(),Pk=mr(),kk=hn(),Ak=on(),Rk=pc();Ek({target:"Promise",stat:!0,forced:Rk},{race:function(e){var t=this,i=Pk.f(t),r=i.reject,s=kk(function(){var n=xk(t.resolve);Ak(e,function(o){wk(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var gb=b(()=>{"use strict";var Mk=Ee(),$k=mr(),Ck=hr().CONSTRUCTOR;Mk({target:"Promise",stat:!0,forced:Ck},{reject:function(e){var t=$k.f(this),i=t.reject;return i(e),t.promise}})});var fc=b((R0,vb)=>{"use strict";var Lk=Lt(),Dk=We(),Bk=mr();vb.exports=function(a,e){if(Lk(a),Dk(e)&&e.constructor===a)return e;var t=Bk.f(a),i=t.resolve;return i(e),t.promise}});var Tb=b(()=>{"use strict";var Vk=Ee(),_k=Ut(),Sb=Et(),Ok=Bi(),yb=hr().CONSTRUCTOR,Nk=fc(),Fk=_k("Promise"),qk=Sb&&!yb;Vk({target:"Promise",stat:!0,forced:Sb||yb},{resolve:function(e){return Nk(qk&&this===Fk?Ok:this,e)}})});var Ib=b(()=>{"use strict";nb();hb();fb();bb();gb();Tb()});var Pb=b(()=>{"use strict";var Uk=Ee(),Hk=Et(),yn=Bi(),jk=Ae(),wb=Ut(),xb=Ie(),Qk=Ou(),Eb=fc(),zk=lr(),gc=yn&&yn.prototype,Wk=!!yn&&jk(function(){gc.finally.call({then:function(){}},function(){})});Uk({target:"Promise",proto:!0,real:!0,forced:Wk},{finally:function(a){var e=Qk(this,wb("Promise")),t=xb(a);return this.then(t?function(i){return Eb(e,a()).then(function(){return i})}:a,t?function(i){return Eb(e,a()).then(function(){throw i})}:a)}});!Hk&&xb(yn)&&(bc=wb("Promise").prototype.finally,gc.finally!==bc&&zk(gc,"finally",bc,{unsafe:!0}));var bc});var Ab=b((V0,kb)=>{"use strict";Dm();Ib();Pb();var Gk=ai();kb.exports=Gk("Promise","finally")});var Mb=b((_0,Rb)=>{"use strict";var Yk=Ab();Rb.exports=Yk});var vc=b((O0,$b)=>{"use strict";var Kk=Mb();$b.exports=Kk});var Nb=b(()=>{"use strict";var aA=Ee(),sA=ir(),nA=ur(),oA=Xr(),uA=Jr();aA({target:"Array",proto:!0},{at:function(e){var t=sA(this),i=nA(t),r=oA(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});uA("at")});var qb=b((MB,Fb)=>{"use strict";Nb();var cA=ai();Fb.exports=cA("Array","at")});var Hb=b(($B,Ub)=>{"use strict";var lA=qb();Ub.exports=lA});var mt=b((CB,jb)=>{"use strict";var dA=Hb();jb.exports=dA});var Nc=b((RO,Ig)=>{"use strict";var PA=xi();Ig.exports=Array.isArray||function(e){return PA(e)==="Array"}});var wg=b((MO,Eg)=>{"use strict";var kA=TypeError,AA=9007199254740991;Eg.exports=function(a){if(a>AA)throw kA("Maximum allowed index exceeded");return a}});var kg=b(($O,Pg)=>{"use strict";var RA=Nc(),MA=ur(),$A=wg(),CA=ar(),xg=function(a,e,t,i,r,s,n,o){for(var u=r,c=0,d=n?CA(n,o):!1,l,p;c<i;)c in t&&(l=d?d(t[c],c,e):t[c],s>0&&RA(l)?(p=MA(l),u=xg(a,e,l,p,u,s-1)-1):($A(u+1),a[u]=l),u++),c++;return u};Pg.exports=xg});var $g=b((CO,Mg)=>{"use strict";var Ag=Nc(),LA=_u(),DA=We(),BA=_e(),VA=BA("species"),Rg=Array;Mg.exports=function(a){var e;return Ag(a)&&(e=a.constructor,LA(e)&&(e===Rg||Ag(e.prototype))?e=void 0:DA(e)&&(e=e[VA],e===null&&(e=void 0))),e===void 0?Rg:e}});var Lg=b((LO,Cg)=>{"use strict";var _A=$g();Cg.exports=function(a,e){return new(_A(a))(e===0?0:e)}});var Dg=b(()=>{"use strict";var OA=Ee(),NA=kg(),FA=Ct(),qA=ir(),UA=ur(),HA=Lg();OA({target:"Array",proto:!0},{flatMap:function(e){var t=qA(this),i=UA(t),r;return FA(e),r=HA(t,0),r.length=NA(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Bg=b(()=>{"use strict";var jA=Jr();jA("flatMap")});var _g=b((OO,Vg)=>{"use strict";Dg();Bg();var QA=ai();Vg.exports=QA("Array","flatMap")});var Ng=b((NO,Og)=>{"use strict";var zA=_g();Og.exports=zA});var Aa=b((FO,Fg)=>{"use strict";var WA=Ng();Fg.exports=WA});var Ma=b((rN,jg)=>{"use strict";var YA=aa(),KA=String;jg.exports=function(a){if(YA(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return KA(a)}});var qc=b((aN,Qg)=>{"use strict";Qg.exports=`
7
- \v\f\r                 \u2028\u2029\uFEFF`});var Gg=b((sN,Wg)=>{"use strict";var XA=Re(),JA=ri(),ZA=Ma(),Hc=qc(),zg=XA("".replace),eR=RegExp("^["+Hc+"]+"),tR=RegExp("(^|[^"+Hc+"])["+Hc+"]+$"),Uc=function(a){return function(e){var t=ZA(JA(e));return a&1&&(t=zg(t,eR,"")),a&2&&(t=zg(t,tR,"$1")),t}};Wg.exports={start:Uc(1),end:Uc(2),trim:Uc(3)}});var Jg=b((nN,Xg)=>{"use strict";var iR=gu().PROPER,rR=Ae(),Yg=qc(),Kg="​…᠎";Xg.exports=function(a){return rR(function(){return!!Yg[a]()||Kg[a]()!==Kg||iR&&Yg[a].name!==a})}});var jc=b((oN,Zg)=>{"use strict";var aR=Gg().start,sR=Jg();Zg.exports=sR("trimStart")?function(){return aR(this)}:"".trimStart});var tv=b(()=>{"use strict";var nR=Ee(),ev=jc();nR({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==ev},{trimLeft:ev})});var rv=b(()=>{"use strict";tv();var oR=Ee(),iv=jc();oR({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==iv},{trimStart:iv})});var sv=b((pN,av)=>{"use strict";rv();var uR=ai();av.exports=uR("String","trimLeft")});var ov=b((hN,nv)=>{"use strict";var cR=sv();nv.exports=cR});var cv=b((mN,uv)=>{"use strict";var lR=ov();uv.exports=lR});var dv=b(()=>{"use strict"});var pv=b(()=>{"use strict"});var mv=b((YN,hv)=>{"use strict";var dR=We(),pR=xi(),hR=_e(),mR=hR("match");hv.exports=function(a){var e;return dR(a)&&((e=a[mR])!==void 0?!!e:pR(a)==="RegExp")}});var gv=b((KN,bv)=>{"use strict";var fR=Te(),bR=Ae(),fv=fR.RegExp,gR=!bR(function(){var a=!0;try{fv(".","d")}catch{a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,c){Object.defineProperty(e,u,{get:function(){return t+=c,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(fv.prototype,"flags").get.call(e);return o!==i||t!==i});bv.exports={correct:gR}});var Sv=b((XN,vv)=>{"use strict";var vR=Lt();vv.exports=function(){var a=vR(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 Iv=b((JN,Tv)=>{"use strict";var SR=at(),yR=wt(),TR=Qr(),yv=gv(),IR=Sv(),ER=RegExp.prototype;Tv.exports=yv.correct?function(a){return a.flags}:function(a){return!yv.correct&&TR(ER,a)&&!yR(a,"flags")?SR(IR,a):a.flags}});var wv=b((ZN,Ev)=>{"use strict";var Gc=Re(),wR=ir(),xR=Math.floor,zc=Gc("".charAt),PR=Gc("".replace),Wc=Gc("".slice),kR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,AR=/\$([$&'`]|\d{1,2})/g;Ev.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=AR;return r!==void 0&&(r=wR(r),u=kR),PR(s,u,function(c,d){var l;switch(zc(d,0)){case"$":return"$";case"&":return a;case"`":return Wc(e,0,t);case"'":return Wc(e,n);case"<":l=r[Wc(d,1,-1)];break;default:var p=+d;if(p===0)return c;if(p>o){var m=xR(p/10);return m===0?c:m<=o?i[m-1]===void 0?zc(d,1):i[m-1]+zc(d,1):c}l=i[p-1]}return l===void 0?"":l})}});var kv=b(()=>{"use strict";var RR=Ee(),MR=at(),Kc=Re(),xv=ri(),$R=Ie(),CR=We(),LR=mv(),kr=Ma(),DR=Wr(),BR=Iv(),VR=wv(),_R=_e(),OR=Et(),NR=_R("replace"),FR=TypeError,Yc=Kc("".indexOf),qR=Kc("".replace),Pv=Kc("".slice),UR=Math.max;RR({target:"String",proto:!0},{replaceAll:function(e,t){var i=xv(this),r,s,n,o,u,c,d,l,p,m,f=0,g="";if(CR(e)){if(r=LR(e),r&&(s=kr(xv(BR(e))),!~Yc(s,"g")))throw new FR("`.replaceAll` does not allow non-global regexes");if(n=DR(e,NR),n)return MR(n,e,i,t);if(OR&&r)return qR(kr(i),e,t)}for(o=kr(i),u=kr(e),c=$R(t),c||(t=kr(t)),d=u.length,l=UR(1,d),p=Yc(o,u);p!==-1;)m=c?kr(t(u,p,o)):VR(u,o,p,[],void 0,t),g+=Pv(o,f,p)+m,f=p+d,p=p+l>o.length?-1:Yc(o,u,p+l);return f<o.length&&(g+=Pv(o,f)),g}})});var Rv=b((iF,Av)=>{"use strict";dv();pv();kv();var HR=ai();Av.exports=HR("String","replaceAll")});var $v=b((rF,Mv)=>{"use strict";var jR=Rv();Mv.exports=jR});var Lv=b((aF,Cv)=>{"use strict";var QR=$v();Cv.exports=QR});var Bv=b((sF,Dv)=>{"use strict";var zR=Xr(),WR=Ma(),GR=ri(),YR=RangeError;Dv.exports=function(e){var t=WR(GR(this)),i="",r=zR(e);if(r<0||r===1/0)throw new YR("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var Fv=b((nF,Nv)=>{"use strict";var Ov=Re(),KR=tu(),Vv=Ma(),XR=Bv(),JR=ri(),ZR=Ov(XR),eM=Ov("".slice),tM=Math.ceil,_v=function(a){return function(e,t,i){var r=Vv(JR(e)),s=KR(t),n=r.length,o=i===void 0?" ":Vv(i),u,c;return s<=n||o===""?r:(u=s-n,c=ZR(o,tM(u/o.length)),c.length>u&&(c=eM(c,0,u)),a?r+c:c+r)}};Nv.exports={start:_v(!1),end:_v(!0)}});var Uv=b((oF,qv)=>{"use strict";var iM=Ai();qv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(iM)});var Hv=b(()=>{"use strict";var rM=Ee(),aM=Fv().start,sM=Uv();rM({target:"String",proto:!0,forced:sM},{padStart:function(e){return aM(this,e,arguments.length>1?arguments[1]:void 0)}})});var Qv=b((lF,jv)=>{"use strict";Hv();var nM=ai();jv.exports=nM("String","padStart")});var Wv=b((dF,zv)=>{"use strict";var oM=Qv();zv.exports=oM});var Yv=b((pF,Gv)=>{"use strict";var uM=Wv();Gv.exports=uM});var JM={};oy(JM,{ChromecastState:()=>tr,HttpConnectionType:()=>As,Observable:()=>Ft.Observable,PlaybackState:()=>Ve,Player:()=>vs,PredefinedQualityLimits:()=>Fr,SDK_VERSION:()=>XM,Subject:()=>Ft.Subject,Subscription:()=>Ft.Subscription,Surface:()=>Rs,VERSION:()=>wo,ValueSubject:()=>Ft.ValueSubject,VideoFormat:()=>$t,VideoQuality:()=>Ft.VideoQuality,WebmCodecStrategy:()=>Ca,areValidLiveRecordSources:()=>Xp,clientChecker:()=>F,isMobile:()=>si});module.exports=uy(JM);var wo="2.0.151-dev.6dd94264.0";var Ve=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ve||{}),$t=(w=>(w.MPEG="MPEG",w.DASH="DASH",w.DASH_SEP="DASH_SEP",w.DASH_SEP_VK="DASH_SEP",w.DASH_WEBM="DASH_WEBM",w.DASH_WEBM_AV1="DASH_WEBM_AV1",w.DASH_STREAMS="DASH_STREAMS",w.DASH_WEBM_VK="DASH_WEBM",w.DASH_ONDEMAND="DASH_ONDEMAND",w.DASH_ONDEMAND_VK="DASH_ONDEMAND",w.DASH_LIVE="DASH_LIVE",w.DASH_LIVE_CMAF="DASH_LIVE_CMAF",w.DASH_LIVE_WEBM="DASH_LIVE_WEBM",w.HLS="HLS",w.HLS_ONDEMAND="HLS_ONDEMAND",w.HLS_JS="HLS",w.HLS_FMP4="HLS_FMP4",w.HLS_LIVE="HLS_LIVE",w.HLS_LIVE_CMAF="HLS_LIVE_CMAF",w.WEB_RTC_LIVE="WEB_RTC_LIVE",w))($t||{});var tr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(tr||{}),As=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(As||{});var Rs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Rs||{}),Fr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Fr||{});var El=j(Mi(),1),XS=j(Ge(),1);var J=require("@vkontakte/videoplayer-shared");var qp=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var _s=class{constructor(e){this.connection$=new J.ValueSubject(void 0);this.castState$=new J.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new J.Subject;this.realCastState$=new J.ValueSubject("NOT_AVAILABLE");this.subscription=new J.Subscription;this.isDestroyed=!1;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,J.isNonNullable)(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||qp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:J.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,J.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,J.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,J.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,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,J.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,J.assertNever)(r.sessionState)}})).add((0,J.merge)((0,J.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,J.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,J.map)(r=>r.castState)),(0,J.observableFrom)([i.getCastState()])).pipe((0,J.filterChanged)(),(0,J.map)(rE),(0,J.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",n=(0,J.isNonNullable)(this.connection$.getValue());if(s&&!n){let o=i.getCurrentSession();(0,J.assertNonNullable)(o);let u=o.getCastDevice(),c=o.getMediaSession()?.media?.contentId;((0,J.isNullable)(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,J.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){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{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:J.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},rE=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,J.assertNever)(a)}};var ee=require("@vkontakte/videoplayer-shared");var Me=require("@vkontakte/videoplayer-shared");var ou=require("@vkontakte/videoplayer-shared");var Oe=(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,ou.assertNever)(t)}return a},Os=(a,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:(0,ou.assertNever)(e)}};var Fs=a=>{let{source:e,format:t,meta:i,output:r}=a,s,n,o;switch(t){case"MPEG":{let l=e[t];(0,Me.assertNonNullable)(l);let p=(0,Me.getHighestQuality)(Object.keys(l));(0,Me.assertNonNullable)(p);let m=l[p];(0,Me.assertNonNullable)(m),s=m,n="video/mp4",o=Ns();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=e[t];(0,Me.assertNonNullable)(l),s=l.url,n="application/x-mpegurl",o=Ns();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=e[t];(0,Me.assertNonNullable)(l),s=l.url,n="application/dash+xml",o=Ns();break}case"DASH_LIVE_CMAF":{let l=e[t];(0,Me.assertNonNullable)(l),s=l.url,n="application/dash+xml",o=Up();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=e[t];(0,Me.assertNonNullable)(l),s=Oe(l.url),n="application/x-mpegurl",o=Up();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",p=new Error(l);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Me.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return(0,Me.assertNever)(t)}let u=aE(i.videoId??s,n);u.contentUrl=s,u.streamType=o,u.metadata=sE();let{title:c,subtitle:d}=i;return(0,Me.isNonNullable)(c)&&(u.metadata.title=c),(0,Me.isNonNullable)(d)&&(u.metadata.subtitle=d),u};function Ns(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function Up(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function aE(a,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(a,e):{contentId:a,contentType:e,metadata:{title:"",subtitle:""},streamType:Ns()}}function sE(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var L=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var qs=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};var cu=require("@vkontakte/videoplayer-shared");var Ys=require("@vkontakte/videoplayer-shared");var Hp=j(Ge(),1),jp=require("@vkontakte/videoplayer-shared");var Us=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Hp.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||c||r||s||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=(0,jp.getWindow)().navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Qp=j(Ge(),1),ni=require("@vkontakte/videoplayer-shared");var si=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Hs=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||(0,Qp.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let e=(0,ni.getWindow)();if(!(0,ni.isBrowserWindow)(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=si()}catch(i){console.error("DeviceChecker: calling isMobile error - ",i)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let e=(0,ni.getWindow)();if(!(0,ni.isBrowserWindow)(e))return;let{userAgentData:t}=e.navigator;if(t?.getHighEntropyValues){let i=await t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.model)}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let s=e.match(i);if(s){let n=r.length>0,o=r.length>1,u="Unknown",c="Unknown";if(n){let d=r[0];typeof d=="number"?d<s.length&&s[d]!==void 0&&(u=s[d]):u=d}if(o){let d=r[1];typeof d=="number"?d<s.length&&s[d]!==void 0&&(c=s[d]):d!==void 0&&(c=d)}else s[2]!==void 0?c=s[2]:s[1]!==void 0&&n&&typeof r[0]=="string"&&(c=s[1]);u=this.normalizeOSName(u),c=this.normalizeOSVersion(c,u),u==="iOS"&&/ipad/i.test(e)?u="iPadOS":u==="iPadOS"&&/ip(hone|od)/i.test(e)&&(u="iOS"),this._os={name:u,version:c||"Unknown",full:c&&c!=="Unknown"?`${u} ${c}`:u};break}}}catch(t){console.error("DeviceChecker: OS detection error - ",t)}}normalizeOSName(e){if(!e)return"Unknown";let t=e.toLowerCase();return t.includes("windows")?"Windows":t.includes("mac os")||t.includes("macintosh")?"macOS":t.includes("iphone")||t.includes("ios")?"iOS":t.includes("ipados")?"iPadOS":t.includes("android")?"Android":t.includes("harmonyos")?"HarmonyOS":t.includes("linux")?"Linux":t.includes("cros")?"Chrome OS":t.includes("freebsd")?"FreeBSD":t.includes("openbsd")?"OpenBSD":t.includes("solaris")||t.includes("sunos")?"Solaris":t.includes("aix")?"AIX":e}normalizeOSVersion(e,t){if(!e)return"Unknown";if(e!=="Unknown"&&(e=e.replace(/_/g,"."),t==="Windows")){let i=parseFloat(e);if(!isNaN(i)){if(i>=11)return"11";if(i>=10)return"10";if(i===6.3)return"8.1";if(i===6.2)return"8";if(i===6.1)return"7";if(i===6)return"Vista";if(i===5.1||i===5.2)return"XP";if(i===5)return"2000";if(i===4)return"NT 4.0"}}return e}detectDeviceDetails(e){try{let t=[[/(iphone)/i,["Apple","iPhone"]],[/(ipad)/i,["Apple","iPad"]],[/(ipod)/i,["Apple","iPod"]],[/(macintosh)/i,["Apple","Macintosh"]],[/(windows[\w\-_ ]*phone)/i,["Microsoft",0]],[/(windows nt|win64|win32|wow64)/i,["Microsoft","PC"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptxs]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?\d+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/smart-tv.+(samsung)/i,["Samsung","Smart TV"]],[/(samsung).*tizen/i,["Samsung","Smart TV"]],[/(pixel (?:c|tablet|[0-9a-z ]+))/i,["Google",1]],[/(pixelbook(?: go)?)/i,["Google",1]],[/nexus [0-9]/i,["Google",0]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[\w\-_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[\w ]*)(?: bui|\))/i,["Xiaomi",1]],[/\b(?:xiao)?mi[\w\-_ ]+pad/i,["Xiaomi",0]],[/(?:huawei|honor) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(?:one)?(?:plus)? ?([a\d0]\d\d\d?)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((?:gm|hd)19|(?:ac|be|in|kb)20|(?:d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/(oneplus)[-_ ]?([-\w]*)/i,["OnePlus",2]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/(realme)[-_ ]?([-\w]*)/i,["Realme",2]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/(oppo)[-_ ]?([-\w]*)/i,["OPPO",2]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/(vivo)[-_ ]?([-\w]*)/i,["Vivo",2]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",0]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",0]],[/droid.+; ([a-z]?\d[0-2]{2}[a-z]{2}|[c-g]\d{4}|so[-gl]\w+|xq-[a-z]{2}\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",0]],[/(sony)[-_ ]?([-\w]*)/i,["Sony",2]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",0]],[/(lg)[-_ ]?([-\w]*)/i,["LG",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))(?: bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/(?:asus[-_ ])?(zenfone[\w\-_ ]*)/i,["ASUS",1]],[/(rog[\w\-_ ]*)/i,["ASUS",1]],[/(asus)[-_ ]?([-\w]*)/i,["ASUS",2]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])(?: bui|;|\)|\/)/i,["Lenovo",1]],[/(thinkpad[\w\-_ ]*)/i,["Lenovo",0]],[/(kf[a-z]{2}[a-z]*)(?: bui|\))/i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/(fire[\w\-_ ]*)/i,["Amazon",0]],[/(amazon)[-_ ]?([-\w]*)/i,["Amazon",2]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(surface[\w\-_ ]*)/i,["Microsoft",0]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(alcatel|tcl)[-_ ]?([-\w]*)/i,[1,2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(panasonic)[-_ ]?([-\w]*)/i,["Panasonic",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(vertu)[-_ ]?([-\w]*)/i,["Vertu",2]],[/(gionee)[-_ ]?([-\w]*)/i,["Gionee",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(cubot)[-_ ]?([-\w]*)/i,["Cubot",2]],[/(umidigi)[-_ ]?([-\w]*)/i,["UMIDIGI",2]],[/(oukitel)[-_ ]?([-\w]*)/i,["Oukitel",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(land rover)[-_ ]?([-\w]*)/i,["Land Rover",2]],[/(shield[\w\-_ ]*)/i,["Nvidia",0]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*/i,["Roku",0]],[/(apple)[-_ ]?tv/i,["Apple","TV"]],[/(amazon)[-_ ]?tv/i,["Amazon","Fire TV"]],[/(google)[-_ ]?tv/i,["Google","TV"]],[/(smart[\w\-_ ]*tv)/i,[0,"Smart TV"]],[/(playstation[\w\-_ ]*)/i,["Sony",0]],[/(nintendo[\w\-_ ]*)/i,["Nintendo",0]],[/(xbox[\w\-_ ]*)/i,["Microsoft",0]],[/(googlebot)/i,["Google","Bot"]],[/(bingbot)/i,["Microsoft","Bing Bot"]],[/(yandexbot)/i,["Yandex","Bot"]],[/(slackbot)/i,["Slack","Bot"]],[/(twitterbot)/i,["Twitter","Bot"]],[/(facebookbot)/i,["Facebook","Bot"]],[/(linkedinbot)/i,["LinkedIn","Bot"]],[/(tesla)[-_ ]?([-\w]*)/i,["Tesla",2]],[/(raspberry[\w\-_ ]*)/i,["Raspberry Pi",0]]];for(let[i,r]of t){let s=e.match(i);if(s){let n=r[0],o=r[1],u=typeof n=="number"?s[n]!==void 0?this.normalizeVendorName(s[n]):"Unknown":this.normalizeVendorName(n),c="Unknown";typeof o=="number"?c=s[o]!==void 0?s[o]:"Unknown":o!==void 0?c=o:s[1]!==void 0?c=s[1]:s[0]!==void 0&&(c=s[0]),c=this.normalizeModelName(c,u),this.details.vendor=u,this.details.model=c;break}}}catch(t){console.error("DeviceChecker: device details detection error - ",t)}}normalizeVendorName(e){if(!e)return"Unknown";let t=e.toLowerCase();return{apple:"Apple",samsung:"Samsung",google:"Google",xiaomi:"Xiaomi",huawei:"Huawei",oneplus:"OnePlus",oppo:"OPPO",vivo:"Vivo",realme:"Realme",motorola:"Motorola",sony:"Sony",lg:"LG",nokia:"Nokia",asus:"ASUS",lenovo:"Lenovo",amazon:"Amazon",blackberry:"BlackBerry",microsoft:"Microsoft",zte:"ZTE",htc:"HTC",alcatel:"Alcatel",tcl:"TCL",meizu:"Meizu",tecno:"Tecno",infinix:"Infinix",micromax:"Micromax",lava:"Lava",panasonic:"Panasonic",sharp:"Sharp",benq:"BenQ",palm:"Palm",honor:"Honor",nvidia:"NVIDIA",roku:"Roku"}[t]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}normalizeModelName(e,t){if(!e||e==="Unknown")return e;if(e==="0")return"Unknown";let i=e.replace(/^build\//i,"").replace(/\s+bui$/i,"").replace(/\)$/,"").replace(/[;,)]/g,"").replace(/\s*\(.*?\)\s*/g,"").trim(),r=t.toLowerCase();return r.includes("samsung")?i=i.replace(/^(sm-|gt-|sgh-|sch-)/i,""):r.includes("xiaomi")?i=i.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,""):r.includes("oneplus")?i=i.replace(/^oneplus[\s\-_]*/i,""):r.includes("google")&&(i=i.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,"")),i=i.replace(/_/g," ").replace(/-/g," ").replace(/\s+/g," ").trim(),i?(i.length>0&&/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i):"Unknown"}detectIOSVersion(){try{let e=(0,ni.getWindow)();if(!(0,ni.isBrowserWindow)(e))return;if(this._highEntropyValues.platformVersion){let i=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(i);return}if(this._os.version!=="Unknown"){let i=this._os.version.split("."),r=i.length>=2?`${i[0]}.${i[1]}`:i[0];this._iosVersion=parseFloat(r);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t?.[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};var Zr=require("@vkontakte/videoplayer-shared"),js=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in(0,Zr.getWindow)()}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let e=(0,Zr.getWindow)();if(!(0,Zr.isBrowserWindow)(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r??0,this._isHdr=!!e.matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=i.colorDepth}catch(s){console.error(s)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(s){console.error(s)}}};var $i=require("@vkontakte/videoplayer-shared");var st=()=>window.ManagedMediaSource||window.MediaSource,cr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),zp=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Qs=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var nE=(0,$i.getWindow)().document?.createElement("video"),oE='video/mp4; codecs="avc1.42000a,mp4a.40.2"',uE='video/mp4; codecs="hev1.1.6.L93.B0"',Wp='video/webm; codecs="vp09.00.10.08"',Gp='video/webm; codecs="av01.0.00M.08"',cE='audio/mp4; codecs="mp4a.40.2"',lE='audio/webm; codecs="opus"',Yp,dE=async()=>{let a=(0,$i.getWindow)();if(!(0,$i.isBrowserWindow)(a))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Gp}}),a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Wp}})]);Yp={DASH_WEBM_AV1:t,DASH_WEBM:i}};dE().catch(a=>{console.log(nE),console.error(a)});var zs=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return Yp}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){let e=(0,$i.getWindow)();if(!(0,$i.isBrowserWindow)(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:cr(),mse:zp(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let i=!!st()?.isTypeSupported?.(oE),r=!!st()?.isTypeSupported?.(uE),s=!!st()?.isTypeSupported?.(cE);this._codecs={h264:i,h265:r,vp9:!!st()?.isTypeSupported?.(Wp),av1:!!st()?.isTypeSupported?.(Gp),aac:s,opus:!!st()?.isTypeSupported?.(lE),mpeg:(i||r)&&s},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(i){console.error(i)}try{this.destroyVideoElement()}catch(i){console.error("Error destroying video element:",i)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var Gs=require("@vkontakte/videoplayer-shared");var Kp="audio/mpeg",Ws=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=(0,Gs.getWindow)();if(!(0,Gs.isBrowserWindow)(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Kp)},this._codecs={mp3:!!st()?.isTypeSupported?.(Kp)}}catch(i){console.error(i)}try{this.destroyAudioElement()}catch(i){console.error("Error destroying audio element:",i)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};var uu=class{constructor(){this.isInited$=new Ys.ValueSubject(!1);this._displayChecker=new js,this._deviceChecker=new Hs(this._displayChecker),this._browserChecker=new Us,this._videoChecker=new zs(this._deviceChecker,this._browserChecker),this._audioChecker=new Ws,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){(0,Ys.isBrowserWindow)()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},F=new uu;var lu=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=F.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return(0,cu.assertNever)(o)}})},ea=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_FMP4":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,cu.assertNever)(a)}},Xp=a=>{let t=Object.keys(a).filter(i=>!ea(i));return lu(t).length>0};var ta=class{constructor(e){this.subscription=new ee.Subscription;this.sessionId$=new ee.ValueSubject(null);this.mediaSessionId$=new ee.ValueSubject(null);this.contentId$=new ee.ValueSubject(null);this.isMobile=si();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if((0,ee.isNullable)(e))return;this.media=e,this.mediaSessionId$.next(e.mediaSessionId??null);let t=e.media?.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=e.media?.duration;(0,ee.isNonNullable)(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if((0,ee.isNonNullable)(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let n=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!n?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new qs(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ea(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:ee.ErrorCategory.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe((0,ee.filter)(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe((0,ee.filter)(ee.isNonNullable),(0,ee.filterChanged)(),(0,ee.debounce)(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe((0,ee.filterChanged)(),(0,ee.map)(Boolean));this.subscription.add((0,ee.combine)({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe((0,ee.filter)(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=(0,ee.combine)({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe((0,ee.filter)(({mediaLoaded:r})=>r),(0,ee.debounce)(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe((0,ee.filter)(({mediaLoaded:r,playbackState:{from:s,to:n}})=>!r&&s==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add((0,ee.combine)({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe((0,ee.debounce)(30)),mediaLoaded:t}).pipe((0,ee.filter)(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:s,volume:n}=r.to;this.setVolume(n,s)},e))}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let t=e.message?.media?.[0];this.syncMediaState(t);let i=e.message?.receiver.volume;this.syncVolumeState(i)}break;case"v2_message":{switch(e.message?.type){case"MEDIA_STATUS":{let t=e.message?.status?.[0];this.syncMediaState(t);break}}break}}}loadMedia(){let e=Fs(this.params),t=this.media?.currentTime,i=this.params.desiredState.seekState.getState(),r=t??(i.state!=="none"?i.position/1e3:0),n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();(0,ee.assertNonNullable)(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();(0,ee.assertNonNullable)(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();(0,ee.assertNonNullable)(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":L(this.params.desiredState.playbackState,"paused");break;case"PLAYING":L(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),L(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):L(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if((0,ee.isNullable)(e))return;let{level:t,muted:i}=e,r={muted:i??!1,volume:t??0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let s=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,s+=`, volume passed to state machine: ${r.volume}`),this.log({message:s}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};var ce=require("@vkontakte/videoplayer-shared");var Jp=a=>({castDevice:{friendlyName:a},remotePlayer:{},remotePlayerController:{},session:{}}),Zp=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var ia=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new ce.ValueSubject(null);this.sessionId$=new ce.ValueSubject(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new ce.Subscription;this.subscriptionEvents=new ce.Subscription;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new ce.ValueSubject(!1);this.presentationConnection$=new ce.ValueSubject(null);this.message$=new ce.ValueSubject(null);this.friendlyName$=new ce.ValueSubject(null);this.errorEvent$=new ce.Subject;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let s=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add((0,ce.fromEvent)(r,"change").subscribe(()=>{s()})),s()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();(0,ce.assertNonNullable)(e,"connect with null presentationRequest");let t=await e.start();this.handleConnection(t)}catch(e){switch(e?.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:ce.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add((0,ce.fromEvent)(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe((0,ce.tap)(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),(0,ce.filter)(e=>!!e)).subscribe(e=>{let t=(0,ce.fromEvent)(e,"message").subscribe(s=>{let n=JSON.parse(s.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${s.data}`}),this.handleMessage(n),this.message$.next(n))}),i=(0,ce.fromEvent)(e,"connect").subscribe(()=>{this.send("client_connect")}),r=(0,ce.fromEvent)(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:ce.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:s});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();t?.state==="connected"&&t?.send(e)}catch(t){this.errorEvent$.next({category:ce.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":e.message?.action==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||Zp()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new ce.Subscription}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};var Ne=require("@vkontakte/videoplayer-shared");var Ht=class a{constructor(e){this.subscription=new Ne.Subscription;this.connection$=new Ne.ValueSubject(void 0);this.castState$=new Ne.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new Ne.Subject;let t=a.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new ia({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){(0,Ne.assertNonNullable)(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=(0,Ne.combine)({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe((0,Ne.filterChanged)())});this.subscription.add(e.pipe((0,Ne.map)(({connection:t,friendlyName:i})=>!!(t&&i)),(0,Ne.filterChanged)()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?Jp(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){this.log({message:"connect"}),this.chromecastConnector?.connect()}disconnect(){this.log({message:"disconnect"}),this.chromecastConnector?.disconnect()}async stopMedia(){this.log({message:"stopMedia"}),this.chromecastConnector?.stopMedia()}toggleConnection(){let e=!!this.chromecastConnector?.presentationConnection$.getValue();this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){this.log({message:"destroy"}),this.chromecastConnector?.destroy(),this.subscription.unsubscribe()}};var vl=j(Ge(),1),Sl=j(oi(),1),OS=j(Cu(),1);var Lb=j(vc(),1);var Bt=require("@vkontakte/videoplayer-shared"),Z=class{constructor(e){this.transitionStarted$=new Bt.Subject;this.transitionEnded$=new Bt.Subject;this.transitionUpdated$=new Bt.Subject;this.forceChanged$=new Bt.Subject;this.stateChangeStarted$=(0,Bt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Bt.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,Bt.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 se=require("@vkontakte/videoplayer-shared");var Xk=5,Jk=5,Zk=500,Cb=7e3,fa=class{constructor(e){this.subscription=new se.Subscription;this.loadMediaTimeoutSubscription=new se.Subscription;this.videoState=new Z("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?.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,se.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,se.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,se.assertNever)(e)}break}default:(0,se.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(ea(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 se.Subscription;this.subscription.add(e),this.subscription.add((0,se.merge)(this.videoState.stateChangeStarted$.pipe((0,se.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,se.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 se.Subject;e.add(r.pipe((0,se.debounce)(Zk)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,se.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)>Xk)&&r.next(o),s=o})),e.add((0,se.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,se.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,se.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,se.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<Jk&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),L(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,se.assertNever)(n)}}),t((0,se.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,se.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,se.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,se.observableFrom)(["init"])).pipe((0,se.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"),L(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),L(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=Fs(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),L(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&L(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??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()}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,se.timeout)(Cb).subscribe(()=>s(`timeout(${Cb})`)))});(0,Lb.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:se.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Lc=j(Ge(),1);var ba=require("@vkontakte/videoplayer-shared");var Db=require("@vkontakte/videoplayer-shared"),Bb=a=>{try{a.pause(),a.playbackRate=0,(0,Db.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var In=require("@vkontakte/videoplayer-shared"),Sc=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)}},Tn=(0,ba.getWindow)(),yc=Tn.WeakMap?new Tn.WeakMap:new Sc,Tc=Tn.WeakMap?new Tn.WeakMap:new Map,eA=(a,e=20)=>{let t=0;return(0,In.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ye=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?(0,ba.clearVideoElement)(i):(i=document.createElement("video"),a.appendChild(i)),yc.set(i,r);let s=new In.Subscription;return s.add(eA(i,e)),Tc.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ke=a=>{Tc.get(a)?.unsubscribe(),Tc.delete(a);let t=yc.get(a);yc.delete(a),t?(0,ba.clearVideoElement)(a):Bb(a)};var Ic=j(Mi(),1),H=require("@vkontakte/videoplayer-shared");var ci=require("@vkontakte/videoplayer-shared"),En=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,ci.isNullable)(r),c=new ci.Subscription;return r&&c.add(r.subscribe(d=>{let l=a.getState();i(d,l)&&a.setState(d)},s)),i(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),c},Vt=(a,e,t)=>En(e,()=>a.loop,i=>{(0,ci.isNonNullable)(i)&&(a.loop=i)},{onError:t}),Xe=(a,e,t,i)=>En(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,ci.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),pt=(a,e,t,i)=>En(e,()=>a.playbackRate,r=>{(0,ci.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),ga=En;var tA=a=>["__",a.language,a.label].join("|"),iA=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Ec=class a{constructor(e){this.available$=new H.Subject;this.current$=new H.ValueSubject(void 0);this.error$=new H.Subject;this.subscription=new H.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:H.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(ga(t.internalTextTracks,()=>(0,Ic.default)(this.internalTracks),s=>{(0,H.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,H.isNonNullable)(s)&&(0,H.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,H.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ga(t.externalTextTracks,()=>(0,Ic.default)(this.externalTracks),s=>{(0,H.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,H.isNonNullable)(s)&&(0,H.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,H.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ga(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(ga(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,H.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,H.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,H.merge)((0,H.fromEvent)(e,"addtrack"),(0,H.fromEvent)(e,"removetrack"),(0,H.observableFrom)(["init"])).pipe((0,H.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,H.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,H.merge)((0,H.fromEvent)(e,"change"),(0,H.observableFrom)(["init"])).pipe((0,H.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,H.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,H.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,H.fromEvent)(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add((0,H.fromEvent)(e,"removetrack").subscribe(i=>{i.track?.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,H.isNonNullable)(t.align)&&(r.align=t.align),(0,H.isNonNullable)(t.position)&&(r.position=t.position),(0,H.isNonNullable)(t.size)&&(r.size=t.size),(0,H.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,H.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:tA(e),s=this.externalTracks.has(r),n=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.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,H.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,H.isNullable)(e)||!iA(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,H.assertNonNullable)(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):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,H.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)}},ht=Ec;var _i=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 Vb=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},wc=a=>{let e=Vb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},_b=a=>{let e=Vb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var R=require("@vkontakte/videoplayer-shared");var rA=3,Ob=(a,e,t=rA)=>{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 Je=a=>{let e=C=>(0,R.fromEvent)(a,C).pipe((0,R.mapTo)(void 0),(0,R.shareReplay)(1)),t=new R.Subscription,i=()=>t.unsubscribe(),r=(0,R.merge)((0,R.fromEvent)(a,"progress"),(0,R.fromEvent)(a,"timeupdate")).pipe((0,R.map)(()=>Ob(a.buffered,a.currentTime)),(0,R.shareReplay)(1)),s=F.browser.isSafari?(0,R.combine)({play:e("play").pipe((0,R.once)()),playing:e("playing")}).pipe((0,R.mapTo)(void 0),(0,R.shareReplay)(1)):e("playing"),n=(0,R.fromEvent)(a,"volumechange").pipe((0,R.map)(()=>({muted:a.muted,volume:a.volume})),(0,R.shareReplay)(1)),o=(0,R.fromEvent)(a,"ratechange").pipe((0,R.map)(()=>a.playbackRate),(0,R.shareReplay)(1)),u=(0,R.fromEvent)(a,"error").pipe((0,R.filter)(()=>!!(a.error||a.played.length)),(0,R.map)(()=>{let C=a.error;return{id:C?`MediaError#${C.code}`:"HtmlVideoError",category:R.ErrorCategory.VIDEO_PIPELINE,message:C?C.message:"Error event from HTML video element",thrown:a.error??void 0}}),(0,R.shareReplay)(1)),c=(0,R.fromEvent)(a,"timeupdate").pipe((0,R.map)(()=>a.currentTime),(0,R.shareReplay)(1)),d=["waiting","seeking","seeked","timeupdate"],l=new R.Subject,p=.3,m;t.add((0,R.merge)(...d.map(C=>(0,R.fromEvent)(a,C))).subscribe(C=>{let re=a.currentTime;a.loop&&(0,R.isNonNullable)(m)&&(0,R.isNonNullable)(re)&&m>=a.duration-p&&re<=p&&l.next(m),m=re}));let f=e("pause").pipe((0,R.filter)(()=>!a.error&&m!==a.duration),(0,R.shareReplay)(1)),g=(0,R.fromEvent)(a,"enterpictureinpicture").pipe((0,R.shareReplay)(1)),v=(0,R.fromEvent)(a,"leavepictureinpicture").pipe((0,R.shareReplay)(1)),S=new R.ValueSubject(_b(a));t.add(g.subscribe(()=>S.next(!0))),t.add(v.subscribe(()=>S.next(!1)));let E=new R.ValueSubject(wc(a)),A=(0,R.fromEvent)(a,"fullscreenchange").pipe((0,R.shareReplay)(1));t.add(A.pipe((0,R.map)(()=>wc(a))).subscribe(E));let w=.1,D=1e3,N=(0,R.fromEvent)(a,"timeupdate").pipe((0,R.map)(C=>a.duration-a.currentTime<w),(0,R.filterChanged)(),(0,R.shareReplay)(1)),U=(0,R.merge)(N.pipe((0,R.filter)(C=>!a.loop&&C)),(0,R.fromEvent)(a,"ended")).pipe((0,R.throttle)(D),(0,R.mapTo)(void 0),(0,R.shareReplay)(1)),Q=(0,R.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(C=>(0,R.fromEvent)(a,C)),N.pipe((0,R.map)(C=>({type:C?"ended":"unknown"})))).pipe((0,R.map)(C=>F.browser.isFirefox&&C.type==="ended"?a.readyState<2:a.readyState<3),(0,R.filterChanged)(),(0,R.shareReplay)(1));return{playing$:s,pause$:f,canplay$:e("canplay"),ended$:U,looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,R.fromEvent)(a,"durationchange").pipe((0,R.map)(()=>a.duration),(0,R.shareReplay)(1)),isBuffering$:Q,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:E,enterPip$:g,leavePip$:v,destroy:i}};var Qt=require("@vkontakte/videoplayer-shared"),li=a=>{switch(a){case"mobile":return Qt.VideoQuality.Q_144P;case"lowest":return Qt.VideoQuality.Q_240P;case"low":return Qt.VideoQuality.Q_360P;case"sd":case"medium":return Qt.VideoQuality.Q_480P;case"hd":case"high":return Qt.VideoQuality.Q_720P;case"fullhd":case"full":return Qt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Qt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Qt.VideoQuality.Q_2160P}};var je=j(mt(),1),Pc=j(Ge(),1),Oi=j(oi(),1),$=require("@vkontakte/videoplayer-shared");var xc=!1,zt={},Qb=a=>{xc=a},zb=()=>{zt={}},Wb=a=>{a(zt)},va=(a,e)=>{xc&&(zt.meta=zt.meta??{},zt.meta[a]=e)},He=class{constructor(e){this.name=e}next(e){if(!xc)return;zt.series=zt.series??{};let t=zt.series[this.name]??[];t.push([Date.now(),e]),zt.series[this.name]=t}};var we=require("@vkontakte/videoplayer-shared");function Gb(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Sr(a,e,t){return(0,we.isNullable)(a)||(0,we.isNonNullable)(a.min)&&(0,we.isNonNullable)(a.max)&&(0,we.isLower)(a.max,a.min)||(0,we.isNonNullable)(a.min)&&e&&(0,we.isHigher)(a.min,e)||(0,we.isNonNullable)(a.max)&&t&&(0,we.isLower)(a.max,t)}function Yb({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Sr({max:a?.max?(0,we.videoHeightToQuality)(a.max):void 0,min:a?.min?(0,we.videoHeightToQuality)(a.min):void 0},e?(0,we.videoHeightToQuality)(e):void 0,t?(0,we.videoHeightToQuality)(t):void 0)}var eg=new He("best_bitrate"),xn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var yr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),di=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,$.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Pn='Assertion "ABR Tracks is empty array" failed',wn=new WeakMap,Kb=new WeakMap,Xb=new WeakMap,Sa=(a,e,t,i)=>{let r=[...e].sort(yr(1)),s=[...t].sort(yr(1)),n=s.filter(u=>(0,$.isNonNullable)(u.bitrate)&&(0,$.isNonNullable)(a.bitrate)?a.bitrate/u.bitrate>i:!0),o=(0,je.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,je.default)(s,-1);return o&&(0,Pc.default)(n,o)?o:n.length?(0,je.default)(n,-1):(0,je.default)(s,0)},ya=(a,e,t,i)=>{let r=wn.get(e);r||(r=[...e].sort(yr(1)),wn.set(e,r));let s=wn.get(t);s||(s=[...t].sort(yr(1)),wn.set(t,s));let n=Xb.get(a);n||(n=s.filter(u=>(0,$.isNonNullable)(u.bitrate)&&(0,$.isNonNullable)(a.bitrate)?a.bitrate/u.bitrate>i:!0),Xb.set(a,n));let o=(0,je.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,je.default)(s,-1);return o&&(0,Pc.default)(n,o)?o:n.length?(0,je.default)(n,-1):(0,je.default)(s,0)},Jb=a=>"quality"in a,kn=(a,e,t,i)=>{let r=(0,$.isNonNullable)(i?.last?.bitrate)&&(0,$.isNonNullable)(t?.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,$.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let o=Jb(n)?"video":"audio",u=Jb(n)?n.quality:n.bitrate;return e({message:`
6
+ "use strict";var iy=Object.create;var ks=Object.defineProperty;var ry=Object.getOwnPropertyDescriptor;var ay=Object.getOwnPropertyNames;var sy=Object.getPrototypeOf,ny=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),oy=(a,e)=>{for(var t in e)ks(a,t,{get:e[t],enumerable:!0})},xl=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ay(e))!ny.call(a,r)&&r!==t&&ks(a,r,{get:()=>e[r],enumerable:!(i=ry(e,r))||i.enumerable});return a};var j=(a,e,t)=>(t=a!=null?iy(sy(a)):{},xl(e||!a||!a.__esModule?ks(t,"default",{value:a,enumerable:!0}):t,a)),uy=a=>xl(ks({},"__esModule",{value:!0}),a);var Te=b((xo,Pl)=>{"use strict";var qr=function(a){return a&&a.Math===Math&&a};Pl.exports=qr(typeof globalThis=="object"&&globalThis)||qr(typeof window=="object"&&window)||qr(typeof self=="object"&&self)||qr(typeof global=="object"&&global)||qr(typeof xo=="object"&&xo)||function(){return this}()||Function("return this")()});var Ae=b((i$,kl)=>{"use strict";kl.exports=function(a){try{return!!a()}catch{return!0}}});var Ur=b((r$,Al)=>{"use strict";var cy=Ae();Al.exports=!cy(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Po=b((a$,Cl)=>{"use strict";var ly=Ur(),$l=Function.prototype,Rl=$l.apply,Ml=$l.call;Cl.exports=typeof Reflect=="object"&&Reflect.apply||(ly?Ml.bind(Rl):function(){return Ml.apply(Rl,arguments)})});var Re=b((s$,Bl)=>{"use strict";var Ll=Ur(),Dl=Function.prototype,ko=Dl.call,dy=Ll&&Dl.bind.bind(ko,ko);Bl.exports=Ll?dy:function(a){return function(){return ko.apply(a,arguments)}}});var xi=b((n$,_l)=>{"use strict";var Vl=Re(),py=Vl({}.toString),hy=Vl("".slice);_l.exports=function(a){return hy(py(a),8,-1)}});var Ao=b((o$,Ol)=>{"use strict";var my=xi(),fy=Re();Ol.exports=function(a){if(my(a)==="Function")return fy(a)}});var Ie=b((u$,Nl)=>{"use strict";var Ro=typeof document=="object"&&document.all;Nl.exports=typeof Ro>"u"&&Ro!==void 0?function(a){return typeof a=="function"||a===Ro}:function(a){return typeof a=="function"}});var rt=b((c$,Fl)=>{"use strict";var by=Ae();Fl.exports=!by(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var at=b((l$,ql)=>{"use strict";var gy=Ur(),Ms=Function.prototype.call;ql.exports=gy?Ms.bind(Ms):function(){return Ms.apply(Ms,arguments)}});var Mo=b(jl=>{"use strict";var Ul={}.propertyIsEnumerable,Hl=Object.getOwnPropertyDescriptor,vy=Hl&&!Ul.call({1:2},1);jl.f=vy?function(e){var t=Hl(this,e);return!!t&&t.enumerable}:Ul});var Hr=b((p$,Ql)=>{"use strict";Ql.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Wl=b((h$,zl)=>{"use strict";var Sy=Re(),yy=Ae(),Ty=xi(),$o=Object,Iy=Sy("".split);zl.exports=yy(function(){return!$o("z").propertyIsEnumerable(0)})?function(a){return Ty(a)==="String"?Iy(a,""):$o(a)}:$o});var jr=b((m$,Gl)=>{"use strict";Gl.exports=function(a){return a==null}});var ri=b((f$,Yl)=>{"use strict";var Ey=jr(),wy=TypeError;Yl.exports=function(a){if(Ey(a))throw new wy("Can't call method on "+a);return a}});var Pi=b((b$,Kl)=>{"use strict";var xy=Wl(),Py=ri();Kl.exports=function(a){return xy(Py(a))}});var We=b((g$,Xl)=>{"use strict";var ky=Ie();Xl.exports=function(a){return typeof a=="object"?a!==null:ky(a)}});var ki=b((v$,Jl)=>{"use strict";Jl.exports={}});var Ut=b((S$,ed)=>{"use strict";var Co=ki(),Lo=Te(),Ay=Ie(),Zl=function(a){return Ay(a)?a:void 0};ed.exports=function(a,e){return arguments.length<2?Zl(Co[a])||Zl(Lo[a]):Co[a]&&Co[a][e]||Lo[a]&&Lo[a][e]}});var Qr=b((y$,td)=>{"use strict";var Ry=Re();td.exports=Ry({}.isPrototypeOf)});var Ai=b((T$,ad)=>{"use strict";var My=Te(),id=My.navigator,rd=id&&id.userAgent;ad.exports=rd?String(rd):""});var Bo=b((I$,ld)=>{"use strict";var cd=Te(),Do=Ai(),sd=cd.process,nd=cd.Deno,od=sd&&sd.versions||nd&&nd.version,ud=od&&od.v8,It,$s;ud&&(It=ud.split("."),$s=It[0]>0&&It[0]<4?1:+(It[0]+It[1]));!$s&&Do&&(It=Do.match(/Edge\/(\d+)/),(!It||It[1]>=74)&&(It=Do.match(/Chrome\/(\d+)/),It&&($s=+It[1])));ld.exports=$s});var Vo=b((E$,pd)=>{"use strict";var dd=Bo(),$y=Ae(),Cy=Te(),Ly=Cy.String;pd.exports=!!Object.getOwnPropertySymbols&&!$y(function(){var a=Symbol("symbol detection");return!Ly(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&dd&&dd<41})});var _o=b((w$,hd)=>{"use strict";var Dy=Vo();hd.exports=Dy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Oo=b((x$,md)=>{"use strict";var By=Ut(),Vy=Ie(),_y=Qr(),Oy=_o(),Ny=Object;md.exports=Oy?function(a){return typeof a=="symbol"}:function(a){var e=By("Symbol");return Vy(e)&&_y(e.prototype,Ny(a))}});var zr=b((P$,fd)=>{"use strict";var Fy=String;fd.exports=function(a){try{return Fy(a)}catch{return"Object"}}});var Ct=b((k$,bd)=>{"use strict";var qy=Ie(),Uy=zr(),Hy=TypeError;bd.exports=function(a){if(qy(a))return a;throw new Hy(Uy(a)+" is not a function")}});var Wr=b((A$,gd)=>{"use strict";var jy=Ct(),Qy=jr();gd.exports=function(a,e){var t=a[e];return Qy(t)?void 0:jy(t)}});var Sd=b((R$,vd)=>{"use strict";var No=at(),Fo=Ie(),qo=We(),zy=TypeError;vd.exports=function(a,e){var t,i;if(e==="string"&&Fo(t=a.toString)&&!qo(i=No(t,a))||Fo(t=a.valueOf)&&!qo(i=No(t,a))||e!=="string"&&Fo(t=a.toString)&&!qo(i=No(t,a)))return i;throw new zy("Can't convert object to primitive value")}});var Et=b((M$,yd)=>{"use strict";yd.exports=!0});var Ed=b(($$,Id)=>{"use strict";var Td=Te(),Wy=Object.defineProperty;Id.exports=function(a,e){try{Wy(Td,a,{value:e,configurable:!0,writable:!0})}catch{Td[a]=e}return e}});var Gr=b((C$,Pd)=>{"use strict";var Gy=Et(),Yy=Te(),Ky=Ed(),wd="__core-js_shared__",xd=Pd.exports=Yy[wd]||Ky(wd,{});(xd.versions||(xd.versions=[])).push({version:"3.43.0",mode:Gy?"pure":"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Uo=b((L$,Ad)=>{"use strict";var kd=Gr();Ad.exports=function(a,e){return kd[a]||(kd[a]=e||{})}});var ir=b((D$,Rd)=>{"use strict";var Xy=ri(),Jy=Object;Rd.exports=function(a){return Jy(Xy(a))}});var wt=b((B$,Md)=>{"use strict";var Zy=Re(),eT=ir(),tT=Zy({}.hasOwnProperty);Md.exports=Object.hasOwn||function(e,t){return tT(eT(e),t)}});var Ho=b((V$,$d)=>{"use strict";var iT=Re(),rT=0,aT=Math.random(),sT=iT(1.1.toString);$d.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+sT(++rT+aT,36)}});var _e=b((_$,Ld)=>{"use strict";var nT=Te(),oT=Uo(),Cd=wt(),uT=Ho(),cT=Vo(),lT=_o(),rr=nT.Symbol,jo=oT("wks"),dT=lT?rr.for||rr:rr&&rr.withoutSetter||uT;Ld.exports=function(a){return Cd(jo,a)||(jo[a]=cT&&Cd(rr,a)?rr[a]:dT("Symbol."+a)),jo[a]}});var _d=b((O$,Vd)=>{"use strict";var pT=at(),Dd=We(),Bd=Oo(),hT=Wr(),mT=Sd(),fT=_e(),bT=TypeError,gT=fT("toPrimitive");Vd.exports=function(a,e){if(!Dd(a)||Bd(a))return a;var t=hT(a,gT),i;if(t){if(e===void 0&&(e="default"),i=pT(t,a,e),!Dd(i)||Bd(i))return i;throw new bT("Can't convert object to primitive value")}return e===void 0&&(e="number"),mT(a,e)}});var Qo=b((N$,Od)=>{"use strict";var vT=_d(),ST=Oo();Od.exports=function(a){var e=vT(a,"string");return ST(e)?e:e+""}});var Cs=b((F$,Fd)=>{"use strict";var yT=Te(),Nd=We(),zo=yT.document,TT=Nd(zo)&&Nd(zo.createElement);Fd.exports=function(a){return TT?zo.createElement(a):{}}});var Wo=b((q$,qd)=>{"use strict";var IT=rt(),ET=Ae(),wT=Cs();qd.exports=!IT&&!ET(function(){return Object.defineProperty(wT("div"),"a",{get:function(){return 7}}).a!==7})});var jd=b(Hd=>{"use strict";var xT=rt(),PT=at(),kT=Mo(),AT=Hr(),RT=Pi(),MT=Qo(),$T=wt(),CT=Wo(),Ud=Object.getOwnPropertyDescriptor;Hd.f=xT?Ud:function(e,t){if(e=RT(e),t=MT(t),CT)try{return Ud(e,t)}catch{}if($T(e,t))return AT(!PT(kT.f,e,t),e[t])}});var Go=b((H$,Qd)=>{"use strict";var LT=Ae(),DT=Ie(),BT=/#|\.prototype\./,Yr=function(a,e){var t=_T[VT(a)];return t===NT?!0:t===OT?!1:DT(e)?LT(e):!!e},VT=Yr.normalize=function(a){return String(a).replace(BT,".").toLowerCase()},_T=Yr.data={},OT=Yr.NATIVE="N",NT=Yr.POLYFILL="P";Qd.exports=Yr});var ar=b((j$,Wd)=>{"use strict";var zd=Ao(),FT=Ct(),qT=Ur(),UT=zd(zd.bind);Wd.exports=function(a,e){return FT(a),e===void 0?a:qT?UT(a,e):function(){return a.apply(e,arguments)}}});var Yo=b((Q$,Gd)=>{"use strict";var HT=rt(),jT=Ae();Gd.exports=HT&&jT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Lt=b((z$,Yd)=>{"use strict";var QT=We(),zT=String,WT=TypeError;Yd.exports=function(a){if(QT(a))return a;throw new WT(zT(a)+" is not an object")}});var Ri=b(Xd=>{"use strict";var GT=rt(),YT=Wo(),KT=Yo(),Ls=Lt(),Kd=Qo(),XT=TypeError,Ko=Object.defineProperty,JT=Object.getOwnPropertyDescriptor,Xo="enumerable",Jo="configurable",Zo="writable";Xd.f=GT?KT?function(e,t,i){if(Ls(e),t=Kd(t),Ls(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Zo in i&&!i[Zo]){var r=JT(e,t);r&&r[Zo]&&(e[t]=i.value,i={configurable:Jo in i?i[Jo]:r[Jo],enumerable:Xo in i?i[Xo]:r[Xo],writable:!1})}return Ko(e,t,i)}:Ko:function(e,t,i){if(Ls(e),t=Kd(t),Ls(i),YT)try{return Ko(e,t,i)}catch{}if("get"in i||"set"in i)throw new XT("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var sr=b((G$,Jd)=>{"use strict";var ZT=rt(),eI=Ri(),tI=Hr();Jd.exports=ZT?function(a,e,t){return eI.f(a,e,tI(1,t))}:function(a,e,t){return a[e]=t,a}});var Ee=b((Y$,ep)=>{"use strict";var Kr=Te(),iI=Po(),rI=Ao(),aI=Ie(),sI=jd().f,nI=Go(),nr=ki(),oI=ar(),or=sr(),Zd=wt();Gr();var uI=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 iI(a,this,arguments)};return e.prototype=a.prototype,e};ep.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?Kr:r?Kr[t]:Kr[t]&&Kr[t].prototype,o=i?nr:nr[t]||or(nr,t,{})[t],u=o.prototype,c,d,l,p,m,f,g,v,S;for(p in e)c=nI(i?p:t+(r?".":"#")+p,a.forced),d=!c&&n&&Zd(n,p),f=o[p],d&&(a.dontCallGetSet?(S=sI(n,p),g=S&&S.value):g=n[p]),m=d&&g?g:e[p],!(!c&&!s&&typeof f==typeof m)&&(a.bind&&d?v=oI(m,Kr):a.wrap&&d?v=uI(m):s&&aI(m)?v=rI(m):v=m,(a.sham||m&&m.sham||f&&f.sham)&&or(v,"sham",!0),or(o,p,v),s&&(l=t+"Prototype",Zd(nr,l)||or(nr,l,{}),or(nr[l],p,m),a.real&&u&&(c||!u[p])&&or(u,p,m)))}});var Ds=b((K$,ip)=>{"use strict";var cI=Uo(),lI=Ho(),tp=cI("keys");ip.exports=function(a){return tp[a]||(tp[a]=lI(a))}});var ap=b((X$,rp)=>{"use strict";var dI=Ae();rp.exports=!dI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Bs=b((J$,np)=>{"use strict";var pI=wt(),hI=Ie(),mI=ir(),fI=Ds(),bI=ap(),sp=fI("IE_PROTO"),eu=Object,gI=eu.prototype;np.exports=bI?eu.getPrototypeOf:function(a){var e=mI(a);if(pI(e,sp))return e[sp];var t=e.constructor;return hI(t)&&e instanceof t?t.prototype:e instanceof eu?gI:null}});var up=b((Z$,op)=>{"use strict";var vI=Math.ceil,SI=Math.floor;op.exports=Math.trunc||function(e){var t=+e;return(t>0?SI:vI)(t)}});var Xr=b((eC,cp)=>{"use strict";var yI=up();cp.exports=function(a){var e=+a;return e!==e||e===0?0:yI(e)}});var dp=b((tC,lp)=>{"use strict";var TI=Xr(),II=Math.max,EI=Math.min;lp.exports=function(a,e){var t=TI(a);return t<0?II(t+e,0):EI(t,e)}});var tu=b((iC,pp)=>{"use strict";var wI=Xr(),xI=Math.min;pp.exports=function(a){var e=wI(a);return e>0?xI(e,9007199254740991):0}});var ur=b((rC,hp)=>{"use strict";var PI=tu();hp.exports=function(a){return PI(a.length)}});var iu=b((aC,fp)=>{"use strict";var kI=Pi(),AI=dp(),RI=ur(),mp=function(a){return function(e,t,i){var r=kI(e),s=RI(r);if(s===0)return!a&&-1;var n=AI(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}};fp.exports={includes:mp(!0),indexOf:mp(!1)}});var Vs=b((sC,bp)=>{"use strict";bp.exports={}});var Sp=b((nC,vp)=>{"use strict";var MI=Re(),ru=wt(),$I=Pi(),CI=iu().indexOf,LI=Vs(),gp=MI([].push);vp.exports=function(a,e){var t=$I(a),i=0,r=[],s;for(s in t)!ru(LI,s)&&ru(t,s)&&gp(r,s);for(;e.length>i;)ru(t,s=e[i++])&&(~CI(r,s)||gp(r,s));return r}});var au=b((oC,yp)=>{"use strict";yp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var su=b((uC,Tp)=>{"use strict";var DI=Sp(),BI=au();Tp.exports=Object.keys||function(e){return DI(e,BI)}});var nu=b((cC,Pp)=>{"use strict";var Ep=rt(),VI=Ae(),wp=Re(),_I=Bs(),OI=su(),NI=Pi(),FI=Mo().f,xp=wp(FI),qI=wp([].push),UI=Ep&&VI(function(){var a=Object.create(null);return a[2]=2,!xp(a,2)}),Ip=function(a){return function(e){for(var t=NI(e),i=OI(t),r=UI&&_I(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Ep||(r?u in t:xp(t,u)))&&qI(o,a?[u,t[u]]:t[u]);return o}};Pp.exports={entries:Ip(!0),values:Ip(!1)}});var kp=b(()=>{"use strict";var HI=Ee(),jI=nu().values;HI({target:"Object",stat:!0},{values:function(e){return jI(e)}})});var Rp=b((pC,Ap)=>{"use strict";kp();var QI=ki();Ap.exports=QI.Object.values});var $p=b((hC,Mp)=>{"use strict";var zI=Rp();Mp.exports=zI});var Mi=b((mC,Cp)=>{"use strict";var WI=$p();Cp.exports=WI});var Jr=b((fC,Lp)=>{"use strict";Lp.exports=function(){}});var Dp=b(()=>{"use strict";var GI=Ee(),YI=iu().includes,KI=Ae(),XI=Jr(),JI=KI(function(){return!Array(1).includes()});GI({target:"Array",proto:!0,forced:JI},{includes:function(e){return YI(this,e,arguments.length>1?arguments[1]:void 0)}});XI("includes")});var ai=b((vC,Bp)=>{"use strict";var ZI=Ut();Bp.exports=ZI});var _p=b((SC,Vp)=>{"use strict";Dp();var eE=ai();Vp.exports=eE("Array","includes")});var Np=b((yC,Op)=>{"use strict";var tE=_p();Op.exports=tE});var Ge=b((TC,Fp)=>{"use strict";var iE=Np();Fp.exports=iE});var eh=b(()=>{"use strict";var pE=Ee(),hE=nu().entries;pE({target:"Object",stat:!0},{entries:function(e){return hE(e)}})});var ih=b((uD,th)=>{"use strict";eh();var mE=ki();th.exports=mE.Object.entries});var ah=b((cD,rh)=>{"use strict";var fE=ih();rh.exports=fE});var oi=b((lD,sh)=>{"use strict";var bE=ah();sh.exports=bE});var Ci=b((dD,nh)=>{"use strict";nh.exports={}});var ch=b((pD,uh)=>{"use strict";var gE=Te(),vE=Ie(),oh=gE.WeakMap;uh.exports=vE(oh)&&/native code/.test(String(oh))});var mu=b((hD,ph)=>{"use strict";var SE=ch(),dh=Te(),yE=We(),TE=sr(),du=wt(),pu=Gr(),IE=Ds(),EE=Vs(),lh="Object already initialized",hu=dh.TypeError,wE=dh.WeakMap,Ks,ra,Xs,xE=function(a){return Xs(a)?ra(a):Ks(a,{})},PE=function(a){return function(e){var t;if(!yE(e)||(t=ra(e)).type!==a)throw new hu("Incompatible receiver, "+a+" required");return t}};SE||pu.state?(xt=pu.state||(pu.state=new wE),xt.get=xt.get,xt.has=xt.has,xt.set=xt.set,Ks=function(a,e){if(xt.has(a))throw new hu(lh);return e.facade=a,xt.set(a,e),e},ra=function(a){return xt.get(a)||{}},Xs=function(a){return xt.has(a)}):(Li=IE("state"),EE[Li]=!0,Ks=function(a,e){if(du(a,Li))throw new hu(lh);return e.facade=a,TE(a,Li,e),e},ra=function(a){return du(a,Li)?a[Li]:{}},Xs=function(a){return du(a,Li)});var xt,Li;ph.exports={set:Ks,get:ra,has:Xs,enforce:xE,getterFor:PE}});var gu=b((mD,mh)=>{"use strict";var fu=rt(),kE=wt(),hh=Function.prototype,AE=fu&&Object.getOwnPropertyDescriptor,bu=kE(hh,"name"),RE=bu&&function(){}.name==="something",ME=bu&&(!fu||fu&&AE(hh,"name").configurable);mh.exports={EXISTS:bu,PROPER:RE,CONFIGURABLE:ME}});var bh=b(fh=>{"use strict";var $E=rt(),CE=Yo(),LE=Ri(),DE=Lt(),BE=Pi(),VE=su();fh.f=$E&&!CE?Object.defineProperties:function(e,t){DE(e);for(var i=BE(t),r=VE(t),s=r.length,n=0,o;s>n;)LE.f(e,o=r[n++],i[o]);return e}});var vu=b((bD,gh)=>{"use strict";var _E=Ut();gh.exports=_E("document","documentElement")});var Iu=b((gD,wh)=>{"use strict";var OE=Lt(),NE=bh(),vh=au(),FE=Vs(),qE=vu(),UE=Cs(),HE=Ds(),Sh=">",yh="<",yu="prototype",Tu="script",Ih=HE("IE_PROTO"),Su=function(){},Eh=function(a){return yh+Tu+Sh+a+yh+"/"+Tu+Sh},Th=function(a){a.write(Eh("")),a.close();var e=a.parentWindow.Object;return a=null,e},jE=function(){var a=UE("iframe"),e="java"+Tu+":",t;return a.style.display="none",qE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Eh("document.F=Object")),t.close(),t.F},Js,Zs=function(){try{Js=new ActiveXObject("htmlfile")}catch{}Zs=typeof document<"u"?document.domain&&Js?Th(Js):jE():Th(Js);for(var a=vh.length;a--;)delete Zs[yu][vh[a]];return Zs()};FE[Ih]=!0;wh.exports=Object.create||function(e,t){var i;return e!==null?(Su[yu]=OE(e),i=new Su,Su[yu]=null,i[Ih]=e):i=Zs(),t===void 0?i:NE.f(i,t)}});var lr=b((vD,xh)=>{"use strict";var QE=sr();xh.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:QE(a,e,t),a}});var Pu=b((SD,Ah)=>{"use strict";var zE=Ae(),WE=Ie(),GE=We(),YE=Iu(),Ph=Bs(),KE=lr(),XE=_e(),JE=Et(),xu=XE("iterator"),kh=!1,jt,Eu,wu;[].keys&&(wu=[].keys(),"next"in wu?(Eu=Ph(Ph(wu)),Eu!==Object.prototype&&(jt=Eu)):kh=!0);var ZE=!GE(jt)||zE(function(){var a={};return jt[xu].call(a)!==a});ZE?jt={}:JE&&(jt=YE(jt));WE(jt[xu])||KE(jt,xu,function(){return this});Ah.exports={IteratorPrototype:jt,BUGGY_SAFARI_ITERATORS:kh}});var en=b((yD,Mh)=>{"use strict";var ew=_e(),tw=ew("toStringTag"),Rh={};Rh[tw]="z";Mh.exports=String(Rh)==="[object z]"});var aa=b((TD,$h)=>{"use strict";var iw=en(),rw=Ie(),tn=xi(),aw=_e(),sw=aw("toStringTag"),nw=Object,ow=tn(function(){return arguments}())==="Arguments",uw=function(a,e){try{return a[e]}catch{}};$h.exports=iw?tn:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=uw(e=nw(a),sw))=="string"?t:ow?tn(e):(i=tn(e))==="Object"&&rw(e.callee)?"Arguments":i}});var Lh=b((ID,Ch)=>{"use strict";var cw=en(),lw=aa();Ch.exports=cw?{}.toString:function(){return"[object "+lw(this)+"]"}});var sa=b((ED,Bh)=>{"use strict";var dw=en(),pw=Ri().f,hw=sr(),mw=wt(),fw=Lh(),bw=_e(),Dh=bw("toStringTag");Bh.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(mw(r,Dh)||pw(r,Dh,{configurable:!0,value:e}),i&&!dw&&hw(r,"toString",fw))}});var _h=b((wD,Vh)=>{"use strict";var gw=Pu().IteratorPrototype,vw=Iu(),Sw=Hr(),yw=sa(),Tw=Ci(),Iw=function(){return this};Vh.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=vw(gw,{next:Sw(+!i,t)}),yw(a,r,!1,!0),Tw[r]=Iw,a}});var Nh=b((xD,Oh)=>{"use strict";var Ew=Re(),ww=Ct();Oh.exports=function(a,e,t){try{return Ew(ww(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var qh=b((PD,Fh)=>{"use strict";var xw=We();Fh.exports=function(a){return xw(a)||a===null}});var Hh=b((kD,Uh)=>{"use strict";var Pw=qh(),kw=String,Aw=TypeError;Uh.exports=function(a){if(Pw(a))return a;throw new Aw("Can't set "+kw(a)+" as a prototype")}});var ku=b((AD,jh)=>{"use strict";var Rw=Nh(),Mw=We(),$w=ri(),Cw=Hh();jh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Rw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return $w(r),Cw(s),Mw(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var tm=b((RD,em)=>{"use strict";var Lw=Ee(),Dw=at(),rn=Et(),Jh=gu(),Bw=Ie(),Vw=_h(),Qh=Bs(),zh=ku(),_w=sa(),Ow=sr(),Au=lr(),Nw=_e(),Wh=Ci(),Zh=Pu(),Fw=Jh.PROPER,qw=Jh.CONFIGURABLE,Gh=Zh.IteratorPrototype,an=Zh.BUGGY_SAFARI_ITERATORS,na=Nw("iterator"),Yh="keys",oa="values",Kh="entries",Xh=function(){return this};em.exports=function(a,e,t,i,r,s,n){Vw(t,e,i);var o=function(S){if(S===r&&p)return p;if(!an&&S&&S in d)return d[S];switch(S){case Yh:return function(){return new t(this,S)};case oa:return function(){return new t(this,S)};case Kh:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,d=a.prototype,l=d[na]||d["@@iterator"]||r&&d[r],p=!an&&l||o(r),m=e==="Array"&&d.entries||l,f,g,v;if(m&&(f=Qh(m.call(new a)),f!==Object.prototype&&f.next&&(!rn&&Qh(f)!==Gh&&(zh?zh(f,Gh):Bw(f[na])||Au(f,na,Xh)),_w(f,u,!0,!0),rn&&(Wh[u]=Xh))),Fw&&r===oa&&l&&l.name!==oa&&(!rn&&qw?Ow(d,"name",oa):(c=!0,p=function(){return Dw(l,this)})),r)if(g={values:o(oa),keys:s?p:o(Yh),entries:o(Kh)},n)for(v in g)(an||c||!(v in d))&&Au(d,v,g[v]);else Lw({target:e,proto:!0,forced:an||c},g);return(!rn||n)&&d[na]!==p&&Au(d,na,p,{name:r}),Wh[e]=p,g}});var rm=b((MD,im)=>{"use strict";im.exports=function(a,e){return{value:a,done:e}}});var Mu=b(($D,um)=>{"use strict";var Uw=Pi(),Ru=Jr(),am=Ci(),nm=mu(),Hw=Ri().f,jw=tm(),sn=rm(),Qw=Et(),zw=rt(),om="Array Iterator",Ww=nm.set,Gw=nm.getterFor(om);um.exports=jw(Array,"Array",function(a,e){Ww(this,{type:om,target:Uw(a),index:0,kind:e})},function(){var a=Gw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,sn(void 0,!0);switch(a.kind){case"keys":return sn(t,!1);case"values":return sn(e[t],!1)}return sn([t,e[t]],!1)},"values");var sm=am.Arguments=am.Array;Ru("keys");Ru("values");Ru("entries");if(!Qw&&zw&&sm.name!=="values")try{Hw(sm,"name",{value:"values"})}catch{}});var lm=b((CD,cm)=>{"use strict";var Yw=_e(),Kw=Ci(),Xw=Yw("iterator"),Jw=Array.prototype;cm.exports=function(a){return a!==void 0&&(Kw.Array===a||Jw[Xw]===a)}});var $u=b((LD,pm)=>{"use strict";var Zw=aa(),dm=Wr(),ex=jr(),tx=Ci(),ix=_e(),rx=ix("iterator");pm.exports=function(a){if(!ex(a))return dm(a,rx)||dm(a,"@@iterator")||tx[Zw(a)]}});var mm=b((DD,hm)=>{"use strict";var ax=at(),sx=Ct(),nx=Lt(),ox=zr(),ux=$u(),cx=TypeError;hm.exports=function(a,e){var t=arguments.length<2?ux(a):e;if(sx(t))return nx(ax(t,a));throw new cx(ox(a)+" is not iterable")}});var gm=b((BD,bm)=>{"use strict";var lx=at(),fm=Lt(),dx=Wr();bm.exports=function(a,e,t){var i,r;fm(a);try{if(i=dx(a,"return"),!i){if(e==="throw")throw t;return t}i=lx(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return fm(i),t}});var on=b((VD,Tm)=>{"use strict";var px=ar(),hx=at(),mx=Lt(),fx=zr(),bx=lm(),gx=ur(),vm=Qr(),vx=mm(),Sx=$u(),Sm=gm(),yx=TypeError,nn=function(a,e){this.stopped=a,this.result=e},ym=nn.prototype;Tm.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=px(e,i),c,d,l,p,m,f,g,v=function(E){return c&&Sm(c,"normal"),new nn(!0,E)},S=function(E){return r?(mx(E),o?u(E[0],E[1],v):u(E[0],E[1])):o?u(E,v):u(E)};if(s)c=a.iterator;else if(n)c=a;else{if(d=Sx(a),!d)throw new yx(fx(a)+" is not iterable");if(bx(d)){for(l=0,p=gx(a);p>l;l++)if(m=S(a[l]),m&&vm(ym,m))return m;return new nn(!1)}c=vx(a,d)}for(f=s?a.next:c.next;!(g=hx(f,c)).done;){try{m=S(g.value)}catch(E){Sm(c,"throw",E)}if(typeof m=="object"&&m&&vm(ym,m))return m}return new nn(!1)}});var Em=b((_D,Im)=>{"use strict";var Tx=rt(),Ix=Ri(),Ex=Hr();Im.exports=function(a,e,t){Tx?Ix.f(a,e,Ex(0,t)):a[e]=t}});var wm=b(()=>{"use strict";var wx=Ee(),xx=on(),Px=Em();wx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return xx(e,function(i,r){Px(t,i,r)},{AS_ENTRIES:!0}),t}})});var Pm=b((FD,xm)=>{"use strict";Mu();wm();var kx=ki();xm.exports=kx.Object.fromEntries});var Am=b((qD,km)=>{"use strict";km.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 Mm=b(()=>{"use strict";Mu();var Ax=Am(),Rx=Te(),Mx=sa(),Rm=Ci();for(un in Ax)Mx(Rx[un],un),Rm[un]=Rm.Array;var un});var Cm=b((jD,$m)=>{"use strict";var $x=Pm();Mm();$m.exports=$x});var Cu=b((QD,Lm)=>{"use strict";var Cx=Cm();Lm.exports=Cx});var Dm=b(()=>{"use strict"});var Lu=b((GD,Bm)=>{"use strict";var ua=Te(),Lx=Ai(),Dx=xi(),cn=function(a){return Lx.slice(0,a.length)===a};Bm.exports=function(){return cn("Bun/")?"BUN":cn("Cloudflare-Workers")?"CLOUDFLARE":cn("Deno/")?"DENO":cn("Node.js/")?"NODE":ua.Bun&&typeof Bun.version=="string"?"BUN":ua.Deno&&typeof Deno.version=="object"?"DENO":Dx(ua.process)==="process"?"NODE":ua.window&&ua.document?"BROWSER":"REST"}()});var ln=b((YD,Vm)=>{"use strict";var Bx=Lu();Vm.exports=Bx==="NODE"});var Om=b((KD,_m)=>{"use strict";var Vx=Ri();_m.exports=function(a,e,t){return Vx.f(a,e,t)}});var qm=b((XD,Fm)=>{"use strict";var _x=Ut(),Ox=Om(),Nx=_e(),Fx=rt(),Nm=Nx("species");Fm.exports=function(a){var e=_x(a);Fx&&e&&!e[Nm]&&Ox(e,Nm,{configurable:!0,get:function(){return this}})}});var Hm=b((JD,Um)=>{"use strict";var qx=Qr(),Ux=TypeError;Um.exports=function(a,e){if(qx(e,a))return a;throw new Ux("Incorrect invocation")}});var Bu=b((ZD,jm)=>{"use strict";var Hx=Re(),jx=Ie(),Du=Gr(),Qx=Hx(Function.toString);jx(Du.inspectSource)||(Du.inspectSource=function(a){return Qx(a)});jm.exports=Du.inspectSource});var _u=b((eB,Ym)=>{"use strict";var zx=Re(),Wx=Ae(),Qm=Ie(),Gx=aa(),Yx=Ut(),Kx=Bu(),zm=function(){},Wm=Yx("Reflect","construct"),Vu=/^\s*(?:class|function)\b/,Xx=zx(Vu.exec),Jx=!Vu.test(zm),ca=function(e){if(!Qm(e))return!1;try{return Wm(zm,[],e),!0}catch{return!1}},Gm=function(e){if(!Qm(e))return!1;switch(Gx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Jx||!!Xx(Vu,Kx(e))}catch{return!0}};Gm.sham=!0;Ym.exports=!Wm||Wx(function(){var a;return ca(ca.call)||!ca(Object)||!ca(function(){a=!0})||a})?Gm:ca});var Xm=b((tB,Km)=>{"use strict";var Zx=_u(),eP=zr(),tP=TypeError;Km.exports=function(a){if(Zx(a))return a;throw new tP(eP(a)+" is not a constructor")}});var Ou=b((iB,Zm)=>{"use strict";var Jm=Lt(),iP=Xm(),rP=jr(),aP=_e(),sP=aP("species");Zm.exports=function(a,e){var t=Jm(a).constructor,i;return t===void 0||rP(i=Jm(t)[sP])?e:iP(i)}});var tf=b((rB,ef)=>{"use strict";var nP=Re();ef.exports=nP([].slice)});var af=b((aB,rf)=>{"use strict";var oP=TypeError;rf.exports=function(a,e){if(a<e)throw new oP("Not enough arguments");return a}});var Nu=b((sB,sf)=>{"use strict";var uP=Ai();sf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(uP)});var Gu=b((nB,mf)=>{"use strict";var nt=Te(),cP=Po(),lP=ar(),nf=Ie(),dP=wt(),hf=Ae(),of=vu(),pP=tf(),uf=Cs(),hP=af(),mP=Nu(),fP=ln(),Qu=nt.setImmediate,zu=nt.clearImmediate,bP=nt.process,Fu=nt.Dispatch,gP=nt.Function,cf=nt.MessageChannel,vP=nt.String,qu=0,la={},lf="onreadystatechange",da,Di,Uu,Hu;hf(function(){da=nt.location});var Wu=function(a){if(dP(la,a)){var e=la[a];delete la[a],e()}},ju=function(a){return function(){Wu(a)}},df=function(a){Wu(a.data)},pf=function(a){nt.postMessage(vP(a),da.protocol+"//"+da.host)};(!Qu||!zu)&&(Qu=function(e){hP(arguments.length,1);var t=nf(e)?e:gP(e),i=pP(arguments,1);return la[++qu]=function(){cP(t,void 0,i)},Di(qu),qu},zu=function(e){delete la[e]},fP?Di=function(a){bP.nextTick(ju(a))}:Fu&&Fu.now?Di=function(a){Fu.now(ju(a))}:cf&&!mP?(Uu=new cf,Hu=Uu.port2,Uu.port1.onmessage=df,Di=lP(Hu.postMessage,Hu)):nt.addEventListener&&nf(nt.postMessage)&&!nt.importScripts&&da&&da.protocol!=="file:"&&!hf(pf)?(Di=pf,nt.addEventListener("message",df,!1)):lf in uf("script")?Di=function(a){of.appendChild(uf("script"))[lf]=function(){of.removeChild(this),Wu(a)}}:Di=function(a){setTimeout(ju(a),0)});mf.exports={set:Qu,clear:zu}});var gf=b((oB,bf)=>{"use strict";var ff=Te(),SP=rt(),yP=Object.getOwnPropertyDescriptor;bf.exports=function(a){if(!SP)return ff[a];var e=yP(ff,a);return e&&e.value}});var Yu=b((uB,Sf)=>{"use strict";var vf=function(){this.head=null,this.tail=null};vf.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}}};Sf.exports=vf});var Tf=b((cB,yf)=>{"use strict";var TP=Ai();yf.exports=/ipad|iphone|ipod/i.test(TP)&&typeof Pebble<"u"});var Ef=b((lB,If)=>{"use strict";var IP=Ai();If.exports=/web0s(?!.*chrome)/i.test(IP)});var Mf=b((dB,Rf)=>{"use strict";var pr=Te(),EP=gf(),wf=ar(),Ku=Gu().set,wP=Yu(),xP=Nu(),PP=Tf(),kP=Ef(),Xu=ln(),xf=pr.MutationObserver||pr.WebKitMutationObserver,Pf=pr.document,kf=pr.process,dn=pr.Promise,ec=EP("queueMicrotask"),dr,Ju,Zu,pn,Af;ec||(pa=new wP,ha=function(){var a,e;for(Xu&&(a=kf.domain)&&a.exit();e=pa.get();)try{e()}catch(t){throw pa.head&&dr(),t}a&&a.enter()},!xP&&!Xu&&!kP&&xf&&Pf?(Ju=!0,Zu=Pf.createTextNode(""),new xf(ha).observe(Zu,{characterData:!0}),dr=function(){Zu.data=Ju=!Ju}):!PP&&dn&&dn.resolve?(pn=dn.resolve(void 0),pn.constructor=dn,Af=wf(pn.then,pn),dr=function(){Af(ha)}):Xu?dr=function(){kf.nextTick(ha)}:(Ku=wf(Ku,pr),dr=function(){Ku(ha)}),ec=function(a){pa.head||dr(),pa.add(a)});var pa,ha;Rf.exports=ec});var Cf=b((pB,$f)=>{"use strict";$f.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var hn=b((hB,Lf)=>{"use strict";Lf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Bi=b((mB,Df)=>{"use strict";var AP=Te();Df.exports=AP.Promise});var hr=b((fB,Of)=>{"use strict";var RP=Te(),ma=Bi(),MP=Ie(),$P=Go(),CP=Bu(),LP=_e(),Bf=Lu(),DP=Et(),tc=Bo(),Vf=ma&&ma.prototype,BP=LP("species"),ic=!1,_f=MP(RP.PromiseRejectionEvent),VP=$P("Promise",function(){var a=CP(ma),e=a!==String(ma);if(!e&&tc===66||DP&&!(Vf.catch&&Vf.finally))return!0;if(!tc||tc<51||!/native code/.test(a)){var t=new ma(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[BP]=i,ic=t.then(function(){})instanceof i,!ic)return!0}return!e&&(Bf==="BROWSER"||Bf==="DENO")&&!_f});Of.exports={CONSTRUCTOR:VP,REJECTION_EVENT:_f,SUBCLASSING:ic}});var mr=b((bB,Ff)=>{"use strict";var Nf=Ct(),_P=TypeError,OP=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new _P("Bad Promise constructor");e=i,t=r}),this.resolve=Nf(e),this.reject=Nf(t)};Ff.exports.f=function(a){return new OP(a)}});var nb=b(()=>{"use strict";var NP=Ee(),FP=Et(),gn=ln(),ui=Te(),qP=ki(),vr=at(),qf=lr(),Uf=ku(),UP=sa(),HP=qm(),jP=Ct(),bn=Ie(),QP=We(),zP=Hm(),WP=Ou(),Wf=Gu().set,oc=Mf(),GP=Cf(),YP=hn(),KP=Yu(),Gf=mu(),vn=Bi(),uc=hr(),Yf=mr(),Sn="Promise",Kf=uc.CONSTRUCTOR,XP=uc.REJECTION_EVENT,JP=uc.SUBCLASSING,rc=Gf.getterFor(Sn),ZP=Gf.set,fr=vn&&vn.prototype,Vi=vn,mn=fr,Xf=ui.TypeError,ac=ui.document,cc=ui.process,sc=Yf.f,ek=sc,tk=!!(ac&&ac.createEvent&&ui.dispatchEvent),Jf="unhandledrejection",ik="rejectionhandled",Hf=0,Zf=1,rk=2,lc=1,eb=2,fn,jf,tb,Qf,ib=function(a){var e;return QP(a)&&bn(e=a.then)?e:!1},rb=function(a,e){var t=e.value,i=e.state===Zf,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,d;try{r?(i||(e.rejection===eb&&sk(e),e.rejection=lc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===a.promise?n(new Xf("Promise-chain cycle")):(c=ib(u))?vr(c,u,s,n):s(u)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},ab=function(a,e){a.notified||(a.notified=!0,oc(function(){for(var t=a.reactions,i;i=t.get();)rb(i,a);a.notified=!1,e&&!a.rejection&&ak(a)}))},sb=function(a,e,t){var i,r;tk?(i=ac.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),ui.dispatchEvent(i)):i={promise:e,reason:t},!XP&&(r=ui["on"+a])?r(i):a===Jf&&GP("Unhandled promise rejection",t)},ak=function(a){vr(Wf,ui,function(){var e=a.facade,t=a.value,i=zf(a),r;if(i&&(r=YP(function(){gn?cc.emit("unhandledRejection",t,e):sb(Jf,e,t)}),a.rejection=gn||zf(a)?eb:lc,r.error))throw r.value})},zf=function(a){return a.rejection!==lc&&!a.parent},sk=function(a){vr(Wf,ui,function(){var e=a.facade;gn?cc.emit("rejectionHandled",e):sb(ik,e,a.value)})},br=function(a,e,t){return function(i){a(e,i,t)}},gr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=rk,ab(a,!0))},nc=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Xf("Promise can't be resolved itself");var i=ib(e);i?oc(function(){var r={done:!1};try{vr(i,e,br(nc,r,a),br(gr,r,a))}catch(s){gr(r,s,a)}}):(a.value=e,a.state=Zf,ab(a,!1))}catch(r){gr({done:!1},r,a)}}};if(Kf&&(Vi=function(e){zP(this,mn),jP(e),vr(fn,this);var t=rc(this);try{e(br(nc,t),br(gr,t))}catch(i){gr(t,i)}},mn=Vi.prototype,fn=function(e){ZP(this,{type:Sn,done:!1,notified:!1,parent:!1,reactions:new KP,rejection:!1,state:Hf,value:null})},fn.prototype=qf(mn,"then",function(e,t){var i=rc(this),r=sc(WP(this,Vi));return i.parent=!0,r.ok=bn(e)?e:!0,r.fail=bn(t)&&t,r.domain=gn?cc.domain:void 0,i.state===Hf?i.reactions.add(r):oc(function(){rb(r,i)}),r.promise}),jf=function(){var a=new fn,e=rc(a);this.promise=a,this.resolve=br(nc,e),this.reject=br(gr,e)},Yf.f=sc=function(a){return a===Vi||a===tb?new jf(a):ek(a)},!FP&&bn(vn)&&fr!==Object.prototype)){Qf=fr.then,JP||qf(fr,"then",function(e,t){var i=this;return new Vi(function(r,s){vr(Qf,i,r,s)}).then(e,t)},{unsafe:!0});try{delete fr.constructor}catch{}Uf&&Uf(fr,mn)}NP({global:!0,constructor:!0,wrap:!0,forced:Kf},{Promise:Vi});tb=qP.Promise;UP(Vi,Sn,!1,!0);HP(Sn)});var db=b((SB,lb)=>{"use strict";var nk=_e(),ub=nk("iterator"),cb=!1;try{ob=0,dc={next:function(){return{done:!!ob++}},return:function(){cb=!0}},dc[ub]=function(){return this},Array.from(dc,function(){throw 2})}catch{}var ob,dc;lb.exports=function(a,e){try{if(!e&&!cb)return!1}catch{return!1}var t=!1;try{var i={};i[ub]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var pc=b((yB,pb)=>{"use strict";var ok=Bi(),uk=db(),ck=hr().CONSTRUCTOR;pb.exports=ck||!uk(function(a){ok.all(a).then(void 0,function(){})})});var hb=b(()=>{"use strict";var lk=Ee(),dk=at(),pk=Ct(),hk=mr(),mk=hn(),fk=on(),bk=pc();lk({target:"Promise",stat:!0,forced:bk},{all:function(e){var t=this,i=hk.f(t),r=i.resolve,s=i.reject,n=mk(function(){var o=pk(t.resolve),u=[],c=0,d=1;fk(e,function(l){var p=c++,m=!1;d++,dk(o,t,l).then(function(f){m||(m=!0,u[p]=f,--d||r(u))},s)}),--d||r(u)});return n.error&&s(n.value),i.promise}})});var fb=b(()=>{"use strict";var gk=Ee(),vk=Et(),Sk=hr().CONSTRUCTOR,mc=Bi(),yk=Ut(),Tk=Ie(),Ik=lr(),mb=mc&&mc.prototype;gk({target:"Promise",proto:!0,forced:Sk,real:!0},{catch:function(a){return this.then(void 0,a)}});!vk&&Tk(mc)&&(hc=yk("Promise").prototype.catch,mb.catch!==hc&&Ik(mb,"catch",hc,{unsafe:!0}));var hc});var bb=b(()=>{"use strict";var Ek=Ee(),wk=at(),xk=Ct(),Pk=mr(),kk=hn(),Ak=on(),Rk=pc();Ek({target:"Promise",stat:!0,forced:Rk},{race:function(e){var t=this,i=Pk.f(t),r=i.reject,s=kk(function(){var n=xk(t.resolve);Ak(e,function(o){wk(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var gb=b(()=>{"use strict";var Mk=Ee(),$k=mr(),Ck=hr().CONSTRUCTOR;Mk({target:"Promise",stat:!0,forced:Ck},{reject:function(e){var t=$k.f(this),i=t.reject;return i(e),t.promise}})});var fc=b((RB,vb)=>{"use strict";var Lk=Lt(),Dk=We(),Bk=mr();vb.exports=function(a,e){if(Lk(a),Dk(e)&&e.constructor===a)return e;var t=Bk.f(a),i=t.resolve;return i(e),t.promise}});var Tb=b(()=>{"use strict";var Vk=Ee(),_k=Ut(),Sb=Et(),Ok=Bi(),yb=hr().CONSTRUCTOR,Nk=fc(),Fk=_k("Promise"),qk=Sb&&!yb;Vk({target:"Promise",stat:!0,forced:Sb||yb},{resolve:function(e){return Nk(qk&&this===Fk?Ok:this,e)}})});var Ib=b(()=>{"use strict";nb();hb();fb();bb();gb();Tb()});var Pb=b(()=>{"use strict";var Uk=Ee(),Hk=Et(),yn=Bi(),jk=Ae(),wb=Ut(),xb=Ie(),Qk=Ou(),Eb=fc(),zk=lr(),gc=yn&&yn.prototype,Wk=!!yn&&jk(function(){gc.finally.call({then:function(){}},function(){})});Uk({target:"Promise",proto:!0,real:!0,forced:Wk},{finally:function(a){var e=Qk(this,wb("Promise")),t=xb(a);return this.then(t?function(i){return Eb(e,a()).then(function(){return i})}:a,t?function(i){return Eb(e,a()).then(function(){throw i})}:a)}});!Hk&&xb(yn)&&(bc=wb("Promise").prototype.finally,gc.finally!==bc&&zk(gc,"finally",bc,{unsafe:!0}));var bc});var Ab=b((VB,kb)=>{"use strict";Dm();Ib();Pb();var Gk=ai();kb.exports=Gk("Promise","finally")});var Mb=b((_B,Rb)=>{"use strict";var Yk=Ab();Rb.exports=Yk});var vc=b((OB,$b)=>{"use strict";var Kk=Mb();$b.exports=Kk});var Nb=b(()=>{"use strict";var aA=Ee(),sA=ir(),nA=ur(),oA=Xr(),uA=Jr();aA({target:"Array",proto:!0},{at:function(e){var t=sA(this),i=nA(t),r=oA(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});uA("at")});var qb=b((M0,Fb)=>{"use strict";Nb();var cA=ai();Fb.exports=cA("Array","at")});var Hb=b(($0,Ub)=>{"use strict";var lA=qb();Ub.exports=lA});var mt=b((C0,jb)=>{"use strict";var dA=Hb();jb.exports=dA});var Nc=b((RO,Ig)=>{"use strict";var PA=xi();Ig.exports=Array.isArray||function(e){return PA(e)==="Array"}});var wg=b((MO,Eg)=>{"use strict";var kA=TypeError,AA=9007199254740991;Eg.exports=function(a){if(a>AA)throw kA("Maximum allowed index exceeded");return a}});var kg=b(($O,Pg)=>{"use strict";var RA=Nc(),MA=ur(),$A=wg(),CA=ar(),xg=function(a,e,t,i,r,s,n,o){for(var u=r,c=0,d=n?CA(n,o):!1,l,p;c<i;)c in t&&(l=d?d(t[c],c,e):t[c],s>0&&RA(l)?(p=MA(l),u=xg(a,e,l,p,u,s-1)-1):($A(u+1),a[u]=l),u++),c++;return u};Pg.exports=xg});var $g=b((CO,Mg)=>{"use strict";var Ag=Nc(),LA=_u(),DA=We(),BA=_e(),VA=BA("species"),Rg=Array;Mg.exports=function(a){var e;return Ag(a)&&(e=a.constructor,LA(e)&&(e===Rg||Ag(e.prototype))?e=void 0:DA(e)&&(e=e[VA],e===null&&(e=void 0))),e===void 0?Rg:e}});var Lg=b((LO,Cg)=>{"use strict";var _A=$g();Cg.exports=function(a,e){return new(_A(a))(e===0?0:e)}});var Dg=b(()=>{"use strict";var OA=Ee(),NA=kg(),FA=Ct(),qA=ir(),UA=ur(),HA=Lg();OA({target:"Array",proto:!0},{flatMap:function(e){var t=qA(this),i=UA(t),r;return FA(e),r=HA(t,0),r.length=NA(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Bg=b(()=>{"use strict";var jA=Jr();jA("flatMap")});var _g=b((OO,Vg)=>{"use strict";Dg();Bg();var QA=ai();Vg.exports=QA("Array","flatMap")});var Ng=b((NO,Og)=>{"use strict";var zA=_g();Og.exports=zA});var Aa=b((FO,Fg)=>{"use strict";var WA=Ng();Fg.exports=WA});var Ma=b((rN,jg)=>{"use strict";var YA=aa(),KA=String;jg.exports=function(a){if(YA(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return KA(a)}});var qc=b((aN,Qg)=>{"use strict";Qg.exports=`
7
+ \v\f\r                 \u2028\u2029\uFEFF`});var Gg=b((sN,Wg)=>{"use strict";var XA=Re(),JA=ri(),ZA=Ma(),Hc=qc(),zg=XA("".replace),eR=RegExp("^["+Hc+"]+"),tR=RegExp("(^|[^"+Hc+"])["+Hc+"]+$"),Uc=function(a){return function(e){var t=ZA(JA(e));return a&1&&(t=zg(t,eR,"")),a&2&&(t=zg(t,tR,"$1")),t}};Wg.exports={start:Uc(1),end:Uc(2),trim:Uc(3)}});var Jg=b((nN,Xg)=>{"use strict";var iR=gu().PROPER,rR=Ae(),Yg=qc(),Kg="​…᠎";Xg.exports=function(a){return rR(function(){return!!Yg[a]()||Kg[a]()!==Kg||iR&&Yg[a].name!==a})}});var jc=b((oN,Zg)=>{"use strict";var aR=Gg().start,sR=Jg();Zg.exports=sR("trimStart")?function(){return aR(this)}:"".trimStart});var tv=b(()=>{"use strict";var nR=Ee(),ev=jc();nR({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==ev},{trimLeft:ev})});var rv=b(()=>{"use strict";tv();var oR=Ee(),iv=jc();oR({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==iv},{trimStart:iv})});var sv=b((pN,av)=>{"use strict";rv();var uR=ai();av.exports=uR("String","trimLeft")});var ov=b((hN,nv)=>{"use strict";var cR=sv();nv.exports=cR});var cv=b((mN,uv)=>{"use strict";var lR=ov();uv.exports=lR});var dv=b(()=>{"use strict"});var pv=b(()=>{"use strict"});var mv=b((YN,hv)=>{"use strict";var dR=We(),pR=xi(),hR=_e(),mR=hR("match");hv.exports=function(a){var e;return dR(a)&&((e=a[mR])!==void 0?!!e:pR(a)==="RegExp")}});var gv=b((KN,bv)=>{"use strict";var fR=Te(),bR=Ae(),fv=fR.RegExp,gR=!bR(function(){var a=!0;try{fv(".","d")}catch{a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,c){Object.defineProperty(e,u,{get:function(){return t+=c,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(fv.prototype,"flags").get.call(e);return o!==i||t!==i});bv.exports={correct:gR}});var Sv=b((XN,vv)=>{"use strict";var vR=Lt();vv.exports=function(){var a=vR(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 Iv=b((JN,Tv)=>{"use strict";var SR=at(),yR=wt(),TR=Qr(),yv=gv(),IR=Sv(),ER=RegExp.prototype;Tv.exports=yv.correct?function(a){return a.flags}:function(a){return!yv.correct&&TR(ER,a)&&!yR(a,"flags")?SR(IR,a):a.flags}});var wv=b((ZN,Ev)=>{"use strict";var Gc=Re(),wR=ir(),xR=Math.floor,zc=Gc("".charAt),PR=Gc("".replace),Wc=Gc("".slice),kR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,AR=/\$([$&'`]|\d{1,2})/g;Ev.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=AR;return r!==void 0&&(r=wR(r),u=kR),PR(s,u,function(c,d){var l;switch(zc(d,0)){case"$":return"$";case"&":return a;case"`":return Wc(e,0,t);case"'":return Wc(e,n);case"<":l=r[Wc(d,1,-1)];break;default:var p=+d;if(p===0)return c;if(p>o){var m=xR(p/10);return m===0?c:m<=o?i[m-1]===void 0?zc(d,1):i[m-1]+zc(d,1):c}l=i[p-1]}return l===void 0?"":l})}});var kv=b(()=>{"use strict";var RR=Ee(),MR=at(),Kc=Re(),xv=ri(),$R=Ie(),CR=We(),LR=mv(),kr=Ma(),DR=Wr(),BR=Iv(),VR=wv(),_R=_e(),OR=Et(),NR=_R("replace"),FR=TypeError,Yc=Kc("".indexOf),qR=Kc("".replace),Pv=Kc("".slice),UR=Math.max;RR({target:"String",proto:!0},{replaceAll:function(e,t){var i=xv(this),r,s,n,o,u,c,d,l,p,m,f=0,g="";if(CR(e)){if(r=LR(e),r&&(s=kr(xv(BR(e))),!~Yc(s,"g")))throw new FR("`.replaceAll` does not allow non-global regexes");if(n=DR(e,NR),n)return MR(n,e,i,t);if(OR&&r)return qR(kr(i),e,t)}for(o=kr(i),u=kr(e),c=$R(t),c||(t=kr(t)),d=u.length,l=UR(1,d),p=Yc(o,u);p!==-1;)m=c?kr(t(u,p,o)):VR(u,o,p,[],void 0,t),g+=Pv(o,f,p)+m,f=p+d,p=p+l>o.length?-1:Yc(o,u,p+l);return f<o.length&&(g+=Pv(o,f)),g}})});var Rv=b((iF,Av)=>{"use strict";dv();pv();kv();var HR=ai();Av.exports=HR("String","replaceAll")});var $v=b((rF,Mv)=>{"use strict";var jR=Rv();Mv.exports=jR});var Lv=b((aF,Cv)=>{"use strict";var QR=$v();Cv.exports=QR});var Bv=b((sF,Dv)=>{"use strict";var zR=Xr(),WR=Ma(),GR=ri(),YR=RangeError;Dv.exports=function(e){var t=WR(GR(this)),i="",r=zR(e);if(r<0||r===1/0)throw new YR("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var Fv=b((nF,Nv)=>{"use strict";var Ov=Re(),KR=tu(),Vv=Ma(),XR=Bv(),JR=ri(),ZR=Ov(XR),eM=Ov("".slice),tM=Math.ceil,_v=function(a){return function(e,t,i){var r=Vv(JR(e)),s=KR(t),n=r.length,o=i===void 0?" ":Vv(i),u,c;return s<=n||o===""?r:(u=s-n,c=ZR(o,tM(u/o.length)),c.length>u&&(c=eM(c,0,u)),a?r+c:c+r)}};Nv.exports={start:_v(!1),end:_v(!0)}});var Uv=b((oF,qv)=>{"use strict";var iM=Ai();qv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(iM)});var Hv=b(()=>{"use strict";var rM=Ee(),aM=Fv().start,sM=Uv();rM({target:"String",proto:!0,forced:sM},{padStart:function(e){return aM(this,e,arguments.length>1?arguments[1]:void 0)}})});var Qv=b((lF,jv)=>{"use strict";Hv();var nM=ai();jv.exports=nM("String","padStart")});var Wv=b((dF,zv)=>{"use strict";var oM=Qv();zv.exports=oM});var Yv=b((pF,Gv)=>{"use strict";var uM=Wv();Gv.exports=uM});var JM={};oy(JM,{ChromecastState:()=>tr,HttpConnectionType:()=>As,Observable:()=>Ft.Observable,PlaybackState:()=>Ve,Player:()=>vs,PredefinedQualityLimits:()=>Fr,SDK_VERSION:()=>XM,Subject:()=>Ft.Subject,Subscription:()=>Ft.Subscription,Surface:()=>Rs,VERSION:()=>wo,ValueSubject:()=>Ft.ValueSubject,VideoFormat:()=>$t,VideoQuality:()=>Ft.VideoQuality,WebmCodecStrategy:()=>Ca,areValidLiveRecordSources:()=>Xp,clientChecker:()=>F,isMobile:()=>si});module.exports=uy(JM);var wo="2.0.151-dev.96546ef5.0";var Ve=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ve||{}),$t=(w=>(w.MPEG="MPEG",w.DASH="DASH",w.DASH_SEP="DASH_SEP",w.DASH_SEP_VK="DASH_SEP",w.DASH_WEBM="DASH_WEBM",w.DASH_WEBM_AV1="DASH_WEBM_AV1",w.DASH_STREAMS="DASH_STREAMS",w.DASH_WEBM_VK="DASH_WEBM",w.DASH_ONDEMAND="DASH_ONDEMAND",w.DASH_ONDEMAND_VK="DASH_ONDEMAND",w.DASH_LIVE="DASH_LIVE",w.DASH_LIVE_CMAF="DASH_LIVE_CMAF",w.DASH_LIVE_WEBM="DASH_LIVE_WEBM",w.HLS="HLS",w.HLS_ONDEMAND="HLS_ONDEMAND",w.HLS_JS="HLS",w.HLS_FMP4="HLS_FMP4",w.HLS_LIVE="HLS_LIVE",w.HLS_LIVE_CMAF="HLS_LIVE_CMAF",w.WEB_RTC_LIVE="WEB_RTC_LIVE",w))($t||{});var tr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(tr||{}),As=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(As||{});var Rs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Rs||{}),Fr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Fr||{});var El=j(Mi(),1),XS=j(Ge(),1);var J=require("@vkontakte/videoplayer-shared");var qp=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var _s=class{constructor(e){this.connection$=new J.ValueSubject(void 0);this.castState$=new J.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new J.Subject;this.realCastState$=new J.ValueSubject("NOT_AVAILABLE");this.subscription=new J.Subscription;this.isDestroyed=!1;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,J.isNonNullable)(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||qp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:J.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,J.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,J.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,J.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,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,J.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,J.assertNever)(r.sessionState)}})).add((0,J.merge)((0,J.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,J.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,J.map)(r=>r.castState)),(0,J.observableFrom)([i.getCastState()])).pipe((0,J.filterChanged)(),(0,J.map)(rE),(0,J.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",n=(0,J.isNonNullable)(this.connection$.getValue());if(s&&!n){let o=i.getCurrentSession();(0,J.assertNonNullable)(o);let u=o.getCastDevice(),c=o.getMediaSession()?.media?.contentId;((0,J.isNullable)(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,J.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){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{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:J.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},rE=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,J.assertNever)(a)}};var ee=require("@vkontakte/videoplayer-shared");var Me=require("@vkontakte/videoplayer-shared");var ou=require("@vkontakte/videoplayer-shared");var Oe=(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,ou.assertNever)(t)}return a},Os=(a,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:(0,ou.assertNever)(e)}};var Fs=a=>{let{source:e,format:t,meta:i,output:r}=a,s,n,o;switch(t){case"MPEG":{let l=e[t];(0,Me.assertNonNullable)(l);let p=(0,Me.getHighestQuality)(Object.keys(l));(0,Me.assertNonNullable)(p);let m=l[p];(0,Me.assertNonNullable)(m),s=m,n="video/mp4",o=Ns();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=e[t];(0,Me.assertNonNullable)(l),s=l.url,n="application/x-mpegurl",o=Ns();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=e[t];(0,Me.assertNonNullable)(l),s=l.url,n="application/dash+xml",o=Ns();break}case"DASH_LIVE_CMAF":{let l=e[t];(0,Me.assertNonNullable)(l),s=l.url,n="application/dash+xml",o=Up();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=e[t];(0,Me.assertNonNullable)(l),s=Oe(l.url),n="application/x-mpegurl",o=Up();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",p=new Error(l);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Me.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return(0,Me.assertNever)(t)}let u=aE(i.videoId??s,n);u.contentUrl=s,u.streamType=o,u.metadata=sE();let{title:c,subtitle:d}=i;return(0,Me.isNonNullable)(c)&&(u.metadata.title=c),(0,Me.isNonNullable)(d)&&(u.metadata.subtitle=d),u};function Ns(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function Up(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function aE(a,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(a,e):{contentId:a,contentType:e,metadata:{title:"",subtitle:""},streamType:Ns()}}function sE(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var L=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var qs=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};var cu=require("@vkontakte/videoplayer-shared");var Ys=require("@vkontakte/videoplayer-shared");var Hp=j(Ge(),1),jp=require("@vkontakte/videoplayer-shared");var Us=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Hp.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||c||r||s||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=(0,jp.getWindow)().navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Qp=j(Ge(),1),ni=require("@vkontakte/videoplayer-shared");var si=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Hs=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||(0,Qp.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let e=(0,ni.getWindow)();if(!(0,ni.isBrowserWindow)(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=si()}catch(i){console.error("DeviceChecker: calling isMobile error - ",i)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let e=(0,ni.getWindow)();if(!(0,ni.isBrowserWindow)(e))return;let{userAgentData:t}=e.navigator;if(t?.getHighEntropyValues){let i=await t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.model)}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let s=e.match(i);if(s){let n=r.length>0,o=r.length>1,u="Unknown",c="Unknown";if(n){let d=r[0];typeof d=="number"?d<s.length&&s[d]!==void 0&&(u=s[d]):u=d}if(o){let d=r[1];typeof d=="number"?d<s.length&&s[d]!==void 0&&(c=s[d]):d!==void 0&&(c=d)}else s[2]!==void 0?c=s[2]:s[1]!==void 0&&n&&typeof r[0]=="string"&&(c=s[1]);u=this.normalizeOSName(u),c=this.normalizeOSVersion(c,u),u==="iOS"&&/ipad/i.test(e)?u="iPadOS":u==="iPadOS"&&/ip(hone|od)/i.test(e)&&(u="iOS"),this._os={name:u,version:c||"Unknown",full:c&&c!=="Unknown"?`${u} ${c}`:u};break}}}catch(t){console.error("DeviceChecker: OS detection error - ",t)}}normalizeOSName(e){if(!e)return"Unknown";let t=e.toLowerCase();return t.includes("windows")?"Windows":t.includes("mac os")||t.includes("macintosh")?"macOS":t.includes("iphone")||t.includes("ios")?"iOS":t.includes("ipados")?"iPadOS":t.includes("android")?"Android":t.includes("harmonyos")?"HarmonyOS":t.includes("linux")?"Linux":t.includes("cros")?"Chrome OS":t.includes("freebsd")?"FreeBSD":t.includes("openbsd")?"OpenBSD":t.includes("solaris")||t.includes("sunos")?"Solaris":t.includes("aix")?"AIX":e}normalizeOSVersion(e,t){if(!e)return"Unknown";if(e!=="Unknown"&&(e=e.replace(/_/g,"."),t==="Windows")){let i=parseFloat(e);if(!isNaN(i)){if(i>=11)return"11";if(i>=10)return"10";if(i===6.3)return"8.1";if(i===6.2)return"8";if(i===6.1)return"7";if(i===6)return"Vista";if(i===5.1||i===5.2)return"XP";if(i===5)return"2000";if(i===4)return"NT 4.0"}}return e}detectDeviceDetails(e){try{let t=[[/(iphone)/i,["Apple","iPhone"]],[/(ipad)/i,["Apple","iPad"]],[/(ipod)/i,["Apple","iPod"]],[/(macintosh)/i,["Apple","Macintosh"]],[/(windows[\w\-_ ]*phone)/i,["Microsoft",0]],[/(windows nt|win64|win32|wow64)/i,["Microsoft","PC"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptxs]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?\d+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/smart-tv.+(samsung)/i,["Samsung","Smart TV"]],[/(samsung).*tizen/i,["Samsung","Smart TV"]],[/(pixel (?:c|tablet|[0-9a-z ]+))/i,["Google",1]],[/(pixelbook(?: go)?)/i,["Google",1]],[/nexus [0-9]/i,["Google",0]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[\w\-_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[\w ]*)(?: bui|\))/i,["Xiaomi",1]],[/\b(?:xiao)?mi[\w\-_ ]+pad/i,["Xiaomi",0]],[/(?:huawei|honor) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(?:one)?(?:plus)? ?([a\d0]\d\d\d?)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((?:gm|hd)19|(?:ac|be|in|kb)20|(?:d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/(oneplus)[-_ ]?([-\w]*)/i,["OnePlus",2]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/(realme)[-_ ]?([-\w]*)/i,["Realme",2]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/(oppo)[-_ ]?([-\w]*)/i,["OPPO",2]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/(vivo)[-_ ]?([-\w]*)/i,["Vivo",2]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",0]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",0]],[/droid.+; ([a-z]?\d[0-2]{2}[a-z]{2}|[c-g]\d{4}|so[-gl]\w+|xq-[a-z]{2}\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",0]],[/(sony)[-_ ]?([-\w]*)/i,["Sony",2]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",0]],[/(lg)[-_ ]?([-\w]*)/i,["LG",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))(?: bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/(?:asus[-_ ])?(zenfone[\w\-_ ]*)/i,["ASUS",1]],[/(rog[\w\-_ ]*)/i,["ASUS",1]],[/(asus)[-_ ]?([-\w]*)/i,["ASUS",2]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])(?: bui|;|\)|\/)/i,["Lenovo",1]],[/(thinkpad[\w\-_ ]*)/i,["Lenovo",0]],[/(kf[a-z]{2}[a-z]*)(?: bui|\))/i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/(fire[\w\-_ ]*)/i,["Amazon",0]],[/(amazon)[-_ ]?([-\w]*)/i,["Amazon",2]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(surface[\w\-_ ]*)/i,["Microsoft",0]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(alcatel|tcl)[-_ ]?([-\w]*)/i,[1,2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(panasonic)[-_ ]?([-\w]*)/i,["Panasonic",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(vertu)[-_ ]?([-\w]*)/i,["Vertu",2]],[/(gionee)[-_ ]?([-\w]*)/i,["Gionee",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(cubot)[-_ ]?([-\w]*)/i,["Cubot",2]],[/(umidigi)[-_ ]?([-\w]*)/i,["UMIDIGI",2]],[/(oukitel)[-_ ]?([-\w]*)/i,["Oukitel",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(land rover)[-_ ]?([-\w]*)/i,["Land Rover",2]],[/(shield[\w\-_ ]*)/i,["Nvidia",0]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*/i,["Roku",0]],[/(apple)[-_ ]?tv/i,["Apple","TV"]],[/(amazon)[-_ ]?tv/i,["Amazon","Fire TV"]],[/(google)[-_ ]?tv/i,["Google","TV"]],[/(smart[\w\-_ ]*tv)/i,[0,"Smart TV"]],[/(playstation[\w\-_ ]*)/i,["Sony",0]],[/(nintendo[\w\-_ ]*)/i,["Nintendo",0]],[/(xbox[\w\-_ ]*)/i,["Microsoft",0]],[/(googlebot)/i,["Google","Bot"]],[/(bingbot)/i,["Microsoft","Bing Bot"]],[/(yandexbot)/i,["Yandex","Bot"]],[/(slackbot)/i,["Slack","Bot"]],[/(twitterbot)/i,["Twitter","Bot"]],[/(facebookbot)/i,["Facebook","Bot"]],[/(linkedinbot)/i,["LinkedIn","Bot"]],[/(tesla)[-_ ]?([-\w]*)/i,["Tesla",2]],[/(raspberry[\w\-_ ]*)/i,["Raspberry Pi",0]]];for(let[i,r]of t){let s=e.match(i);if(s){let n=r[0],o=r[1],u=typeof n=="number"?s[n]!==void 0?this.normalizeVendorName(s[n]):"Unknown":this.normalizeVendorName(n),c="Unknown";typeof o=="number"?c=s[o]!==void 0?s[o]:"Unknown":o!==void 0?c=o:s[1]!==void 0?c=s[1]:s[0]!==void 0&&(c=s[0]),c=this.normalizeModelName(c,u),this.details.vendor=u,this.details.model=c;break}}}catch(t){console.error("DeviceChecker: device details detection error - ",t)}}normalizeVendorName(e){if(!e)return"Unknown";let t=e.toLowerCase();return{apple:"Apple",samsung:"Samsung",google:"Google",xiaomi:"Xiaomi",huawei:"Huawei",oneplus:"OnePlus",oppo:"OPPO",vivo:"Vivo",realme:"Realme",motorola:"Motorola",sony:"Sony",lg:"LG",nokia:"Nokia",asus:"ASUS",lenovo:"Lenovo",amazon:"Amazon",blackberry:"BlackBerry",microsoft:"Microsoft",zte:"ZTE",htc:"HTC",alcatel:"Alcatel",tcl:"TCL",meizu:"Meizu",tecno:"Tecno",infinix:"Infinix",micromax:"Micromax",lava:"Lava",panasonic:"Panasonic",sharp:"Sharp",benq:"BenQ",palm:"Palm",honor:"Honor",nvidia:"NVIDIA",roku:"Roku"}[t]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}normalizeModelName(e,t){if(!e||e==="Unknown")return e;if(e==="0")return"Unknown";let i=e.replace(/^build\//i,"").replace(/\s+bui$/i,"").replace(/\)$/,"").replace(/[;,)]/g,"").replace(/\s*\(.*?\)\s*/g,"").trim(),r=t.toLowerCase();return r.includes("samsung")?i=i.replace(/^(sm-|gt-|sgh-|sch-)/i,""):r.includes("xiaomi")?i=i.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,""):r.includes("oneplus")?i=i.replace(/^oneplus[\s\-_]*/i,""):r.includes("google")&&(i=i.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,"")),i=i.replace(/_/g," ").replace(/-/g," ").replace(/\s+/g," ").trim(),i?(i.length>0&&/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i):"Unknown"}detectIOSVersion(){try{let e=(0,ni.getWindow)();if(!(0,ni.isBrowserWindow)(e))return;if(this._highEntropyValues.platformVersion){let i=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(i);return}if(this._os.version!=="Unknown"){let i=this._os.version.split("."),r=i.length>=2?`${i[0]}.${i[1]}`:i[0];this._iosVersion=parseFloat(r);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t?.[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};var Zr=require("@vkontakte/videoplayer-shared"),js=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in(0,Zr.getWindow)()}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let e=(0,Zr.getWindow)();if(!(0,Zr.isBrowserWindow)(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r??0,this._isHdr=!!e.matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=i.colorDepth}catch(s){console.error(s)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(s){console.error(s)}}};var $i=require("@vkontakte/videoplayer-shared");var st=()=>window.ManagedMediaSource||window.MediaSource,cr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),zp=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Qs=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var nE=(0,$i.getWindow)().document?.createElement("video"),oE='video/mp4; codecs="avc1.42000a,mp4a.40.2"',uE='video/mp4; codecs="hev1.1.6.L93.B0"',Wp='video/webm; codecs="vp09.00.10.08"',Gp='video/webm; codecs="av01.0.00M.08"',cE='audio/mp4; codecs="mp4a.40.2"',lE='audio/webm; codecs="opus"',Yp,dE=async()=>{let a=(0,$i.getWindow)();if(!(0,$i.isBrowserWindow)(a))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Gp}}),a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Wp}})]);Yp={DASH_WEBM_AV1:t,DASH_WEBM:i}};dE().catch(a=>{console.log(nE),console.error(a)});var zs=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return Yp}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){let e=(0,$i.getWindow)();if(!(0,$i.isBrowserWindow)(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:cr(),mse:zp(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let i=!!st()?.isTypeSupported?.(oE),r=!!st()?.isTypeSupported?.(uE),s=!!st()?.isTypeSupported?.(cE);this._codecs={h264:i,h265:r,vp9:!!st()?.isTypeSupported?.(Wp),av1:!!st()?.isTypeSupported?.(Gp),aac:s,opus:!!st()?.isTypeSupported?.(lE),mpeg:(i||r)&&s},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(i){console.error(i)}try{this.destroyVideoElement()}catch(i){console.error("Error destroying video element:",i)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var Gs=require("@vkontakte/videoplayer-shared");var Kp="audio/mpeg",Ws=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=(0,Gs.getWindow)();if(!(0,Gs.isBrowserWindow)(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Kp)},this._codecs={mp3:!!st()?.isTypeSupported?.(Kp)}}catch(i){console.error(i)}try{this.destroyAudioElement()}catch(i){console.error("Error destroying audio element:",i)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};var uu=class{constructor(){this.isInited$=new Ys.ValueSubject(!1);this._displayChecker=new js,this._deviceChecker=new Hs(this._displayChecker),this._browserChecker=new Us,this._videoChecker=new zs(this._deviceChecker,this._browserChecker),this._audioChecker=new Ws,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){(0,Ys.isBrowserWindow)()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},F=new uu;var lu=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=F.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return(0,cu.assertNever)(o)}})},ea=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_FMP4":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,cu.assertNever)(a)}},Xp=a=>{let t=Object.keys(a).filter(i=>!ea(i));return lu(t).length>0};var ta=class{constructor(e){this.subscription=new ee.Subscription;this.sessionId$=new ee.ValueSubject(null);this.mediaSessionId$=new ee.ValueSubject(null);this.contentId$=new ee.ValueSubject(null);this.isMobile=si();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if((0,ee.isNullable)(e))return;this.media=e,this.mediaSessionId$.next(e.mediaSessionId??null);let t=e.media?.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=e.media?.duration;(0,ee.isNonNullable)(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if((0,ee.isNonNullable)(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let n=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!n?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new qs(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ea(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:ee.ErrorCategory.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe((0,ee.filter)(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe((0,ee.filter)(ee.isNonNullable),(0,ee.filterChanged)(),(0,ee.debounce)(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe((0,ee.filterChanged)(),(0,ee.map)(Boolean));this.subscription.add((0,ee.combine)({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe((0,ee.filter)(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=(0,ee.combine)({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe((0,ee.filter)(({mediaLoaded:r})=>r),(0,ee.debounce)(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe((0,ee.filter)(({mediaLoaded:r,playbackState:{from:s,to:n}})=>!r&&s==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add((0,ee.combine)({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe((0,ee.debounce)(30)),mediaLoaded:t}).pipe((0,ee.filter)(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:s,volume:n}=r.to;this.setVolume(n,s)},e))}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let t=e.message?.media?.[0];this.syncMediaState(t);let i=e.message?.receiver.volume;this.syncVolumeState(i)}break;case"v2_message":{switch(e.message?.type){case"MEDIA_STATUS":{let t=e.message?.status?.[0];this.syncMediaState(t);break}}break}}}loadMedia(){let e=Fs(this.params),t=this.media?.currentTime,i=this.params.desiredState.seekState.getState(),r=t??(i.state!=="none"?i.position/1e3:0),n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();(0,ee.assertNonNullable)(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();(0,ee.assertNonNullable)(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();(0,ee.assertNonNullable)(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":L(this.params.desiredState.playbackState,"paused");break;case"PLAYING":L(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),L(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):L(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if((0,ee.isNullable)(e))return;let{level:t,muted:i}=e,r={muted:i??!1,volume:t??0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let s=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,s+=`, volume passed to state machine: ${r.volume}`),this.log({message:s}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};var ce=require("@vkontakte/videoplayer-shared");var Jp=a=>({castDevice:{friendlyName:a},remotePlayer:{},remotePlayerController:{},session:{}}),Zp=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var ia=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new ce.ValueSubject(null);this.sessionId$=new ce.ValueSubject(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new ce.Subscription;this.subscriptionEvents=new ce.Subscription;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new ce.ValueSubject(!1);this.presentationConnection$=new ce.ValueSubject(null);this.message$=new ce.ValueSubject(null);this.friendlyName$=new ce.ValueSubject(null);this.errorEvent$=new ce.Subject;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let s=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add((0,ce.fromEvent)(r,"change").subscribe(()=>{s()})),s()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();(0,ce.assertNonNullable)(e,"connect with null presentationRequest");let t=await e.start();this.handleConnection(t)}catch(e){switch(e?.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:ce.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add((0,ce.fromEvent)(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe((0,ce.tap)(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),(0,ce.filter)(e=>!!e)).subscribe(e=>{let t=(0,ce.fromEvent)(e,"message").subscribe(s=>{let n=JSON.parse(s.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${s.data}`}),this.handleMessage(n),this.message$.next(n))}),i=(0,ce.fromEvent)(e,"connect").subscribe(()=>{this.send("client_connect")}),r=(0,ce.fromEvent)(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:ce.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:s});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();t?.state==="connected"&&t?.send(e)}catch(t){this.errorEvent$.next({category:ce.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":e.message?.action==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||Zp()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new ce.Subscription}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};var Ne=require("@vkontakte/videoplayer-shared");var Ht=class a{constructor(e){this.subscription=new Ne.Subscription;this.connection$=new Ne.ValueSubject(void 0);this.castState$=new Ne.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new Ne.Subject;let t=a.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new ia({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){(0,Ne.assertNonNullable)(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=(0,Ne.combine)({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe((0,Ne.filterChanged)())});this.subscription.add(e.pipe((0,Ne.map)(({connection:t,friendlyName:i})=>!!(t&&i)),(0,Ne.filterChanged)()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?Jp(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){this.log({message:"connect"}),this.chromecastConnector?.connect()}disconnect(){this.log({message:"disconnect"}),this.chromecastConnector?.disconnect()}async stopMedia(){this.log({message:"stopMedia"}),this.chromecastConnector?.stopMedia()}toggleConnection(){let e=!!this.chromecastConnector?.presentationConnection$.getValue();this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){this.log({message:"destroy"}),this.chromecastConnector?.destroy(),this.subscription.unsubscribe()}};var vl=j(Ge(),1),Sl=j(oi(),1),OS=j(Cu(),1);var Lb=j(vc(),1);var Bt=require("@vkontakte/videoplayer-shared"),Z=class{constructor(e){this.transitionStarted$=new Bt.Subject;this.transitionEnded$=new Bt.Subject;this.transitionUpdated$=new Bt.Subject;this.forceChanged$=new Bt.Subject;this.stateChangeStarted$=(0,Bt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Bt.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,Bt.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 se=require("@vkontakte/videoplayer-shared");var Xk=5,Jk=5,Zk=500,Cb=7e3,fa=class{constructor(e){this.subscription=new se.Subscription;this.loadMediaTimeoutSubscription=new se.Subscription;this.videoState=new Z("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?.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,se.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,se.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,se.assertNever)(e)}break}default:(0,se.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(ea(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 se.Subscription;this.subscription.add(e),this.subscription.add((0,se.merge)(this.videoState.stateChangeStarted$.pipe((0,se.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,se.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 se.Subject;e.add(r.pipe((0,se.debounce)(Zk)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,se.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)>Xk)&&r.next(o),s=o})),e.add((0,se.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,se.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,se.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,se.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<Jk&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),L(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,se.assertNever)(n)}}),t((0,se.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,se.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,se.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,se.observableFrom)(["init"])).pipe((0,se.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"),L(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),L(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=Fs(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),L(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&L(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??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()}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,se.timeout)(Cb).subscribe(()=>s(`timeout(${Cb})`)))});(0,Lb.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:se.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Lc=j(Ge(),1);var ba=require("@vkontakte/videoplayer-shared");var Db=require("@vkontakte/videoplayer-shared"),Bb=a=>{try{a.pause(),a.playbackRate=0,(0,Db.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var In=require("@vkontakte/videoplayer-shared"),Sc=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)}},Tn=(0,ba.getWindow)(),yc=Tn.WeakMap?new Tn.WeakMap:new Sc,Tc=Tn.WeakMap?new Tn.WeakMap:new Map,eA=(a,e=20)=>{let t=0;return(0,In.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ye=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?(0,ba.clearVideoElement)(i):(i=document.createElement("video"),a.appendChild(i)),yc.set(i,r);let s=new In.Subscription;return s.add(eA(i,e)),Tc.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ke=a=>{Tc.get(a)?.unsubscribe(),Tc.delete(a);let t=yc.get(a);yc.delete(a),t?(0,ba.clearVideoElement)(a):Bb(a)};var Ic=j(Mi(),1),H=require("@vkontakte/videoplayer-shared");var ci=require("@vkontakte/videoplayer-shared"),En=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,ci.isNullable)(r),c=new ci.Subscription;return r&&c.add(r.subscribe(d=>{let l=a.getState();i(d,l)&&a.setState(d)},s)),i(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),c},Vt=(a,e,t)=>En(e,()=>a.loop,i=>{(0,ci.isNonNullable)(i)&&(a.loop=i)},{onError:t}),Xe=(a,e,t,i)=>En(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,ci.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),pt=(a,e,t,i)=>En(e,()=>a.playbackRate,r=>{(0,ci.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),ga=En;var tA=a=>["__",a.language,a.label].join("|"),iA=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Ec=class a{constructor(e){this.available$=new H.Subject;this.current$=new H.ValueSubject(void 0);this.error$=new H.Subject;this.subscription=new H.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:H.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(ga(t.internalTextTracks,()=>(0,Ic.default)(this.internalTracks),s=>{(0,H.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,H.isNonNullable)(s)&&(0,H.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,H.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ga(t.externalTextTracks,()=>(0,Ic.default)(this.externalTracks),s=>{(0,H.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,H.isNonNullable)(s)&&(0,H.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,H.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ga(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(ga(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,H.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,H.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,H.merge)((0,H.fromEvent)(e,"addtrack"),(0,H.fromEvent)(e,"removetrack"),(0,H.observableFrom)(["init"])).pipe((0,H.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,H.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,H.merge)((0,H.fromEvent)(e,"change"),(0,H.observableFrom)(["init"])).pipe((0,H.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,H.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,H.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,H.fromEvent)(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add((0,H.fromEvent)(e,"removetrack").subscribe(i=>{i.track?.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,H.isNonNullable)(t.align)&&(r.align=t.align),(0,H.isNonNullable)(t.position)&&(r.position=t.position),(0,H.isNonNullable)(t.size)&&(r.size=t.size),(0,H.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,H.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:tA(e),s=this.externalTracks.has(r),n=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.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,H.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,H.isNullable)(e)||!iA(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,H.assertNonNullable)(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):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,H.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)}},ht=Ec;var _i=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 Vb=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},wc=a=>{let e=Vb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},_b=a=>{let e=Vb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var R=require("@vkontakte/videoplayer-shared");var rA=3,Ob=(a,e,t=rA)=>{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 Je=a=>{let e=C=>(0,R.fromEvent)(a,C).pipe((0,R.mapTo)(void 0),(0,R.shareReplay)(1)),t=new R.Subscription,i=()=>t.unsubscribe(),r=(0,R.merge)((0,R.fromEvent)(a,"progress"),(0,R.fromEvent)(a,"timeupdate")).pipe((0,R.map)(()=>Ob(a.buffered,a.currentTime)),(0,R.shareReplay)(1)),s=F.browser.isSafari?(0,R.combine)({play:e("play").pipe((0,R.once)()),playing:e("playing")}).pipe((0,R.mapTo)(void 0),(0,R.shareReplay)(1)):e("playing"),n=(0,R.fromEvent)(a,"volumechange").pipe((0,R.map)(()=>({muted:a.muted,volume:a.volume})),(0,R.shareReplay)(1)),o=(0,R.fromEvent)(a,"ratechange").pipe((0,R.map)(()=>a.playbackRate),(0,R.shareReplay)(1)),u=(0,R.fromEvent)(a,"error").pipe((0,R.filter)(()=>!!(a.error||a.played.length)),(0,R.map)(()=>{let C=a.error;return{id:C?`MediaError#${C.code}`:"HtmlVideoError",category:R.ErrorCategory.VIDEO_PIPELINE,message:C?C.message:"Error event from HTML video element",thrown:a.error??void 0}}),(0,R.shareReplay)(1)),c=(0,R.fromEvent)(a,"timeupdate").pipe((0,R.map)(()=>a.currentTime),(0,R.shareReplay)(1)),d=["waiting","seeking","seeked","timeupdate"],l=new R.Subject,p=.3,m;t.add((0,R.merge)(...d.map(C=>(0,R.fromEvent)(a,C))).subscribe(C=>{let re=a.currentTime;a.loop&&(0,R.isNonNullable)(m)&&(0,R.isNonNullable)(re)&&m>=a.duration-p&&re<=p&&l.next(m),m=re}));let f=e("pause").pipe((0,R.filter)(()=>!a.error&&m!==a.duration),(0,R.shareReplay)(1)),g=(0,R.fromEvent)(a,"enterpictureinpicture").pipe((0,R.shareReplay)(1)),v=(0,R.fromEvent)(a,"leavepictureinpicture").pipe((0,R.shareReplay)(1)),S=new R.ValueSubject(_b(a));t.add(g.subscribe(()=>S.next(!0))),t.add(v.subscribe(()=>S.next(!1)));let E=new R.ValueSubject(wc(a)),A=(0,R.fromEvent)(a,"fullscreenchange").pipe((0,R.shareReplay)(1));t.add(A.pipe((0,R.map)(()=>wc(a))).subscribe(E));let w=.1,D=1e3,N=(0,R.fromEvent)(a,"timeupdate").pipe((0,R.map)(C=>a.duration-a.currentTime<w),(0,R.filterChanged)(),(0,R.shareReplay)(1)),U=(0,R.merge)(N.pipe((0,R.filter)(C=>!a.loop&&C)),(0,R.fromEvent)(a,"ended")).pipe((0,R.throttle)(D),(0,R.mapTo)(void 0),(0,R.shareReplay)(1)),Q=(0,R.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(C=>(0,R.fromEvent)(a,C)),N.pipe((0,R.map)(C=>({type:C?"ended":"unknown"})))).pipe((0,R.map)(C=>F.browser.isFirefox&&C.type==="ended"?a.readyState<2:a.readyState<3),(0,R.filterChanged)(),(0,R.shareReplay)(1));return{playing$:s,pause$:f,canplay$:e("canplay"),ended$:U,looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,R.fromEvent)(a,"durationchange").pipe((0,R.map)(()=>a.duration),(0,R.shareReplay)(1)),isBuffering$:Q,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:E,enterPip$:g,leavePip$:v,destroy:i}};var Qt=require("@vkontakte/videoplayer-shared"),li=a=>{switch(a){case"mobile":return Qt.VideoQuality.Q_144P;case"lowest":return Qt.VideoQuality.Q_240P;case"low":return Qt.VideoQuality.Q_360P;case"sd":case"medium":return Qt.VideoQuality.Q_480P;case"hd":case"high":return Qt.VideoQuality.Q_720P;case"fullhd":case"full":return Qt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Qt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Qt.VideoQuality.Q_2160P}};var je=j(mt(),1),Pc=j(Ge(),1),Oi=j(oi(),1),$=require("@vkontakte/videoplayer-shared");var xc=!1,zt={},Qb=a=>{xc=a},zb=()=>{zt={}},Wb=a=>{a(zt)},va=(a,e)=>{xc&&(zt.meta=zt.meta??{},zt.meta[a]=e)},He=class{constructor(e){this.name=e}next(e){if(!xc)return;zt.series=zt.series??{};let t=zt.series[this.name]??[];t.push([Date.now(),e]),zt.series[this.name]=t}};var we=require("@vkontakte/videoplayer-shared");function Gb(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Sr(a,e,t){return(0,we.isNullable)(a)||(0,we.isNonNullable)(a.min)&&(0,we.isNonNullable)(a.max)&&(0,we.isLower)(a.max,a.min)||(0,we.isNonNullable)(a.min)&&e&&(0,we.isHigher)(a.min,e)||(0,we.isNonNullable)(a.max)&&t&&(0,we.isLower)(a.max,t)}function Yb({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Sr({max:a?.max?(0,we.videoHeightToQuality)(a.max):void 0,min:a?.min?(0,we.videoHeightToQuality)(a.min):void 0},e?(0,we.videoHeightToQuality)(e):void 0,t?(0,we.videoHeightToQuality)(t):void 0)}var eg=new He("best_bitrate"),xn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var yr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),di=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,$.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Pn='Assertion "ABR Tracks is empty array" failed',wn=new WeakMap,Kb=new WeakMap,Xb=new WeakMap,Sa=(a,e,t,i)=>{let r=[...e].sort(yr(1)),s=[...t].sort(yr(1)),n=s.filter(u=>(0,$.isNonNullable)(u.bitrate)&&(0,$.isNonNullable)(a.bitrate)?a.bitrate/u.bitrate>i:!0),o=(0,je.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,je.default)(s,-1);return o&&(0,Pc.default)(n,o)?o:n.length?(0,je.default)(n,-1):(0,je.default)(s,0)},ya=(a,e,t,i)=>{let r=wn.get(e);r||(r=[...e].sort(yr(1)),wn.set(e,r));let s=wn.get(t);s||(s=[...t].sort(yr(1)),wn.set(t,s));let n=Xb.get(a);n||(n=s.filter(u=>(0,$.isNonNullable)(u.bitrate)&&(0,$.isNonNullable)(a.bitrate)?a.bitrate/u.bitrate>i:!0),Xb.set(a,n));let o=(0,je.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,je.default)(s,-1);return o&&(0,Pc.default)(n,o)?o:n.length?(0,je.default)(n,-1):(0,je.default)(s,0)},Jb=a=>"quality"in a,kn=(a,e,t,i)=>{let r=(0,$.isNonNullable)(i?.last?.bitrate)&&(0,$.isNonNullable)(t?.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,$.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let o=Jb(n)?"video":"audio",u=Jb(n)?n.quality:n.bitrate;return e({message:`
8
8
  [last ${o} selected] ${u}
9
9
  `}),n}return i?.recordSwitch(t),t},pA=(a,e)=>Math.log(e)/Math.log(a),tg=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&F.display.pixelRatio){let s=F.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,c=0]=a.pixelRatioLogCoefficients,d=pA(n,o*s+u)+c;Number.isFinite(d)&&(r*=d)}}return(0,$.isNonNullable)(t?.min)&&(0,$.isHigherOrEqual)(t.min,a.highQualityLimit)&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Zb=new WeakMap,_t=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:c,visible:d,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:m,abrLogger:f,panelSize:g})=>{(0,$.assertNotEmptyArray)(a,Pn);let{containerSizeFactor:v,containerSizeLimit:S}=tg({container:e,tuning:i,limits:r,panelSize:g}),E=i.considerPlaybackRate&&(0,$.isNonNullable)(o)?o:1,A=Zb.get(a);A||(A=a.filter(k=>!(0,$.isInvariantQuality)(k.quality)).sort((k,P)=>(0,$.isHigher)(k.quality,P.quality)?-1:1),Zb.set(a,A));let w=(0,je.default)(A,-1)?.quality,D=(0,je.default)(A,0)?.quality,N=Sr(r,D,w),U=E*xn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),B={},Q=null;for(let k of A){let P=!0;if(S)if(k.size)P=k.size.width<=S.width&&k.size.height<=S.height;else{let ne=S&&(0,$.videoSizeToQuality)(S);P=ne?(0,$.isLowerOrEqual)(k.quality,ne):!0}if(!P){B[k.quality]="FitsContainer";continue}let X=m||t,V=(0,$.isNonNullable)(X)&&isFinite(X)&&(0,$.isNonNullable)(k.bitrate)?X-s>=k.bitrate*U:!0,ae=r?.min===k.quality;if(!V&&!ae){B[k.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&(0,$.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,$.isInvariantQuality)(u.quality)&&(n??0)<i.minBufferToSwitchUp&&(0,$.isHigher)(k.quality,u.quality)){B[k.quality]="Buffer";continue}if(!!l&&(0,$.isHigherOrEqual)(k.quality,l)&&!ae){B[k.quality]="DroppedFramesLimit";continue}if(!!p&&(0,$.isHigherOrEqual)(k.quality,p)&&!ae){B[k.quality]="StallsLimit";continue}let Le=N||((0,$.isNullable)(r?.max)||(0,$.isLowerOrEqual)(k.quality,r.max))&&((0,$.isNullable)(r?.min)||(0,$.isHigherOrEqual)(k.quality,r.min)),De=(0,$.isNonNullable)(d)&&!d?(0,$.isLowerOrEqual)(k.quality,i.backgroundVideoQualityLimit):!0;if(!Le||!De){B[k.quality]="FitsQualityLimits";continue}Q||(Q=k)}Q&&Q.bitrate&&eg.next(Q.bitrate);let C=Q??(0,je.default)(A,-1)??a[0],re=c?.last,Y=kn(i,f,C,c);return(0,$.isNonNullable)(c)&&Y.quality!==re?.quality&&f({message:`
10
10
  [VIDEO TRACKS ABR]
@@ -175,7 +175,7 @@ void main(void) {
175
175
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
176
176
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
177
177
  (?:-(?<privateuse>(?:${e})))?
178
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Zv=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?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},kt=(a,e)=>{let t=a;t=(0,Jc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,eS.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Jc.default)(t,n,(o,u)=>(0,$a.isNullable)(s)?o:(0,$a.isNullable)(u)?s:(0,tS.default)(s,parseInt(u,10),"0"))}return t},Gn=(a,e)=>{let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Q=>Q.textContent?.trim()??""),o=(0,iS.default)(n,0)??"",u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),l=s.getElementsByTagName("vk:Attrs")[0],p=l?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,m=l?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=l?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,g=l?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,v;u&&(v={availabilityStartTime:c?new Date(c).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:m==="yes",streamIsUnpublished:f==="yes"});let S,E=s.getAttribute("mediaPresentationDuration"),A=[...s.getElementsByTagName("Period")],w=A.reduce((Q,C)=>({...Q,[C.id]:C.children}),{}),D=A.reduce((Q,C)=>({...Q,[C.id]:C.getAttribute("duration")}),{});E?S=Zv(E):(0,Zc.default)(D).filter(Q=>Q).length&&!u?S=(0,Zc.default)(D).reduce((Q,C)=>Q+(Zv(C)??0),0):g&&(S=parseInt(g,10));let N=0,U=s.getAttribute("profiles")?.split(",")??[];for(let Q of A.map(C=>C.id))for(let C of w[Q]){let re=C.getAttribute("id")??"id"+(N++).toString(10),Y=C.getAttribute("mimeType")??"",k=C.getAttribute("codecs")??"",P=C.getAttribute("contentType")??Y?.split("/")[0],X=C.getAttribute("profiles")?.split(",")??[],V=Jv(C.getAttribute("lang")??"")??{},ae=C.querySelector("Label")?.textContent?.trim()??void 0,de=C.querySelectorAll("Representation"),ye=C.querySelector("SegmentTemplate"),Pe=C.querySelector("Role")?.getAttribute("value")??void 0,Le=P,De={id:re,language:V.language,isDefault:Pe==="main",label:ae,codecs:k,hdr:Le==="video"&&Xc(k),mime:Y,representations:[]};for(let ne of de){let te=ne.getAttribute("lang")??void 0,Be=ae??C.getAttribute("label")??ne.getAttribute("label")??void 0,qe=ne.querySelector("BaseURL")?.textContent?.trim()??"",ke=new URL(qe||o,e).toString(),lt=ne.getAttribute("mimeType")??Y,Zt=ne.getAttribute("codecs")??k??"",vt;if(P==="text"){let it=ne.getAttribute("id")||"",ei=V.privateuse?.includes("x-auto")||it.includes("_auto"),St=ne.querySelector("SegmentTemplate");if(St){let Vr={representationId:ne.getAttribute("id")??void 0,bandwidth:ne.getAttribute("bandwidth")??void 0},Ss=parseInt(ne.getAttribute("bandwidth")??"",10)/1e3,ys=parseInt(St.getAttribute("startNumber")??"",10)??1,Yi=parseInt(St.getAttribute("timescale")??"",10),Io=St.querySelectorAll("SegmentTimeline S")??[],Ki=St.getAttribute("media");if(!Ki)continue;let Ts=[],Is=0,Es="",Xi=0,_r=ys,Ue=0;for(let yt of Io){let Ii=parseInt(yt.getAttribute("d")??"",10),dt=parseInt(yt.getAttribute("r")??"",10)||0,ti=parseInt(yt.getAttribute("t")??"",10);Ue=Number.isFinite(ti)?ti:Ue;let Ei=Ii/Yi*1e3,Ji=Ue/Yi*1e3;for(let Rt=0;Rt<dt+1;Rt++){let ii=kt(Ki,{...Vr,segmentNumber:_r.toString(10),segmentTime:(Ue+Rt*Ii).toString(10)}),Zi=(Ji??0)+Rt*Ei,Nr=Zi+Ei;_r++,Ts.push({time:{from:Zi,to:Nr},url:ii})}Ue+=(dt+1)*Ii,Is+=(dt+1)*Ei}Xi=Ue/Yi*1e3,Es=kt(Ki,{...Vr,segmentNumber:_r.toString(10),segmentTime:Ue.toString(10)});let Or={time:{from:Xi,to:1/0},url:Es},qt={type:"template",baseUrl:ke,segmentTemplateUrl:Ki,initUrl:"",totalSegmentsDurationMs:Is,segments:Ts,nextSegmentBeyondManifest:Or,timescale:Yi};vt={id:it,kind:"text",segmentReference:qt,profiles:[],duration:S,bitrate:Ss,mime:"",codecs:"",width:0,height:0,isAuto:ei}}else vt={id:it,isAuto:ei,kind:"text",url:ke}}else{let it=ne.getAttribute("contentType")??lt?.split("/")[0]??P,ei=C.getAttribute("profiles")?.split(",")??[],St=parseInt(ne.getAttribute("width")??"",10),Vr=parseInt(ne.getAttribute("height")??"",10),Ss=parseInt(ne.getAttribute("bandwidth")??"",10)/1e3,ys=ne.getAttribute("frameRate")??"",Yi=ne.getAttribute("quality")??void 0,Io=ys?Xv(ys):void 0,Ki=ne.getAttribute("id")??"id"+(N++).toString(10),Ts=it==="video"?`${Vr}p`:it==="audio"?`${Ss}Kbps`:Zt,Is=`${Ki}@${Ts}`,Es=[...U,...X,...ei],Xi,_r=ne.querySelector("SegmentBase"),Ue=ne.querySelector("SegmentTemplate")??ye;if(_r){let qt=ne.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[yt,Ii]=qt.split("-").map(ii=>parseInt(ii,10)),dt={from:yt,to:Ii},ti=ne.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ei,Ji]=ti?ti.split("-").map(ii=>parseInt(ii,10)):[],Rt=ti?{from:Ei,to:Ji}:void 0;Xi={type:"byteRange",url:ke,initRange:dt,indexRange:Rt}}else if(Ue){let qt={representationId:ne.getAttribute("id")??void 0,bandwidth:ne.getAttribute("bandwidth")??void 0},yt=parseInt(Ue.getAttribute("timescale")??"",10),Ii=Ue.getAttribute("initialization")??"",dt=Ue.getAttribute("media"),ti=parseInt(Ue.getAttribute("startNumber")??"",10)??1,Ei=kt(Ii,qt);if(!dt)throw new ReferenceError("No media attribute in SegmentTemplate");let Ji=Ue.querySelectorAll("SegmentTimeline S")??[],Rt=[],ii=0,Zi="",Nr=0;if(Ji.length){let ws=ti,Tt=0;for(let er of Ji){let Mt=parseInt(er.getAttribute("d")??"",10),wi=parseInt(er.getAttribute("r")??"",10)||0,xs=parseInt(er.getAttribute("t")??"",10);Tt=Number.isFinite(xs)?xs:Tt;let Eo=Mt/yt*1e3,ZS=Tt/yt*1e3;for(let Ps=0;Ps<wi+1;Ps++){let ey=kt(dt,{...qt,segmentNumber:ws.toString(10),segmentTime:(Tt+Ps*Mt).toString(10)}),wl=(ZS??0)+Ps*Eo,ty=wl+Eo;ws++,Rt.push({time:{from:wl,to:ty},url:ey})}Tt+=(wi+1)*Mt,ii+=(wi+1)*Eo}Nr=Tt/yt*1e3,Zi=kt(dt,{...qt,segmentNumber:ws.toString(10),segmentTime:Tt.toString(10)})}else if((0,$a.isNonNullable)(S)){let Tt=parseInt(Ue.getAttribute("duration")??"",10)/yt*1e3,er=Math.ceil(S/Tt),Mt=0;for(let wi=1;wi<er;wi++){let xs=kt(dt,{...qt,segmentNumber:wi.toString(10),segmentTime:Mt.toString(10)});Rt.push({time:{from:Mt,to:Mt+Tt},url:xs}),Mt+=Tt}Nr=Mt,Zi=kt(dt,{...qt,segmentNumber:er.toString(10),segmentTime:Mt.toString(10)})}let JS={time:{from:Nr,to:1/0},url:Zi};Xi={type:"template",baseUrl:ke,segmentTemplateUrl:dt,initUrl:Ei,totalSegmentsDurationMs:ii,segments:Rt,nextSegmentBeyondManifest:JS,timescale:yt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!it||!lt)continue;let Or={video:"video",audio:"audio",text:"text"}[it];if(!Or)continue;Le||=Or,vt={id:Is,kind:Or,segmentReference:Xi,profiles:Es,duration:S,bitrate:Ss,mime:lt,codecs:Zt,width:St,height:Vr,fps:Io,quality:Yi}}De.language||=te,De.label||=Be,De.mime||=lt,De.codecs||=Zt,De.hdr||=Le==="video"&&Xc(Zt),De.representations.push(vt)}if(Le){let ne=r[Le].find(te=>te.id===De.id);if(ne&&De.representations.every(te=>te.segmentReference.type==="template"))for(let te of ne.representations){let Be=De.representations.find(lt=>lt.id===te.id);if(!Be)continue;let qe=Be.segmentReference,ke=te.segmentReference;ke.segments.push(...qe.segments),ke.nextSegmentBeyondManifest=qe.nextSegmentBeyondManifest}else r[Le].push(De)}}return{duration:S,streams:r,baseUrls:n,live:v}};var Kn=j(mt(),1),el=j(Ge(),1),La=require("@vkontakte/videoplayer-shared");var Ca=(s=>(s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient",s))(Ca||{});var Yn=a=>{let{webmDecodingInfo:e}=F.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:(0,La.assertNever)(a)}},rS=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Yn(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(F.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...Yn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Yn(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Yn(a),...s,"HLS","HLS_ONDEMAND"];default:(0,La.assertNever)(e)}if(F.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:(0,La.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},aS=({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=F.device.isMac&&F.browser.isSafari;if(F.device.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,La.assertNever)(a)}else F.video.nativeHlsSupported&&!u&&!F.browser.isChromiumBased?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"]},tl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Xn=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Kn.default)(t.value.split("."),0)}for(let t of a){let i=(0,Kn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Kn.default)(e.value.split("."),0)},Jn=a=>{let e=a.map(i=>Ar(i)),{codecs:t}=F.video;return pM().filter(i=>{if((0,el.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},Zn=a=>{let e=a.map(i=>Ar(i)),{codecs:t}=F.video;return hM().filter(i=>{if((0,el.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Ar=a=>a.split(".")[0].replace("0",""),pM=()=>["av1","vp9","hev1","avc1"],hM=()=>["opus","mp4a"];var SS=j(mt(),1);var mM=(a,e={})=>{let i=e.timeout||1,r=performance.now();return xe.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},fM=a=>xe.clearTimeout(a),sS=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),nS=!sS(xe.requestIdleCallback)||!sS(xe.cancelIdleCallback),Fi=nS?mM:xe.requestIdleCallback,qi=nS?fM:xe.cancelIdleCallback;var M=require("@vkontakte/videoplayer-shared");var uS=j(mt(),1);var eo=a=>a.valid,oe=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}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 Rr=class extends oe{};var oS=require("@vkontakte/videoplayer-shared");var Da=class extends oe{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:(0,oS.assertNever)(e)}}};var Ba=class extends oe{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var Va=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var be=class extends oe{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var _a=class extends be{constructor(e,t){super(e,t),this.valid&&(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 Oa=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Na=class extends oe{constructor(e,t){super(e,t),this.data=this.content}};var Ui=class extends be{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}}};var Fa=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qa=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ua=class extends be{constructor(e,t){if(super(e,t),!this.valid)return;switch(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 Ha=class extends be{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var ja=class extends be{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Qa=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var za=class extends be{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 Wa=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ga=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends be{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Ka=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xa=class extends be{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 Ja=class extends be{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 Za=class extends be{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 es=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ts=class extends be{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var is=class extends oe{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var gM={ftyp:Ba,moov:Va,mvhd:_a,moof:Oa,mdat:Na,sidx:Ui,trak:Fa,mdia:Qa,mfhd:Ya,tkhd:za,traf:Ka,tfhd:Xa,tfdt:Ja,trun:Za,minf:Wa,sv3d:qa,st3d:Ua,prhd:Ha,proj:Ga,equi:ja,uuid:Da,stbl:es,stsd:ts,avc1:is,unknown:Rr},Gt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!eo(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=gM[e];return i?new i(t,new a):new Rr(t,new a)}};var fi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{eo(t)&&(this.index[t.type]??=[],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 SM=new TextDecoder("ascii"),yM=a=>SM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",TM=a=>{let e=new Ui(a,new Gt),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})},IM=(a,e)=>{let i=new Gt().parse(a),r=new fi(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,l)},EM=a=>{let t=new Gt().parse(a),i=new fi(t),r={},s=i.findAll("uuid"),n=(0,uS.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},wM=a=>{let t=new Gt().parse(a);return new fi(t).find("sidx")?.timescale},xM=(a,e)=>{let i=new Gt().parse(a),s=new fi(i).findAll("traf"),n=s[s.length-1].children.find(l=>l.type==="tfhd"),o=s[s.length-1].children.find(l=>l.type==="tfdt"),u=s[s.length-1].children.find(l=>l.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((l,p)=>l+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},PM=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 Gt().parse(a),r=new fi(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},cS={validateData:yM,parseInit:PM,getIndexRange:()=>{},parseSegments:TM,parseFeedableSegmentChunk:IM,getChunkEndTime:xM,getServerLatencyTimestamps:EM,getTimescaleFromIndex:wM};var as=j(Ge(),1),Yt=require("@vkontakte/videoplayer-shared");var dS=require("@vkontakte/videoplayer-shared");var lS={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"}},pS=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=rs(a,t),r=i in lS,s=r?lS[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,d=rs(u),l=c*2**((o-1)*8)+d,p=t+o,m;return p+l>a.byteLength?m=new DataView(a.buffer,a.byteOffset+p):m=new DataView(a.buffer,a.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:m,valueSize:l}},rs=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},At=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return rs(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,dS.assertNever)(e)}},Hi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=pS(i);if(!e(r))return;r.type==="master"&&Hi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},hS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=pS(a);return Hi(r.value,({tag:s,type:n,value:o})=>(s===17143?e=At(o,n):s===17026?t=At(o,n):s===17029&&(i=At(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var mS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],kM=[231,22612,22743,167,171,163,160,175],AM=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,c,d=!1,l=0;return Hi(a,({tag:p,type:m,value:f,valueSize:g})=>{if(p===21419){let v=At(f,m);c=rs(v)}else p!==21420&&(c=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=At(f,m):p===17545?r=At(f,m):p===21420&&c===475249515?u=At(f,m):p===374648427?Hi(f,({tag:v,type:S,value:E})=>v===30321?(d=At(E,S)===1,!1):!0):s&&n&&(0,as.default)(mS,p)&&(o=!0),!o}),(0,Yt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Yt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Yt.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=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:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},RM=a=>{if((0,Yt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},MM=(a,e)=>{let t=!1,i=!1,r=o=>(0,Yt.isNonNullable)(o.time)&&(0,Yt.isNonNullable)(o.position),s=[],n;return Hi(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=At(c,u));break;case 183:break;case 241:n&&(n.position=At(c,u));break;default:t&&(0,as.default)(mS,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:d}=o,l=s[u+1];return{status:"none",time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},$M=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):(0,as.default)(kM,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,as.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},fS={validateData:hS,parseInit:AM,getIndexRange:RM,parseSegments:MM,parseFeedableSegmentChunk:$M};var ji=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return fS;case"mp4":return cS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var il=j(mt(),1);var bS=require("@vkontakte/videoplayer-shared"),bi=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let o=(s?li(s):void 0)??(0,bS.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},ss=({id:a,bitrate:e})=>({id:a,bitrate:e}),gS=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),vS=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),rl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,il.default)(i.split("."),0),isDefault:r}),al=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,il.default)(r.split("."),0)}),sl=a=>"url"in a,ut=a=>a.type==="template";var Mr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,manifest:o}){this.error$=new M.Subject;this.playingRepresentation$=new M.ValueSubject(void 0);this.playingRepresentationInit$=new M.ValueSubject(void 0);this.currentSegmentLength$=new M.ValueSubject(0);this.onLastSegment$=new M.ValueSubject(!1);this.fullyBuffered$=new M.ValueSubject(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new me;this.downloadAbortController=new me;this.subscription=new M.Subscription;this.startWith=(0,M.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,M.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=ji(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,M.assertNonNullable)(i,"No init buffer for starting representation"),(0,M.assertNonNullable)(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s)}.bind(this));this.switchTo=(0,M.abortable)(this.destroyAbortController.signal,async function*(e,t=!0){if((0,M.isNullable)(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);(0,M.assertNonNullable)(r,`No such representation ${e}`),(0,M.assertNonNullable)(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let s=this.initData.get(r.id),n=this.segments.get(r.id);(0,M.assertNonNullable)(s,"No init buffer for switching representation"),(0,M.assertNonNullable)(n,"No segments for switching representation");let o=this.getCurrentPosition()??0,u=l=>l.segment.networkStatus!=="downloaded"||l.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,c=l=>{let p=this.representations.get(l.representationId);return(0,M.assertNonNullable)(p,"No itemRepresentation for previous track before switch"),l.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(p,r)},d=l=>t?u(l)&&c(l):u(l);this.bufferPlaybackQueue.filter(d).forEach(l=>l.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(l=>!d(l)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=(0,M.abortable)(this.downloadAbortController.signal,async function*(){let e=(0,M.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=(0,M.getWindow)();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add((0,M.fromEvent)(i,"online").pipe((0,M.once)()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=s,this.getCurrentPosition=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.baseUrls=o?.baseUrls??[],this.representations=new Map(i.map(u=>[u.id,u]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){(0,M.isNullable)(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return(0,M.isNonNullable)(t)&&(0,M.isNonNullable)(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){let t=this.downloadingRepresentationId??this.playingRepresentationId??"";return this.segments.get(t)?.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from}getRepresentationInitialTime(){return(0,M.isNullable)(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}calculateDurationFromSegments(){if((0,M.isNullable)(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,SS.default)(e,-1)?.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=(0,M.getWindow)();if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),e.__polyfill_cancelIdleCallback_bgan9da8h1hj)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_bgan9da8h1hj(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=bi(e),s=bi(t);i=(0,M.isNonNullable)(r)&&(0,M.isNonNullable)(s)&&(0,M.isHigher)(s.quality,r.quality)}else if(this.kind==="audio"){let r=ss(e),s=ss(t);i=(0,M.isNonNullable)(r?.bitrate)&&(0,M.isNonNullable)(s?.bitrate)&&s.bitrate>r.bitrate}return i}async clearBuffer(){this.bufferClearingMutex=!0,await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new me,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}async abortNativeBuffer(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=await this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,this.maintainNativeBufferMutex=!1,i}async loadInits(e){await this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,Fi(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),s;this.initData.has(e.id)&&this.segments.has(e.id)?s=Promise.resolve():(0,M.isNonNullable)(r)?s=r:s=this.loadInit(e,t,i),await s}async loadInit(e,t="auto",i=!1){try{let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r);this.initDataPromises.set(e.id,s);let{initMetadata:n,initDataView:o,segments:u}=await s??{};if(this.initDataPromises.delete(e.id),(0,M.isNullable)(o)||(0,M.isNullable)(u))return;n&&this.parsedInitData.set(e.id,n);let c=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,u),this.failedDownloads=0}catch(r){i&&this.error$.next({id:"LoadInits",category:M.ErrorCategory.WTF,message:"loadInit threw",thrown:r})}}async maintainNativeBuffer(){let e=this.getCurrentPosition();if((0,M.isNullable)(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(o=>this.withinInterval(e,o.segment.time)),i=this.bufferPlaybackQueue.find(o=>o.segment.bufferStatus!=="fed"),r=this.initData.get(i?.representationId??""),s=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;(0,M.isNonNullable)(r)&&(0,M.isNonNullable)(i)&&(0,M.isNonNullable)(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),(0,M.isNonNullable)(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,n):await this.appendSegmentPartially(i,n)),(0,M.isNonNullable)(s)&&this.withinRemoveInterval(e,s.segment.time)&&await this.removeSegment(s,n),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){(0,M.assertNonNullable)(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if((0,M.isNullable)(t)||(0,M.isNullable)(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(n=>e>=n.time.from&&e<n.time.to);(0,M.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let s=this.selectItemsToLoad();await this.loadItems(s,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){let t=this.segments.get(this.downloadingRepresentationId??"");if((0,M.isNullable)(t)||t.length===0)return;let i=t[t?.length-1];(0,M.isNullable)(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){(0,M.assertNonNullable)(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,s;(0,M.isNonNullable)(i)&&this.withinInterval(e,i)?(s=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(s=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&s>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;s-=u-o,r++}return n}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return(0,M.isNonNullable)(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return(0,M.isNonNullable)(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return(0,M.isNonNullable)(e)?e-i>t:!1}async appendSegmentFully(e,t){if((0,M.isNullable)(e.segment.data))return;e.segment.feedingBytes=e.segment.size,await this.nativeBufferManager.append(e.segment.data,t)&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))}async appendSegmentPartially(e,t){if((0,M.isNullable)(e.segment.data)||(0,M.isNullable)(e.segment.loadedBytes)||(0,M.isNullable)(e.segment.feedingBytes)||(0,M.isNullable)(e.segment.fedBytes)||(0,M.isNullable)(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),s=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;s?.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=s.byteLength,await this.nativeBufferManager.append(s,t)&&(e.segment.fedBytes+=s.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,s=(r-i)/4;await this.nativeBufferManager.remove(0,r-s,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||(0,M.isNonNullable)(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let s=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)(0,M.isNonNullable)(o.size)&&s>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())(0,M.isNonNullable)(o.size)&&s>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size)}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())this.updateRepresentationBaseUrl(t,e)}};var Nt=require("@vkontakte/videoplayer-shared");var to=class extends Mr{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(s,{...n,priority:i}),this.lastDataObtainedTimestampMs=(0,Nt.now)(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Pt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,s=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=s);){let o=this.downloadingBufferItems[n].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[n]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,n++}return i}prepareFetchParams(e,t){if(Qe(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,s={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:s,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=(0,Nt.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:s?s.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Nt.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,globalFrom:r,loaded:s,signal:n}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||(0,Nt.isNullable)(o)||(0,Nt.isNullable)(r)||n.aborted))for(let u of e){let{segment:c}=u,d=c.byte.from-r,l=c.byte.to-r,p=l-d+1,m=d<s,f=l<=s;c.size=p,m&&(c.networkStatus==="downloading"&&c.bufferStatus==="none"&&f?(c.data=new DataView(t.buffer,t.byteOffset+d,p),this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u),c.loadedBytes=Math.min(p,s-d),await this.onDownloadItem(u)):(0,Nt.isNonNullable)(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(p,s-d),f&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+d,c.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(Qe(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};var Kt=require("@vkontakte/videoplayer-shared");var $r=class extends Mr{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(s,{...n,priority:i});if(this.lastDataObtainedTimestampMs=(0,Kt.now)(),(0,Kt.isNullable)(o))return;let u=e[0],c=new DataView(o);u.segment.size=c.byteLength,u.segment.loadedBytes=c.byteLength,u.segment.data=c,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Pt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:async(n,o)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=(0,Kt.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:Kt.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!Qe(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:s}){let n=e[0],{segment:o}=n,u=this.representations.get(i);!this.downloadingBufferItems.length||(0,Kt.isNullable)(u)||(0,Kt.isNullable)(o.feedingBytes)||o.networkStatus!=="downloading"||s.aborted||(o.loadedBytes=r,o.loadedBytes>o.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(o.data=new DataView(t.buffer,t.byteOffset,o.loadedBytes),await this.onDownloadItem(n)))}updateRepresentationBaseUrl(e,t){if(!Qe(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var nl=j(Aa(),1),yS=j(mt(),1);var Ce=require("@vkontakte/videoplayer-shared");var io=class extends $r{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new Ce.ValueSubject(0);this.currentLowLatencySegmentLength$=new Ce.ValueSubject(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=s.isActiveLowLatency}updateManifest(t){if(!t||[...this.segments.values()].every(r=>!r.length))return;let i=(0,nl.default)(t.streams[this.kind],r=>r.representations);for(let r of i){if((0,Ce.isNullable)(r)||!Qe(r.segmentReference))return;let s=r.segmentReference.segments.map(d=>({...d,networkStatus:"none",bufferStatus:"none",size:void 0})),n=100,o=this.segments.get(r.id)??[],u=(0,yS.default)(o,-1)?.time.to??0,c=s?.findIndex(d=>u>=d.time.from+n&&u<=d.time.to+n);if(c===-1){let d=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,d)}else{let d=s.slice(c+1);this.segments.set(r.id,[...o,...d])}this.representations.set(r.id,r)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;(0,Ce.assertNonNullable)(t);let i=this.segments.get(t);if(i?.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t?.streams[this.kind],r=(0,nl.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if((0,Ce.isNullable)(r))return;let s=this.segments.get(r.id);if(s?.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}getRepresentationInitialTime(){if((0,Ce.isNullable)(this.playingRepresentationId))return 0;let t=this.representations.get(this.playingRepresentationId)?.segmentReference;return(0,Ce.isNullable)(t)||!Qe(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return{...super.prepareFetchParams(t,i),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:t,...i}){await super.onSomeDataLoaded({downloadingItems:t,...i}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),(0,Ce.isNullable)(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:s,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);s&&n&&this.currentLiveSegmentServerLatency$.next(n-s),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){let i=t.segment.data,r=this.representations.get(t.representationId)?.segmentReference;if((0,Ce.isNullable)(t.segment.data)||(0,Ce.isNullable)(r)||!Qe(r))return;let s=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:n}=r;t.segment.time.to=s.getChunkEndTime(i,n)}}updateLowLatencyLive(t){let i=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!Qe(s))return;let n=this.segments.get(r.id)??[],o=n.find(c=>Math.floor(c.time.from)===Math.floor(t.segment.time.from));if(o?.isCurrentLowLatency&&(o.time.to=t.segment.time.to,i=o.time.to-o.time.from,o.isCurrentLowLatency=!1),!!!n.find(c=>Math.floor(c.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let c=Math.round(t.segment.time.to*s.timescale/1e3).toString(10),d=kt(s.segmentTemplateUrl,{segmentTime:c});n.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:d,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){try{let s=this.tuning.dash.useFetchPriorityHints?i:"auto",n=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,s);this.initDataPromises.set(t.id,n);let{initMetadata:o,initDataView:u,segments:c}=await n??{};if(this.initDataPromises.delete(t.id),(0,Ce.isNullable)(u)||(0,Ce.isNullable)(c))return;o&&this.parsedInitData.set(t.id,o);let d=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,d);let l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(t.id,l),this.failedDownloads=0}catch(s){r&&this.error$.next({id:"LoadInits",category:Ce.ErrorCategory.WTF,message:"loadInit threw",thrown:s})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[],n=0,o=i.length-1;do s.unshift(i[o]),n+=i[o].time.to-i[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[s[0]]:s}};var ns=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new io(e,t,i,r):Qe(i[0].segmentReference)?new $r(e,t,i,r):new to(e,t,i,r)}};var ze=require("@vkontakte/videoplayer-shared");var gi=require("@vkontakte/videoplayer-shared");var CM=18,TS=!1;try{TS=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=CM}catch(a){console.error(a)}var ol=class{constructor(e,t=!1){this.bufferFull$=new gi.Subject;this.error$=new gi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:gi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};TS&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,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(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:gi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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,gi.assertNever)(t)}}},IS=ol;var vi=(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 os=class{constructor(e){this.error$=new ze.Subject;this.subscription=new ze.Subscription;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new IS(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add((0,ze.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ze.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}async clear(e){let t=this.getBufferState();if((0,ze.isNullable)(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&=await this.sourceBufferTaskQueue.remove(r.from,r.to,e);return i}warmUpMediaSource(){!(0,ze.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if((0,ze.isNullable)(this.sourceBuffer)||!he(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return(0,ze.isNullable)(this.sourceBuffer)||!he(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,ze.isNullable)(e)?0:vi(this.sourceBuffer.buffered,e)}async abortBuffer(e){return(0,ze.isNullable)(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){if(this.subscription.unsubscribe(),this.sourceBufferTaskQueue?.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null}};var ro=(a,e)=>{a.video.forEach(t=>{let i=t.representations.filter(({fps:r,height:s})=>{let n=e.find(([o])=>o===`${s}p`)?.[1];return n&&Number.isInteger(n)&&r&&Number.isInteger(r)?r<=n:!0});t.representations=i})};var LM=["timeupdate","progress","play","seeked","stalled","waiting"],ES=["timeupdate","progress","loadeddata","playing","seeked"],ao=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new T.Subscription;this.subscriptionRemovable=new T.SubscriptionRemovable;this.representationSubscription=new T.Subscription;this.forceEnded$=new T.Subject;this.destroyController=new me;this.state$=new Z("none");this.currentVideoRepresentation$=new T.ValueSubject(void 0);this.currentVideoRepresentationInit$=new T.ValueSubject(void 0);this.currentAudioRepresentation$=new T.ValueSubject(void 0);this.currentVideoSegmentLength$=new T.ValueSubject(0);this.currentAudioSegmentLength$=new T.ValueSubject(0);this.error$=new T.Subject;this.manifestRequested=new T.Subject;this.manifestReceived=new T.Subject;this.firstBytesRequested=new T.Subject;this.firstBytesReceived=new T.Subject;this.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=new T.ValueSubject(void 0);this.lastConnectionMetrics$=new T.ValueSubject(void 0);this.lastDownloadMetrics$=new T.ValueSubject(void 0);this.currentLiveTextRepresentation$=new T.ValueSubject(null);this.isLive$=new T.ValueSubject(!1);this.isActiveLive$=new T.ValueSubject(!1);this.isLowLatency$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveSeekableDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(0);this.liveStreamStatus$=new T.ValueSubject(void 0);this.currentBuffer$=new T.ValueSubject({from:0,to:0});this.bufferLength$=new T.ValueSubject(0);this.nativeBufferLength$=new T.ValueSubject(0);this.liveLatency$=new T.ValueSubject(void 0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.currentStallDuration$=new T.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new T.ValueSubject(0);this.fetcherRecoverableError$=new T.Subject;this.fetcherError$=new T.Subject;this.initRepresentations=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),(0,T.assertNonNullable)(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?this.audioBufferManager?.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=(0,T.abortable)(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){(0,T.isNullable)(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Qn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}async initManifest(e,t,i){this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:T.ErrorCategory.PARSER,message:"No playable video representations"})}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,T.merge)(...LM.map(t=>(0,T.fromEvent)(this.element,t)),(0,T.fromEvent)((0,T.getWindow)(),"online")).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add((0,T.merge)(...e.map(t=>(0,T.fromEvent)(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,T.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}async seek(e,t=!1){(0,T.assertNonNullable)(this.element),(0,T.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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await this.audioBufferManager?.seek(i),this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.isNonNullable)(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(t=>t.warmUpMediaSource())}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}get isStreamEnded(){return this.source?.readyState==="ended"}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(e=>e.destroy()),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&(0,T.getWindow)().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),(0,T.isNonNullable)(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){return this.source?.readyState!=="open"}async reinitDecoderIfNeeded(e=!1){let t=this.videoNativeBufferManager?.getBufferState()??[];if((0,T.isNullable)(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(r=>i>=r.from&&i<=r.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){(0,T.assertNonNullable)(this.element),(0,T.assertNonNullable)(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=(0,T.now)(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,c=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,d=(0,T.isNonNullable)(this.videoBufferManager)&&u<s&&r-n>i,l=(0,T.isNonNullable)(this.audioBufferManager)&&c<s&&r-o>i;return(d||l)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if((0,T.isNullable)(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",(0,T.flattenObject)(i)),i}parseManifest(e){try{return Gn(e??"",this.manifestUrlString)}catch(t){let i=qn(e)??{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:t};this.error$.next(i)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,c)=>!!(this.element?.canPlayType?.(u)&&st()?.isTypeSupported?.(`${u}; codecs="${c}"`)||o==="text"),r,s;for(let o of["video","audio"]){let c=e.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));t[o]=c;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=c.map(({codecs:p})=>p);o==="audio"&&(s=Zn(l),d=s[0]),o==="video"&&(r=Jn(l),this.forceVideoCodec&&(0,wS.default)(r,this.forceVideoCodec)?d=this.forceVideoCodec:d=r[0]),d&&(t[o]=c.filter(({codecs:p})=>Ar(p)===d))}else{let l=new Set(c.map(({codecs:p})=>p));d=Xn(l),d&&(t[o]=c.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=t.video.some(g=>g.hdr),m=t.video.some(g=>!g.hdr);F.display.isHDR&&l&&p?t.video=t.video.filter(g=>g.hdr):m&&(t.video=t.video.filter(g=>!g.hdr));let{videoStreamRepresentaionsFilter:f}=this.tuning.dash;f.length&&ro(t,f)}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:s}),n}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element);let s=c=>{this.representationSubscription.add((0,T.fromEvent)(c,"error").pipe((0,T.filter)(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=Qs();let n=(0,T.getWindow)().document,o=n.createElement("source");if(s(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),cr())if(r){let c=n.createElement("source");s(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;let u=this.manifest.streams.video.reduce((c,d)=>[...c,...d.representations],[]);if(this.videoNativeBufferManager=new os(this.source),this.videoBufferManager=ns.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],(0,T.isNonNullable)(i)){this.audioNativeBufferManager=new os(this.source);let c=this.manifest.streams.audio.reduce((d,l)=>[...d,...l.representations],[]);this.audioBufferManager=ns.getBufferManager("audio",this.audioNativeBufferManager,c,e),this.bufferManagers.push(this.audioBufferManager),this.nativeBufferManagers.push(this.audioNativeBufferManager)}}async waitStreamToOpen(){if(this.isStreamNotOpen){let e=this.tuning.dash.sourceOpenTimeout>=0;await new Promise(t=>{e&&(this.timeoutSourceOpenId=(0,T.getWindow)().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&(0,T.getWindow)().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),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(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.representationSubscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),(0,T.assertNonNullable)(this.videoBufferManager),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.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add((0,T.merge)(...ES.map(e=>(0,T.fromEvent)(this.element,e))).pipe((0,T.map)(e=>this.videoBufferManager?.getPlaybackBufferState()),(0,T.filter)(T.isNonNullable),(0,T.map)(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add((0,T.merge)(...ES.map(e=>(0,T.fromEvent)(this.element,e))).pipe((0,T.map)(e=>Math.max(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),(0,T.filterChanged)()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe((0,T.filter)(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=(0,T.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if((0,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=(this.videoNativeBufferManager?.getBufferState()??[]).find(r=>e>=r.from&&e<=r.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await this.audioBufferManager?.maintain(e)}};var le=require("@vkontakte/videoplayer-shared");var so=class extends ao{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){(0,le.assertNonNullable)(this.manifest),(0,le.assertNonNullable)(this.source);let e=[this.manifest.duration??0,...(0,ul.default)((0,ul.default)([...this.manifest.streams.audio,...this.manifest.streams.video],t=>t.representations),t=>{let i=[];return t.duration&&i.push(t.duration),Qe(t.segmentReference)&&t.segmentReference.totalSegmentsDurationMs&&i.push(t.segmentReference.totalSegmentsDurationMs),i})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){(0,le.assertNonNullable)(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){(0,le.assertNonNullable)(this.element);let e=(0,le.merge)((0,le.fromEvent)(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe((0,le.filter)(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add((0,le.merge)(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=(0,le.merge)(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe((0,le.map)(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=(0,le.merge)(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe((0,le.map)(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=(0,le.combine)({allBuffersFull:e,someBufferEnded:t}).pipe((0,le.filterChanged)(),(0,le.map)(({allBuffersFull:s,someBufferEnded:n})=>s&&n),(0,le.filter)(s=>s)),r=()=>{try{this.source?.endOfStream()}catch(s){this.error$.next({id:"EndOfStream",category:le.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:s})}};this.representationSubscription.add((0,le.merge)(this.forceEnded$,i).pipe((0,le.filter)(s=>(0,le.isNonNullable)(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var Cr=class extends ka{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,xS.filterChanged)()).subscribe(s=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:l}])=>l.id===s);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[o,{stream:u}]=n,c=this.params.desiredState.videoStream.getTransition();c&&c.to&&c.to.id===u.id&&this.params.desiredState.videoStream.setState(c.to),e.currentVideoTrack$.next(o),e.currentVideoStream$.next(Ln(u));let d=this.player.calculateDurationFromSegments();d&&this.params.output.duration$.next(d/1e3)},r))}getPlayer(){return new so({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var q=require("@vkontakte/videoplayer-shared");var RS=j(Ge(),1),pl=j(Aa(),1);var Si=(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 y=require("@vkontakte/videoplayer-shared");var no=j(Ge(),1),Qi=j(mt(),1),oo=j(Aa(),1);var AS=j(vc(),1);var yi=require("@vkontakte/videoplayer-shared");var DM=18,PS=!1;try{PS=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=DM}catch(a){console.error(a)}var cl=class{constructor(e,t=!1){this.bufferFull$=new yi.Subject;this.error$=new yi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:yi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};PS&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,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(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:yi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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,yi.assertNever)(t)}}},kS=cl;var ll=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var x=require("@vkontakte/videoplayer-shared");var us=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new x.ValueSubject(0);this.currentLowLatencySegmentLength$=new x.ValueSubject(0);this.currentSegmentLength$=new x.ValueSubject(0);this.onLastSegment$=new x.ValueSubject(!1);this.fullyBuffered$=new x.ValueSubject(!1);this.playingRepresentation$=new x.ValueSubject(void 0);this.playingRepresentationInit$=new x.ValueSubject(void 0);this.error$=new x.Subject;this.gaps=[];this.subscription=new x.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new me;this.switchAbortController=new me;this.destroyAbortController=new me;this.useSmartRepresentationSwitch=!1;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,x.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,x.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new kS(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!he(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ll(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let c=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,c<d).catch(l=>{this.handleAsyncError(l,"pruneBuffer")})})),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,x.assertNonNullable)(i,"No init buffer for starting representation"),(0,x.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.switchTo=(0,x.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!he(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,x.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,x.isNullable)(s)||(0,x.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,x.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,x.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=(0,x.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!he(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,x.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,x.isNullable)(s)||(0,x.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,x.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,x.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,x.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,oo.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let c=t.find(p=>p.id===u);c&&this.representations.set(u,c);let d=this.representations.get(u);if(!d||!ut(d.segmentReference)){this.isSeekingLive=!1;return}let l=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,l)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,x.assertNonNullable)(r,`Representation not found by id ${i}`);let s=this.segments.get(i);(0,x.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,x.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!c?.live,this.baseUrls=c?.baseUrls??[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!he(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new me,(0,x.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,x.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,x.isNullable)(o)||(0,x.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,x.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer))){if(yield 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,x.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))}warmUpMediaSource(){!(0,x.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new me,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,x.isNullable)(e)||(0,x.isNullable)(this.downloadingRepresentationId)||(0,x.isNullable)(this.playingRepresentationId)||(0,x.isNullable)(this.sourceBuffer)||!he(this.mediaSource,this.sourceBuffer)||(0,x.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if((0,x.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,x.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,x.isNullable)(r)||(0,x.isNullable)(s))return;let n=r.find(p=>e>=p.time.from&&e<p.time.to);(0,x.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=this.getForwardBufferDuration(e),m=bi(i),f=bi(t),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,x.isNonNullable)(m)&&(0,x.isNonNullable)(f)&&(0,x.isHigher)(m.quality,f.quality),v=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(g||v?o+=Math.min(p,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let E=[...this.segments.entries()].map(([A,w])=>{let D=w.find(N=>e>=N.time.from&&e<N.time.to);return{representationId:A,status:D?.status}}).find(A=>A.status==="fed")?.representationId;E&&(this.playingRepresentationId=E,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&ll(this.sourceBuffer.buffered)>=this.bufferLimit){let p=this.getForwardBufferDuration(e),m=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<m).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,no.default)(d,n))p="high";else{let m=(0,Qi.default)(d,0);m&&m.time.from-n.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(d,t,p).catch(m=>{this.handleAsyncError(m,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!d.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Qi.default)(r,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-l.time.from>0))}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,persistent:!0}),i=s.time.to;(0,x.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}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?.streams[this.kind];if(!t)return;let i=(0,oo.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,oo.default)(e.streams[this.kind],i=>i.representations);for(let i of t){if(!i||!ut(i.segmentReference))return;let r=i.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],o=(0,Qi.default)(n,-1)?.time.to??0,u=r?.findIndex(c=>o>=c.time.from+s&&o<=c.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,c)}else{let c=r.slice(u+1);this.segments.set(i.id,[...n,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,x.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Qi.default)(e,-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!ut(r))return;let s=this.segments.get(i.id)??[],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,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),c=kt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&qi&&qi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&qi&&qi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}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=this.getForwardBufferDuration(i),s=e.findIndex(({status:p,time:{from:m,to:f}},g)=>{let v=m<=i&&f>=i,S=m>i||v||g===0&&i===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&m<=i+E||r<E&&f-m>=E||f<=i+E;return(p==="none"||p==="partially_ejected"&&S&&A&&this.sourceBuffer&&he(this.mediaSource,this.sourceBuffer)&&!(Si(this.sourceBuffer.buffered,m)&&Si(this.sourceBuffer.buffered,f)))&&S&&A});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=d||u<=l);p++){let m=n[p];if(o+=m.byte.to+1-m.byte.from,u+=m.time.to+1-m.time.from,m.status==="none"||m.status==="partially_ejected")c.push(m);else break}return c}async loadSegments(e,t,i="auto"){ut(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,x.abortable)(o,async function*(){let d=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,x.now)(),!d)return;let l=new DataView(d),p=ji(t.mime);if(!isFinite(r.segment.time.to)){let g=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(l,g)}u&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,o);let{serverDataReceivedTimestamp:m,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(l);m&&f&&this.currentLiveSegmentServerLatency$.next(f-m),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Pt(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())ut(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,x.abortable)(n,async function*(){let u=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),(0,x.fromEvent)(window,"online").pipe((0,x.once)()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,x.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Pt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ut(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Qi.default)(e,0).byte.from,to:(0,Qi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,x.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ut(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,x.now)();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,no.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!he(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=ji(n.mime).parseFeedableSegmentChunk(c,this.isLive);d?.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!he(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let d=c.byte.from-i,l=c.byte.to-i,p=l-d+1,m=d<r,f=l<=r;if(!m)continue;let g=ji(o.mime);if(c.status==="downloading"&&f){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-d),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?v:g.parseFeedableSegmentChunk(v);S?.byteLength&&(c.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!((0,x.isNullable)(this.sourceBuffer)||!he(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Si(this.sourceBuffer.buffered,e.segment.time.from,100)&&Si(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",sl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");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||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Fi(()=>(0,AS.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?(0,x.abortable)(this.destroyAbortController.signal,async function*(){let u=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ji(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async u=>{if(!u)return;let{init:c,dataView:d,segments:l}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let m=l;this.isLive&&ut(e.segmentReference)&&(m=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,m),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,u=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:x.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,x.isNullable)(e))return!1;let r=[],s=0,n=u=>{u.sort((d,l)=>d.from-l.from);let c=[u[0]];for(let d=1;d<u.length;d++){let{from:l,to:p}=u[d],m=c[c.length-1];m.to>=l?m.to=Math.max(m.to,p):c.push(u[d])}return c},o=u=>{if(s>=t)return r;r.push({...u.time}),r=n(r);let c=sl(u)?u.size??0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let d=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,l=0;for(let p of this.segments.values())for(let m of p)(0,no.default)(["none","partially_ejected"],m.status)&&Math.round(m.time.from)<=Math.round(c)&&Math.round(m.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:c,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 c of this.segments.values())for(let d of c)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,d)=>c||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,x.isNullable)(e)?0:vi(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let o=s.start(n)*1e3,u=s.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Fi(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:x.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,x.isNullable)(this.sourceBuffer)||!he(this.mediaSource,this.sourceBuffer)||(0,x.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),c=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(c.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")}}handleAsyncError(e,t){this.error$.next({id:t,category:x.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var O=require("@vkontakte/videoplayer-shared");var co=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new O.Subject;this.firstBytesManifest$=new O.Subject;this.firstBytesRequested$=new O.Subject;this.firstBytesReceived$=new O.Subject;this.lastConnectionType$=new O.ValueSubject(void 0);this.lastConnectionReused$=new O.ValueSubject(void 0);this.lastRequestFirstBytes$=new O.ValueSubject(void 0);this.lastConnectionMetrics$=new O.ValueSubject(void 0);this.lastDownloadMetrics$=new O.ValueSubject(void 0);this.recoverableError$=new O.Subject;this.error$=new O.Subject;this.abortAllController=new me;this.subscription=new O.SubscriptionRemovable;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=(0,O.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=mi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Hn(i)),this.trackRequestStart(i,performance.now());let r=(0,O.now)();this.manifestRequested$.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(uo);if(s){let n=(0,O.now)();t.log("success",(0,O.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(s.headers),this.firstBytesManifest$.next();let o=s.headers.get("content-length"),u=0;o&&(u=parseInt(o,10));let c=await s.text();if((!o||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let d=n-r,p=u/(d/1e3)*8/1024,m={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(m)}return c}else return t.error("error",(0,O.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=(0,O.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:d=!1}={}){let l=e,p=new Headers,m=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let P=new URL(l,(0,O.getWindow)().location.href);P.searchParams.append("bytes",`${i.from}-${i.to}`),l=P.toString();break}default:(0,O.assertNever)(t)}this.requestQuic&&(l=mi(l));let f=this.abortAllController.signal,g;if(n){let P=new me;if(g=(0,O.merge)((0,O.fromEvent)(this.abortAllController.signal,"abort"),(0,O.fromEvent)(n,"abort")).subscribe(()=>{try{P.abort()}catch(X){uo(X)}}),this.subscription.add(g),this.abortAllController.signal.aborted||n.aborted)try{P.abort()}catch(X){uo(X)}f=P.signal}let v=0,S=(0,O.now)();m.log("startRequest",(0,O.flattenObject)({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.trackRequestStart(l,performance.now()),this.firstBytesRequested$.next();let E=yield this.doFetch(l,{priority:s,headers:p,signal:f},{ignoreNetworkErrors:d}),A=(0,O.now)();if(!E)return m.error("error",{message:"No response in request"}),m.end(),this.unsubscribeAbortSubscription(g),null;if(this.throughputEstimator?.addRawRtt(A-S),!E.ok||!E.body){this.unsubscribeAbortSubscription(g);let P=`Fetch error ${E.status}: ${E.statusText}`;return m.error("error",{message:P}),m.end(),Promise.reject(new Error(`Fetch error ${E.status}: ${E.statusText}`))}if(this.onHeadersReceived(E.headers),!r&&!o){this.unsubscribeAbortSubscription(g);let P=(0,O.now)(),X={requestStartedAt:S,requestEndedAt:P,duration:P-S};return m.log("endRequest",(0,O.flattenObject)(X)),m.end(),E.arrayBuffer()}let w=E.body;if(o){let P;[w,P]=E.body.tee(),this.throughputEstimator?.trackStream(P,u)}let D=w.getReader(),N,U=parseInt(E.headers.get("content-length")??"",10);Number.isFinite(U)&&(N=U),!N&&i&&(N=i.to-i.from+1);let B=N?new Uint8Array(N):new Uint8Array(0),Q=!1,C=P=>{this.unsubscribeAbortSubscription(g),Q=!0,uo(P)},re=(0,O.abortable)(f,async function*({done:P,value:X}){if(v===0&&(this.lastRequestFirstBytes$.next((0,O.now)()-S),this.firstBytesReceived$.next()),f.aborted){this.unsubscribeAbortSubscription(g);return}if(!P&&X){if(c&&N)B.set(X,v),v+=X.byteLength;else{let V=new Uint8Array(B.length+X.length);V.set(B),V.set(X,B.length),B=V,v+=X.byteLength}r?.(new DataView(B.buffer),v),yield D?.read().then(re,C)}}.bind(this));yield D?.read().then(re,C),this.unsubscribeAbortSubscription(g);let Y=(0,O.now)(),k={failed:Q,requestStartedAt:S,requestEndedAt:Y,duration:Y-S};if(Q)return m.error("endRequest",(0,O.flattenObject)(k)),m.end(),null;if(v>0){let P=Y-S,V=v/(P/1e3)*8/1024,ae={bytes:v,speed:V,url:e};this.lastDownloadMetrics$.next(ae)}return m.log("endRequest",(0,O.flattenObject)(k)),m.end(),B.buffer}.bind(this));this.fetchByteRangeRepresentation=(0,O.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,r),o=Math.max(d,s))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!l)return null;let p=new DataView(l,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let m=t.parseInit(p),f=e.indexRange??t.getIndexRange(m);if(!f)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(l,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,measureThroughput:!1});if(!S)return null;g=new DataView(S)}let v=t.parseSegments(g,m,f);return{init:m,dataView:new DataView(l),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,O.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s,(0,O.getWindow)().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=Un(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new((0,O.getWindow)()).PerformanceObserver(e=>{e.getEntriesByType("resource").forEach(t=>{this.processPerformanceResourceTiming(t)})}),this.performanceObserver.observe({entryTypes:["resource"]})}processPerformanceResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let r=this.extractConnectionMetrics(e);r&&this.lastConnectionMetrics$.next(r)}estimateNetworkType(){if(!("connection"in(0,O.getWindow)().navigator))return"unknown";let e=(0,O.getWindow)().navigator.connection;return e.effectiveType?{"slow-2g":"2g","2g":"2g","3g":"3g","4g":"lte"}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?"2g":e.downlink<5?"3g":e.downlink<50?"lte":"wifi":e.rtt?e.rtt>500?"2g":e.rtt>250?"3g":e.rtt>50?"lte":"wifi":"unknown"}extractConnectionMetrics(e){let t=0,i=0,r=0,s=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(s=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=s),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,s),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),s=r.origin+r.pathname,n=new URL(i.url),o=n.origin+n.pathname;if(s===o&&e.startTime>=i.startTime-10&&e.startTime<=i.startTime+1e3)return t}}catch{this.recoverableError$.next({id:"VideoDataFetchError",message:"Video data fetch error with getting download metrics",category:O.ErrorCategory.WTF})}return null}trackRequestStart(e,t){let i=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(i,{url:e,startTime:t})}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,O.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.pendingConnectionMetrics.clear(),this.tracer.end()}async doFetch(e,t,i){let r=await bt(e,t);if(r.ok)return r;if(i?.ignoreNetworkErrors)return;let s=await r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:O.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:O.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:O.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:O.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:O.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},uo=a=>{if(!Pt(a))throw a};var cs=require("@vkontakte/videoplayer-shared"),Ti=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new cs.ValueSubject(e.initial),this.debounced$=new cs.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new He(`raw_${t}`),this.smoothedSeries$=new He(`smoothed_${t}`),this.reportedSeries$=new He(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,cs.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 lo=class extends Ti{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Wt(this.slow,e,this.params.emaAlphaSlow),this.fast=Wt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var po=class extends Ti{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Vc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Wt(this.emaSmoothed,e,this.params.emaAlpha);let i=yg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var ho=class extends Ti{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?Wt(this.smoothed,t,this.params.emaAlpha):t}};var zi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new lo({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new po({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new ho({initial:e,label:"liveEdgeDelay",...t})}};var dl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var mo=require("@vkontakte/videoplayer-shared");var ls=class a{constructor(e,t){this.currentRepresentation$=new mo.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?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,mo.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,o=r.segments[s-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(c=>c.time.from<=e&&c.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of 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?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&ut(t.segmentReference))}};var _M=["timeupdate","progress","play","seeked","stalled","waiting"],OM=["timeupdate","progress","loadeddata","playing","seeked"];var fo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new y.Subscription;this.subscriptionRemovable=new y.SubscriptionRemovable;this.representationSubscription=new y.Subscription;this.state$=new Z("none");this.currentVideoRepresentation$=new y.ValueSubject(void 0);this.currentVideoRepresentationInit$=new y.ValueSubject(void 0);this.currentAudioRepresentation$=new y.ValueSubject(void 0);this.currentVideoSegmentLength$=new y.ValueSubject(0);this.currentAudioSegmentLength$=new y.ValueSubject(0);this.error$=new y.Subject;this.manifestRequested$=new y.Subject;this.firstBytesManifest$=new y.Subject;this.manifestReceived$=new y.Subject;this.firstBytesRequested$=new y.Subject;this.firstBytesReceived$=new y.Subject;this.lastConnectionType$=new y.ValueSubject(void 0);this.lastConnectionReused$=new y.ValueSubject(void 0);this.lastRequestFirstBytes$=new y.ValueSubject(void 0);this.lastConnectionMetrics$=new y.ValueSubject(void 0);this.lastDownloadMetrics$=new y.ValueSubject(void 0);this.currentLiveTextRepresentation$=new y.ValueSubject(null);this.isLive$=new y.ValueSubject(!1);this.isActiveLive$=new y.ValueSubject(!1);this.isLowLatency$=new y.ValueSubject(!1);this.liveDuration$=new y.ValueSubject(0);this.liveSeekableDuration$=new y.ValueSubject(0);this.liveAvailabilityStartTime$=new y.ValueSubject(0);this.liveStreamStatus$=new y.ValueSubject(void 0);this.bufferLength$=new y.ValueSubject(0);this.liveLatency$=new y.ValueSubject(void 0);this.liveLoadBufferLength$=new y.ValueSubject(0);this.livePositionFromPlayer$=new y.ValueSubject(0);this.currentStallDuration$=new y.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new y.ValueSubject(0);this.fetcherRecoverableError$=new y.Subject;this.fetcherError$=new y.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new y.Subject;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new me;this.initManifest=(0,y.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Oe(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:y.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,y.abortable)(this.destroyController.signal,async function*(){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:y.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Gn(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let c=qn(e)??{id:"ManifestParsing",category:y.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(c)}if(!t)return null;let i=(u,c,d)=>!!(this.element?.canPlayType?.(c)&&st()?.isTypeSupported?.(`${c}; codecs="${d}"`)||u==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:u,latestSegmentPublishTime:c,streamIsUnpublished:d,streamIsAlive:l}=t.live,p=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((c-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";if(l||(m=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m),l&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let f=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(f).catch(g=>{this.error$.next({id:"updateManifest",category:y.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:g})})}}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:m})=>i(u,p,m));r[u]=d;let l;if(this.tuning.dash.codecsPrioritizeEnabled){let p=d.map(({codecs:m})=>m);u==="audio"&&(n=Zn(p),l=n[0]),u==="video"&&(s=Jn(p),this.forceVideoCodec&&(0,RS.default)(s,this.forceVideoCodec)?l=this.forceVideoCodec:l=s[0]),l&&(r[u]=d.filter(({codecs:m})=>Ar(m)===l))}else{let p=new Set(d.map(({codecs:m})=>m));l=Xn(p),l&&(r[u]=d.filter(({codecs:m})=>m.startsWith(l)))}if(u==="video"){let p=this.tuning.preferHDR,m=r.video.some(v=>v.hdr),f=r.video.some(v=>!v.hdr);F.display.isHDR&&p&&m?r.video=r.video.filter(v=>v.hdr):f&&(r.video=r.video.filter(v=>!v.hdr));let{videoStreamRepresentaionsFilter:g}=this.tuning.dash;g.length&&ro(r,g)}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",(0,y.flattenObject)(o)),o}.bind(this));this.initRepresentations=(0,y.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,y.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,y.assertNonNullable)(this.manifest),(0,y.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add((0,y.fromEvent)(l,"error").pipe((0,y.filter)(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=Qs();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),cr())if(i){let l=document.createElement("source");r(l),l.type="application/x-mpegurl",l.src=i.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new us("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,y.isNonNullable)(t)){let l=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new us("audio",this.source,l,n),this.bufferManagers.push(this.audioBufferManager)}if(ls.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ls(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,y.merge)(...OM.map(l=>(0,y.fromEvent)(this.element,l))).pipe((0,y.map)(l=>this.element?vi(this.element.buffered,this.element.currentTime*1e3):0),(0,y.filterChanged)(),(0,y.tap)(l=>{l>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,y.merge)((0,y.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,y.filterChanged)()).subscribe(p=>this.liveStreamEndTimestamp=(0,y.now)())),this.subscription.add((0,y.fromEvent)(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:p}=this.tuning.dash;this.livePauseWatchdogSubscription=(0,y.interval)(p).subscribe(m=>{let f=Os(this.manifestUrlString,2);this.manifestUrlString=Oe(this.manifestUrlString,f+p,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,y.fromEvent)(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,y.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.map)(({isActiveLive:p,isLowLatency:m})=>p&&m),(0,y.filterChanged)()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||dl(this.element,1)})),this.representationSubscription.add((0,y.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.filter)(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let m=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add((0,y.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,y.filter)(({isLive:p})=>p),(0,y.filterChanged)((p,m)=>m.bufferLength<p.bufferLength),(0,y.map)(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let g=Os(this.manifestUrlString,2);return(p/2+m+f+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,y.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=p-g;if(this.isManualDecreasePlaybackInLive())return;let A=1;Math.abs(E)>v&&(A=1+Math.sign(E)*S),dl(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let l=0;this.representationSubscription.add((0,y.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,y.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,g=Os(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,A=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,w=isFinite(p)?p:m,D=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),N=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(N);let U="none";if(D?U="active_low_latency":this.isLowLatency$.getValue()&&N?(this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),U="active_low_latency"):g!==0&&w<S?U="live_forward_buffering":w<S+A&&(U="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),U==="live_forward_buffering"||U==="live_with_target_offset"){let B=l-(S+E),Q=this.normalizeLiveOffset(Math.trunc(g+B/f)),C=Math.abs(Q-g),re=0;!p||C<=this.tuning.dashCmafLive.offsetCalculationError?re=g:Q>0&&C>this.tuning.dashCmafLive.offsetCalculationError&&(re=Q),this.manifestUrlString=Oe(this.manifestUrlString,re,2)}(U==="live_with_target_offset"||U==="live_forward_buffering")&&(l=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:y.ErrorCategory.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let u=(0,y.merge)(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe((0,y.map)(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),c=(0,y.merge)(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe((0,y.map)(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue()))),d=(0,y.combine)({allBuffersFull:u,someBufferEnded:c}).pipe((0,y.filterChanged)(),(0,y.map)(({allBuffersFull:l,someBufferEnded:p})=>l&&p),(0,y.filter)(l=>l));if(this.representationSubscription.add((0,y.merge)(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add((0,y.merge)(...this.bufferManagers.map(l=>l.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"){let l=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{l&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let l=[this.manifest.duration??0,...(0,pl.default)((0,pl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let m=[];return p.duration&&m.push(p.duration),ut(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...l)/1e3}this.audioBufferManager&&(0,y.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=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,y.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:y.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new co({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.subscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.liveBuffer=zi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){(0,y.assertNonNullable)(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?(0,y.now)()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Oe(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){(0,y.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,y.merge)(..._M.map(e=>(0,y.fromEvent)(this.element,e)),(0,y.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:y.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,y.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,y.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&Si(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let d=this.currentStallDuration$.getValue();d+=n,this.currentStallDuration$.next(d);let l={timeInWaiting:d},p=(0,y.now)(),m=100,f=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(f);let g=this.audioBufferManager?.lastDataObtainedTimestamp??0,v=this.videoBufferManager?.getForwardBufferDuration()??0,S=this.audioBufferManager?.getForwardBufferDuration()??0,E=v<m&&p-f>r,A=this.audioBufferManager&&S<m&&p-g>r;if((!t||c)&&((E||A)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(o&&d%s===0){let w=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(w),this.updateManifest()):this.seekLive(w).catch(D=>{this.error$.next({id:"stallIntervalCallback",category:y.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:D})}),l.liveLastOffset=w}else{let w=this.element.currentTime*1e3;this.videoBufferManager?.maintain(w),this.audioBufferManager?.maintain(w),l.position=w}this.tracer.log("stallIntervalCallback",(0,y.flattenObject)(l))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,y.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:y.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(0,y.assertNonNullable)(this.element),(0,y.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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Si(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,y.isNullable)(this.element)||(0,y.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,y.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,y.isNonNullable)(this.element)&&(0,y.isNonNullable)(this.source)&&(0,y.isNonNullable)(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,y.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let c of u.gaps)(r&&c.persistent||u.playingRepresentation$.getValue()===c.representation)&&c.from-o<=s&&c.to+o>s&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?n.push(1/0):n.push(c.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,y.flattenObject)(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var tt=require("@vkontakte/videoplayer-shared"),bo=class{constructor(){this.subscription=new tt.Subscription;this.pipSize$=new tt.ValueSubject(void 0);this.videoSize$=new tt.ValueSubject(void 0);this.elementSize$=new tt.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=tt.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,tt.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,tt.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,tt.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Wi=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new Z("stopped");this.observableVideo=null;this.droppedFramesManager=new Ir;this.stallsManager=new _n;this.elementSizeManager=new bo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new di;this.audioTrackSwitchHistory=new di;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(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(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"),L(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&L(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return(0,q.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Er(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new ht(e.source.url),this.params=e,this.video=Ye(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(Fe(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 fo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,q.isNullable)(this.observableVideo)&&(this.observableVideo=Je(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:q.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,q.filter)(l=>!!l.length),(0,q.once)()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,q.map)(l=>l.to.state!=="none"),(0,q.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.currentBuffer$,e.currentNativeBuffer$),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.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),s(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,q.filter)(q.isNonNullable),(0,q.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,q.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Vt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),hi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Xe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(ft(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams(),m=this.player.getCodecs();if((0,q.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let g=[];for(let v of p.audio){g.push(rl(v));let S=[];for(let E of v.representations){let A=ss(E);S.push(A),this.audioTracksMap.set(A,{stream:v,representation:E})}this.audioStreamsMap.set(v,S)}this.params.output.availableAudioStreams$.next(g)}let f=[];for(let g of p.video){f.push(al(g));let v=[];for(let S of g.representations){let E=bi({...S,streamId:g.id});E&&(v.push(E),this.videoTracksMap.set(E,{stream:g,representation:S}))}this.videoStreamsMap.set(g,v)}this.params.output.availableVideoStreams$.next(f);for(let g of p.text)for(let v of g.representations){let S=gS(g,v);this.textTracksMap.set(S,{stream:g,representation:v})}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),m?.video&&this.params.output.availableVideoCodecs$.next(m.video),m?.audio&&this.params.output.availableAudioCodecs$.next(m.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=(0,q.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,q.fromEvent)(this.video,"progress")).pipe((0,q.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe((0,q.throttle)(u))),this.subscription.add(o.subscribe(async()=>{let l=this.player.state$.getState(),p=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let m=this.selectVideoAudioRepresentations();if(!m)return;let[f,g]=m,v=[...this.videoTracksMap.keys()].find(E=>this.videoTracksMap.get(E)?.representation.id===f.id);(0,q.isNonNullable)(v)&&(this.stallsManager.lastVideoTrackSelected=v);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),l==="manifest_ready")await this.player.initRepresentations(f.id,g?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),g){let E=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",g.id,E)}},r)),this.subscription.add((0,q.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,q.merge)((0,q.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,q.map)(l=>l.to)))}).pipe((0,q.map)(({videoState:l,autoVideoTrackState:p})=>l.to!=="stopped"&&p),(0,q.filterChanged)()).subscribe(l=>this.player.setSmartRepresentationSwitch(l))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,q.filterChanged)()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:S}])=>S.id===l);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[m,{stream:f}]=p,g=this.params.desiredState.videoStream.getTransition();g&&g.to&&g.to.id===f.id&&this.params.desiredState.videoStream.setState(g.to),e.currentVideoTrack$.next(m),e.currentVideoStream$.next(al(f));let v=this.player.calculateDurationFromSegments();v&&this.params.output.duration$.next(v/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,q.filterChanged)()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:v}])=>v.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[m,{stream:f}]=p,g=this.params.desiredState.audioStream.getTransition();g&&g.to&&g.to.id===f.id&&this.params.desiredState.audioStream.setState(g.to),e.currentAudioStream$.next(rl(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),this.params.tuning.spherical?.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)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe((0,q.map)(({to:l})=>l==="ready"),(0,q.filterChanged)());this.subscription.add((0,q.merge)(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,q.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),m=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(m)})),this.subscription.add((0,q.merge)(c,this.player.state$.stateChangeEnded$,(0,q.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=(0,q.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ya:Sa,t=this.params.tuning.useNewAutoSelectVideoTrack?Mn:Rn,i=this.params.tuning.useNewAutoSelectVideoTrack?_t:An,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:B})=>B===o),c=s.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:B})=>B===d.id),p=l&&this.videoStreamsMap.get(l);if(!p)return;let m=vi(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,v=Math.min(m/Math.min(f,g||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),E=[...this.audioStreamsMap.keys()].find(({id:B})=>B===S?.id)??this.audioStreamsMap.keys().next().value,A=0;if(E){if(u&&!n){let B=e(u,p,this.audioStreamsMap.get(E)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);A=Math.max(A,B?.bitrate??-1/0)}if(c){let B=e(c,p,this.audioStreamsMap.get(E)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);A=Math.max(A,B?.bitrate??-1/0)}}let w=u;(n||!w)&&(w=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:A,forwardBufferHealth:v,current:c,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}));let D=E&&t(w,p,this.audioStreamsMap.get(E)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),N=this.videoTracksMap.get(w)?.representation,U=D&&this.audioTracksMap.get(D)?.representation;if(N&&U)return[N,U];if(N&&!U&&this.audioTracksMap.size===0)return[N,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ze(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(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}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ke(this.video),this.tracer.end()}};var ds=class extends Wi{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 pe=require("@vkontakte/videoplayer-shared");var ps=class extends Wi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new pe.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,pe.filterChanged)()).subscribe(u=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!u&&!c&&l?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe((0,pe.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,pe.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,pe.map)(({liveBufferTime:u,liveAvailabilityStartTime:c})=>u&&c?u*1e3+c+t:void 0)).subscribe(i.liveTime$)).add((0,pe.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,pe.merge)(r.playbackRateState$,new pe.ValueSubject(1))}).pipe((0,pe.filter)(({liveStreamStatus:u,liveDuration:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let d=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-p||this.video.paused||(0,pe.isNullable)(d)||(t=u-d)})).add((0,pe.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,pe.merge)(r.playbackRateState$,new pe.ValueSubject(1))}).pipe((0,pe.filterChanged)((u,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||(0,pe.isNullable)(u)||(0,pe.isNullable)(c))return;let m=-1*(c-u-t);i.position$.next(Math.min(m,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=vS(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,pe.filter)(u=>(0,pe.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var MS="X-Playback-Duration",hl=async a=>{let e=await bt(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(MS)?parseInt(e.headers.get(MS),10):void 0};var ie=require("@vkontakte/videoplayer-shared");var fl=j(Cu(),1);var go=require("@vkontakte/videoplayer-shared");var FM=a=>{let e=null;if(a.QUALITY&&(e=li(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,go.videoSizeToQuality)({width:t,height:i})}return e??null},qM=(a,e)=>{let t=a.split(`
178
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Zv=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?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},kt=(a,e)=>{let t=a;t=(0,Jc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,eS.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Jc.default)(t,n,(o,u)=>(0,$a.isNullable)(s)?o:(0,$a.isNullable)(u)?s:(0,tS.default)(s,parseInt(u,10),"0"))}return t},Gn=(a,e)=>{let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Q=>Q.textContent?.trim()??""),o=(0,iS.default)(n,0)??"",u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),l=s.getElementsByTagName("vk:Attrs")[0],p=l?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,m=l?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=l?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,g=l?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,v;u&&(v={availabilityStartTime:c?new Date(c).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:m==="yes",streamIsUnpublished:f==="yes"});let S,E=s.getAttribute("mediaPresentationDuration"),A=[...s.getElementsByTagName("Period")],w=A.reduce((Q,C)=>({...Q,[C.id]:C.children}),{}),D=A.reduce((Q,C)=>({...Q,[C.id]:C.getAttribute("duration")}),{});E?S=Zv(E):(0,Zc.default)(D).filter(Q=>Q).length&&!u?S=(0,Zc.default)(D).reduce((Q,C)=>Q+(Zv(C)??0),0):g&&(S=parseInt(g,10));let N=0,U=s.getAttribute("profiles")?.split(",")??[];for(let Q of A.map(C=>C.id))for(let C of w[Q]){let re=C.getAttribute("id")??"id"+(N++).toString(10),Y=C.getAttribute("mimeType")??"",k=C.getAttribute("codecs")??"",P=C.getAttribute("contentType")??Y?.split("/")[0],X=C.getAttribute("profiles")?.split(",")??[],V=Jv(C.getAttribute("lang")??"")??{},ae=C.querySelector("Label")?.textContent?.trim()??void 0,de=C.querySelectorAll("Representation"),ye=C.querySelector("SegmentTemplate"),Pe=C.querySelector("Role")?.getAttribute("value")??void 0,Le=P,De={id:re,language:V.language,isDefault:Pe==="main",label:ae,codecs:k,hdr:Le==="video"&&Xc(k),mime:Y,representations:[]};for(let ne of de){let te=ne.getAttribute("lang")??void 0,Be=ae??C.getAttribute("label")??ne.getAttribute("label")??void 0,qe=ne.querySelector("BaseURL")?.textContent?.trim()??"",ke=new URL(qe||o,e).toString(),lt=ne.getAttribute("mimeType")??Y,Zt=ne.getAttribute("codecs")??k??"",vt;if(P==="text"){let it=ne.getAttribute("id")||"",ei=V.privateuse?.includes("x-auto")||it.includes("_auto"),St=ne.querySelector("SegmentTemplate");if(St){let Vr={representationId:ne.getAttribute("id")??void 0,bandwidth:ne.getAttribute("bandwidth")??void 0},Ss=parseInt(ne.getAttribute("bandwidth")??"",10)/1e3,ys=parseInt(St.getAttribute("startNumber")??"",10)??1,Yi=parseInt(St.getAttribute("timescale")??"",10),Io=St.querySelectorAll("SegmentTimeline S")??[],Ki=St.getAttribute("media");if(!Ki)continue;let Ts=[],Is=0,Es="",Xi=0,_r=ys,Ue=0;for(let yt of Io){let Ii=parseInt(yt.getAttribute("d")??"",10),dt=parseInt(yt.getAttribute("r")??"",10)||0,ti=parseInt(yt.getAttribute("t")??"",10);Ue=Number.isFinite(ti)?ti:Ue;let Ei=Ii/Yi*1e3,Ji=Ue/Yi*1e3;for(let Rt=0;Rt<dt+1;Rt++){let ii=kt(Ki,{...Vr,segmentNumber:_r.toString(10),segmentTime:(Ue+Rt*Ii).toString(10)}),Zi=(Ji??0)+Rt*Ei,Nr=Zi+Ei;_r++,Ts.push({time:{from:Zi,to:Nr},url:ii})}Ue+=(dt+1)*Ii,Is+=(dt+1)*Ei}Xi=Ue/Yi*1e3,Es=kt(Ki,{...Vr,segmentNumber:_r.toString(10),segmentTime:Ue.toString(10)});let Or={time:{from:Xi,to:1/0},url:Es},qt={type:"template",baseUrl:ke,segmentTemplateUrl:Ki,initUrl:"",totalSegmentsDurationMs:Is,segments:Ts,nextSegmentBeyondManifest:Or,timescale:Yi};vt={id:it,kind:"text",segmentReference:qt,profiles:[],duration:S,bitrate:Ss,mime:"",codecs:"",width:0,height:0,isAuto:ei}}else vt={id:it,isAuto:ei,kind:"text",url:ke}}else{let it=ne.getAttribute("contentType")??lt?.split("/")[0]??P,ei=C.getAttribute("profiles")?.split(",")??[],St=parseInt(ne.getAttribute("width")??"",10),Vr=parseInt(ne.getAttribute("height")??"",10),Ss=parseInt(ne.getAttribute("bandwidth")??"",10)/1e3,ys=ne.getAttribute("frameRate")??"",Yi=ne.getAttribute("quality")??void 0,Io=ys?Xv(ys):void 0,Ki=ne.getAttribute("id")??"id"+(N++).toString(10),Ts=it==="video"?`${Vr}p`:it==="audio"?`${Ss}Kbps`:Zt,Is=`${Ki}@${Ts}`,Es=[...U,...X,...ei],Xi,_r=ne.querySelector("SegmentBase"),Ue=ne.querySelector("SegmentTemplate")??ye;if(_r){let qt=ne.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[yt,Ii]=qt.split("-").map(ii=>parseInt(ii,10)),dt={from:yt,to:Ii},ti=ne.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ei,Ji]=ti?ti.split("-").map(ii=>parseInt(ii,10)):[],Rt=ti?{from:Ei,to:Ji}:void 0;Xi={type:"byteRange",url:ke,initRange:dt,indexRange:Rt}}else if(Ue){let qt={representationId:ne.getAttribute("id")??void 0,bandwidth:ne.getAttribute("bandwidth")??void 0},yt=parseInt(Ue.getAttribute("timescale")??"",10),Ii=Ue.getAttribute("initialization")??"",dt=Ue.getAttribute("media"),ti=parseInt(Ue.getAttribute("startNumber")??"",10)??1,Ei=kt(Ii,qt);if(!dt)throw new ReferenceError("No media attribute in SegmentTemplate");let Ji=Ue.querySelectorAll("SegmentTimeline S")??[],Rt=[],ii=0,Zi="",Nr=0;if(Ji.length){let ws=ti,Tt=0;for(let er of Ji){let Mt=parseInt(er.getAttribute("d")??"",10),wi=parseInt(er.getAttribute("r")??"",10)||0,xs=parseInt(er.getAttribute("t")??"",10);Tt=Number.isFinite(xs)?xs:Tt;let Eo=Mt/yt*1e3,ZS=Tt/yt*1e3;for(let Ps=0;Ps<wi+1;Ps++){let ey=kt(dt,{...qt,segmentNumber:ws.toString(10),segmentTime:(Tt+Ps*Mt).toString(10)}),wl=(ZS??0)+Ps*Eo,ty=wl+Eo;ws++,Rt.push({time:{from:wl,to:ty},url:ey})}Tt+=(wi+1)*Mt,ii+=(wi+1)*Eo}Nr=Tt/yt*1e3,Zi=kt(dt,{...qt,segmentNumber:ws.toString(10),segmentTime:Tt.toString(10)})}else if((0,$a.isNonNullable)(S)){let Tt=parseInt(Ue.getAttribute("duration")??"",10)/yt*1e3,er=Math.ceil(S/Tt),Mt=0;for(let wi=1;wi<er;wi++){let xs=kt(dt,{...qt,segmentNumber:wi.toString(10),segmentTime:Mt.toString(10)});Rt.push({time:{from:Mt,to:Mt+Tt},url:xs}),Mt+=Tt}Nr=Mt,Zi=kt(dt,{...qt,segmentNumber:er.toString(10),segmentTime:Mt.toString(10)})}let JS={time:{from:Nr,to:1/0},url:Zi};Xi={type:"template",baseUrl:ke,segmentTemplateUrl:dt,initUrl:Ei,totalSegmentsDurationMs:ii,segments:Rt,nextSegmentBeyondManifest:JS,timescale:yt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!it||!lt)continue;let Or={video:"video",audio:"audio",text:"text"}[it];if(!Or)continue;Le||=Or,vt={id:Is,kind:Or,segmentReference:Xi,profiles:Es,duration:S,bitrate:Ss,mime:lt,codecs:Zt,width:St,height:Vr,fps:Io,quality:Yi}}De.language||=te,De.label||=Be,De.mime||=lt,De.codecs||=Zt,De.hdr||=Le==="video"&&Xc(Zt),De.representations.push(vt)}if(Le){let ne=r[Le].find(te=>te.id===De.id);if(ne&&De.representations.every(te=>te.segmentReference.type==="template"))for(let te of ne.representations){let Be=De.representations.find(lt=>lt.id===te.id);if(!Be)continue;let qe=Be.segmentReference,ke=te.segmentReference;ke.segments.push(...qe.segments),ke.nextSegmentBeyondManifest=qe.nextSegmentBeyondManifest}else r[Le].push(De)}}return{duration:S,streams:r,baseUrls:n,live:v}};var Kn=j(mt(),1),el=j(Ge(),1),La=require("@vkontakte/videoplayer-shared");var Ca=(s=>(s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient",s))(Ca||{});var Yn=a=>{let{webmDecodingInfo:e}=F.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:(0,La.assertNever)(a)}},rS=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Yn(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(F.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...Yn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Yn(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Yn(a),...s,"HLS","HLS_ONDEMAND"];default:(0,La.assertNever)(e)}if(F.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:(0,La.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},aS=({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=F.device.isMac&&F.browser.isSafari;if(F.device.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,La.assertNever)(a)}else F.video.nativeHlsSupported&&!u&&!F.browser.isChromiumBased?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"]},tl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Xn=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Kn.default)(t.value.split("."),0)}for(let t of a){let i=(0,Kn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Kn.default)(e.value.split("."),0)},Jn=a=>{let e=a.map(i=>Ar(i)),{codecs:t}=F.video;return pM().filter(i=>{if((0,el.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},Zn=a=>{let e=a.map(i=>Ar(i)),{codecs:t}=F.video;return hM().filter(i=>{if((0,el.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Ar=a=>a.split(".")[0].replace("0",""),pM=()=>["av1","vp9","hev1","avc1"],hM=()=>["opus","mp4a"];var SS=j(mt(),1);var mM=(a,e={})=>{let i=e.timeout||1,r=performance.now();return xe.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},fM=a=>xe.clearTimeout(a),sS=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),nS=!sS(xe.requestIdleCallback)||!sS(xe.cancelIdleCallback),Fi=nS?mM:xe.requestIdleCallback,qi=nS?fM:xe.cancelIdleCallback;var M=require("@vkontakte/videoplayer-shared");var uS=j(mt(),1);var eo=a=>a.valid,oe=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}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 Rr=class extends oe{};var oS=require("@vkontakte/videoplayer-shared");var Da=class extends oe{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:(0,oS.assertNever)(e)}}};var Ba=class extends oe{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var Va=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var be=class extends oe{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var _a=class extends be{constructor(e,t){super(e,t),this.valid&&(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 Oa=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Na=class extends oe{constructor(e,t){super(e,t),this.data=this.content}};var Ui=class extends be{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}}};var Fa=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qa=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ua=class extends be{constructor(e,t){if(super(e,t),!this.valid)return;switch(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 Ha=class extends be{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var ja=class extends be{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Qa=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var za=class extends be{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 Wa=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ga=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends be{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Ka=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xa=class extends be{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 Ja=class extends be{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 Za=class extends be{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 es=class extends oe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ts=class extends be{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var is=class extends oe{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var gM={ftyp:Ba,moov:Va,mvhd:_a,moof:Oa,mdat:Na,sidx:Ui,trak:Fa,mdia:Qa,mfhd:Ya,tkhd:za,traf:Ka,tfhd:Xa,tfdt:Ja,trun:Za,minf:Wa,sv3d:qa,st3d:Ua,prhd:Ha,proj:Ga,equi:ja,uuid:Da,stbl:es,stsd:ts,avc1:is,unknown:Rr},Gt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!eo(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=gM[e];return i?new i(t,new a):new Rr(t,new a)}};var fi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{eo(t)&&(this.index[t.type]??=[],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 SM=new TextDecoder("ascii"),yM=a=>SM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",TM=a=>{let e=new Ui(a,new Gt),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})},IM=(a,e)=>{let i=new Gt().parse(a),r=new fi(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,l)},EM=a=>{let t=new Gt().parse(a),i=new fi(t),r={},s=i.findAll("uuid"),n=(0,uS.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},wM=a=>{let t=new Gt().parse(a);return new fi(t).find("sidx")?.timescale},xM=(a,e)=>{let i=new Gt().parse(a),s=new fi(i).findAll("traf"),n=s[s.length-1].children.find(l=>l.type==="tfhd"),o=s[s.length-1].children.find(l=>l.type==="tfdt"),u=s[s.length-1].children.find(l=>l.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((l,p)=>l+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},PM=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 Gt().parse(a),r=new fi(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},cS={validateData:yM,parseInit:PM,getIndexRange:()=>{},parseSegments:TM,parseFeedableSegmentChunk:IM,getChunkEndTime:xM,getServerLatencyTimestamps:EM,getTimescaleFromIndex:wM};var as=j(Ge(),1),Yt=require("@vkontakte/videoplayer-shared");var dS=require("@vkontakte/videoplayer-shared");var lS={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"}},pS=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=rs(a,t),r=i in lS,s=r?lS[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,d=rs(u),l=c*2**((o-1)*8)+d,p=t+o,m;return p+l>a.byteLength?m=new DataView(a.buffer,a.byteOffset+p):m=new DataView(a.buffer,a.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:m,valueSize:l}},rs=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},At=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return rs(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,dS.assertNever)(e)}},Hi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=pS(i);if(!e(r))return;r.type==="master"&&Hi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},hS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=pS(a);return Hi(r.value,({tag:s,type:n,value:o})=>(s===17143?e=At(o,n):s===17026?t=At(o,n):s===17029&&(i=At(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var mS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],kM=[231,22612,22743,167,171,163,160,175],AM=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,c,d=!1,l=0;return Hi(a,({tag:p,type:m,value:f,valueSize:g})=>{if(p===21419){let v=At(f,m);c=rs(v)}else p!==21420&&(c=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=At(f,m):p===17545?r=At(f,m):p===21420&&c===475249515?u=At(f,m):p===374648427?Hi(f,({tag:v,type:S,value:E})=>v===30321?(d=At(E,S)===1,!1):!0):s&&n&&(0,as.default)(mS,p)&&(o=!0),!o}),(0,Yt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Yt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Yt.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=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:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},RM=a=>{if((0,Yt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},MM=(a,e)=>{let t=!1,i=!1,r=o=>(0,Yt.isNonNullable)(o.time)&&(0,Yt.isNonNullable)(o.position),s=[],n;return Hi(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=At(c,u));break;case 183:break;case 241:n&&(n.position=At(c,u));break;default:t&&(0,as.default)(mS,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:d}=o,l=s[u+1];return{status:"none",time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},$M=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):(0,as.default)(kM,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,as.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},fS={validateData:hS,parseInit:AM,getIndexRange:RM,parseSegments:MM,parseFeedableSegmentChunk:$M};var ji=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return fS;case"mp4":return cS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var il=j(mt(),1);var bS=require("@vkontakte/videoplayer-shared"),bi=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let o=(s?li(s):void 0)??(0,bS.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},ss=({id:a,bitrate:e})=>({id:a,bitrate:e}),gS=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),vS=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),rl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,il.default)(i.split("."),0),isDefault:r}),al=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,il.default)(r.split("."),0)}),sl=a=>"url"in a,ut=a=>a.type==="template";var Mr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,manifest:o}){this.error$=new M.Subject;this.playingRepresentation$=new M.ValueSubject(void 0);this.playingRepresentationInit$=new M.ValueSubject(void 0);this.currentSegmentLength$=new M.ValueSubject(0);this.onLastSegment$=new M.ValueSubject(!1);this.fullyBuffered$=new M.ValueSubject(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new me;this.downloadAbortController=new me;this.subscription=new M.Subscription;this.startWith=(0,M.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,M.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=ji(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,M.assertNonNullable)(i,"No init buffer for starting representation"),(0,M.assertNonNullable)(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s)}.bind(this));this.switchTo=(0,M.abortable)(this.destroyAbortController.signal,async function*(e,t=!0){if((0,M.isNullable)(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);(0,M.assertNonNullable)(r,`No such representation ${e}`),(0,M.assertNonNullable)(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let s=this.initData.get(r.id),n=this.segments.get(r.id);(0,M.assertNonNullable)(s,"No init buffer for switching representation"),(0,M.assertNonNullable)(n,"No segments for switching representation");let o=this.getCurrentPosition()??0,u=l=>l.segment.networkStatus!=="downloaded"||l.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,c=l=>{let p=this.representations.get(l.representationId);return(0,M.assertNonNullable)(p,"No itemRepresentation for previous track before switch"),l.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(p,r)},d=l=>t?u(l)&&c(l):u(l);this.bufferPlaybackQueue.filter(d).forEach(l=>l.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(l=>!d(l)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=(0,M.abortable)(this.downloadAbortController.signal,async function*(){let e=(0,M.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=(0,M.getWindow)();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add((0,M.fromEvent)(i,"online").pipe((0,M.once)()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=s,this.getCurrentPosition=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.baseUrls=o?.baseUrls??[],this.representations=new Map(i.map(u=>[u.id,u]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){(0,M.isNullable)(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return(0,M.isNonNullable)(t)&&(0,M.isNonNullable)(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){let t=this.downloadingRepresentationId??this.playingRepresentationId??"";return this.segments.get(t)?.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from}getRepresentationInitialTime(){return(0,M.isNullable)(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}calculateDurationFromSegments(){if((0,M.isNullable)(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,SS.default)(e,-1)?.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=(0,M.getWindow)();if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),e.__polyfill_cancelIdleCallback_10c8n03b79nlf)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_10c8n03b79nlf(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=bi(e),s=bi(t);i=(0,M.isNonNullable)(r)&&(0,M.isNonNullable)(s)&&(0,M.isHigher)(s.quality,r.quality)}else if(this.kind==="audio"){let r=ss(e),s=ss(t);i=(0,M.isNonNullable)(r?.bitrate)&&(0,M.isNonNullable)(s?.bitrate)&&s.bitrate>r.bitrate}return i}async clearBuffer(){this.bufferClearingMutex=!0,await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new me,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}async abortNativeBuffer(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=await this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,this.maintainNativeBufferMutex=!1,i}async loadInits(e){await this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,Fi(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),s;this.initData.has(e.id)&&this.segments.has(e.id)?s=Promise.resolve():(0,M.isNonNullable)(r)?s=r:s=this.loadInit(e,t,i),await s}async loadInit(e,t="auto",i=!1){try{let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r);this.initDataPromises.set(e.id,s);let{initMetadata:n,initDataView:o,segments:u}=await s??{};if(this.initDataPromises.delete(e.id),(0,M.isNullable)(o)||(0,M.isNullable)(u))return;n&&this.parsedInitData.set(e.id,n);let c=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,u),this.failedDownloads=0}catch(r){i&&this.error$.next({id:"LoadInits",category:M.ErrorCategory.WTF,message:"loadInit threw",thrown:r})}}async maintainNativeBuffer(){let e=this.getCurrentPosition();if((0,M.isNullable)(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(o=>this.withinInterval(e,o.segment.time)),i=this.bufferPlaybackQueue.find(o=>o.segment.bufferStatus!=="fed"),r=this.initData.get(i?.representationId??""),s=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;(0,M.isNonNullable)(r)&&(0,M.isNonNullable)(i)&&(0,M.isNonNullable)(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),(0,M.isNonNullable)(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,n):await this.appendSegmentPartially(i,n)),(0,M.isNonNullable)(s)&&this.withinRemoveInterval(e,s.segment.time)&&await this.removeSegment(s,n),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){(0,M.assertNonNullable)(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if((0,M.isNullable)(t)||(0,M.isNullable)(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(n=>e>=n.time.from&&e<n.time.to);(0,M.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let s=this.selectItemsToLoad();await this.loadItems(s,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){let t=this.segments.get(this.downloadingRepresentationId??"");if((0,M.isNullable)(t)||t.length===0)return;let i=t[t?.length-1];(0,M.isNullable)(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){(0,M.assertNonNullable)(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,s;(0,M.isNonNullable)(i)&&this.withinInterval(e,i)?(s=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(s=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&s>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;s-=u-o,r++}return n}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return(0,M.isNonNullable)(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return(0,M.isNonNullable)(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return(0,M.isNonNullable)(e)?e-i>t:!1}async appendSegmentFully(e,t){if((0,M.isNullable)(e.segment.data))return;e.segment.feedingBytes=e.segment.size,await this.nativeBufferManager.append(e.segment.data,t)&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))}async appendSegmentPartially(e,t){if((0,M.isNullable)(e.segment.data)||(0,M.isNullable)(e.segment.loadedBytes)||(0,M.isNullable)(e.segment.feedingBytes)||(0,M.isNullable)(e.segment.fedBytes)||(0,M.isNullable)(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),s=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;s?.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=s.byteLength,await this.nativeBufferManager.append(s,t)&&(e.segment.fedBytes+=s.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,s=(r-i)/4;await this.nativeBufferManager.remove(0,r-s,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||(0,M.isNonNullable)(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let s=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)(0,M.isNonNullable)(o.size)&&s>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())(0,M.isNonNullable)(o.size)&&s>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size)}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())this.updateRepresentationBaseUrl(t,e)}};var Nt=require("@vkontakte/videoplayer-shared");var to=class extends Mr{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(s,{...n,priority:i}),this.lastDataObtainedTimestampMs=(0,Nt.now)(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Pt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,s=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=s);){let o=this.downloadingBufferItems[n].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[n]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,n++}return i}prepareFetchParams(e,t){if(Qe(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,s={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:s,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=(0,Nt.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:s?s.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Nt.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,globalFrom:r,loaded:s,signal:n}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||(0,Nt.isNullable)(o)||(0,Nt.isNullable)(r)||n.aborted))for(let u of e){let{segment:c}=u,d=c.byte.from-r,l=c.byte.to-r,p=l-d+1,m=d<s,f=l<=s;c.size=p,m&&(c.networkStatus==="downloading"&&c.bufferStatus==="none"&&f?(c.data=new DataView(t.buffer,t.byteOffset+d,p),this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u),c.loadedBytes=Math.min(p,s-d),await this.onDownloadItem(u)):(0,Nt.isNonNullable)(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(p,s-d),f&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+d,c.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(Qe(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};var Kt=require("@vkontakte/videoplayer-shared");var $r=class extends Mr{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(s,{...n,priority:i});if(this.lastDataObtainedTimestampMs=(0,Kt.now)(),(0,Kt.isNullable)(o))return;let u=e[0],c=new DataView(o);u.segment.size=c.byteLength,u.segment.loadedBytes=c.byteLength,u.segment.data=c,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Pt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:async(n,o)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=(0,Kt.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:Kt.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!Qe(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:s}){let n=e[0],{segment:o}=n,u=this.representations.get(i);!this.downloadingBufferItems.length||(0,Kt.isNullable)(u)||(0,Kt.isNullable)(o.feedingBytes)||o.networkStatus!=="downloading"||s.aborted||(o.loadedBytes=r,o.loadedBytes>o.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(o.data=new DataView(t.buffer,t.byteOffset,o.loadedBytes),await this.onDownloadItem(n)))}updateRepresentationBaseUrl(e,t){if(!Qe(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var nl=j(Aa(),1),yS=j(mt(),1);var Ce=require("@vkontakte/videoplayer-shared");var io=class extends $r{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new Ce.ValueSubject(0);this.currentLowLatencySegmentLength$=new Ce.ValueSubject(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=s.isActiveLowLatency}updateManifest(t){if(!t||[...this.segments.values()].every(r=>!r.length))return;let i=(0,nl.default)(t.streams[this.kind],r=>r.representations);for(let r of i){if((0,Ce.isNullable)(r)||!Qe(r.segmentReference))return;let s=r.segmentReference.segments.map(d=>({...d,networkStatus:"none",bufferStatus:"none",size:void 0})),n=100,o=this.segments.get(r.id)??[],u=(0,yS.default)(o,-1)?.time.to??0,c=s?.findIndex(d=>u>=d.time.from+n&&u<=d.time.to+n);if(c===-1){let d=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,d)}else{let d=s.slice(c+1);this.segments.set(r.id,[...o,...d])}this.representations.set(r.id,r)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;(0,Ce.assertNonNullable)(t);let i=this.segments.get(t);if(i?.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t?.streams[this.kind],r=(0,nl.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if((0,Ce.isNullable)(r))return;let s=this.segments.get(r.id);if(s?.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}getRepresentationInitialTime(){if((0,Ce.isNullable)(this.playingRepresentationId))return 0;let t=this.representations.get(this.playingRepresentationId)?.segmentReference;return(0,Ce.isNullable)(t)||!Qe(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return{...super.prepareFetchParams(t,i),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:t,...i}){await super.onSomeDataLoaded({downloadingItems:t,...i}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),(0,Ce.isNullable)(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:s,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);s&&n&&this.currentLiveSegmentServerLatency$.next(n-s),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){let i=t.segment.data,r=this.representations.get(t.representationId)?.segmentReference;if((0,Ce.isNullable)(t.segment.data)||(0,Ce.isNullable)(r)||!Qe(r))return;let s=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:n}=r;t.segment.time.to=s.getChunkEndTime(i,n)}}updateLowLatencyLive(t){let i=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!Qe(s))return;let n=this.segments.get(r.id)??[],o=n.find(c=>Math.floor(c.time.from)===Math.floor(t.segment.time.from));if(o?.isCurrentLowLatency&&(o.time.to=t.segment.time.to,i=o.time.to-o.time.from,o.isCurrentLowLatency=!1),!!!n.find(c=>Math.floor(c.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let c=Math.round(t.segment.time.to*s.timescale/1e3).toString(10),d=kt(s.segmentTemplateUrl,{segmentTime:c});n.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:d,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){try{let s=this.tuning.dash.useFetchPriorityHints?i:"auto",n=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,s);this.initDataPromises.set(t.id,n);let{initMetadata:o,initDataView:u,segments:c}=await n??{};if(this.initDataPromises.delete(t.id),(0,Ce.isNullable)(u)||(0,Ce.isNullable)(c))return;o&&this.parsedInitData.set(t.id,o);let d=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,d);let l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(t.id,l),this.failedDownloads=0}catch(s){r&&this.error$.next({id:"LoadInits",category:Ce.ErrorCategory.WTF,message:"loadInit threw",thrown:s})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[],n=0,o=i.length-1;do s.unshift(i[o]),n+=i[o].time.to-i[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[s[0]]:s}};var ns=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new io(e,t,i,r):Qe(i[0].segmentReference)?new $r(e,t,i,r):new to(e,t,i,r)}};var ze=require("@vkontakte/videoplayer-shared");var gi=require("@vkontakte/videoplayer-shared");var CM=18,TS=!1;try{TS=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=CM}catch(a){console.error(a)}var ol=class{constructor(e,t=!1){this.bufferFull$=new gi.Subject;this.error$=new gi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:gi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};TS&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,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(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:gi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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,gi.assertNever)(t)}}},IS=ol;var vi=(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 os=class{constructor(e){this.error$=new ze.Subject;this.subscription=new ze.Subscription;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new IS(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add((0,ze.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ze.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}async clear(e){let t=this.getBufferState();if((0,ze.isNullable)(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&=await this.sourceBufferTaskQueue.remove(r.from,r.to,e);return i}warmUpMediaSource(){!(0,ze.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if((0,ze.isNullable)(this.sourceBuffer)||!he(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return(0,ze.isNullable)(this.sourceBuffer)||!he(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,ze.isNullable)(e)?0:vi(this.sourceBuffer.buffered,e)}async abortBuffer(e){return(0,ze.isNullable)(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){if(this.subscription.unsubscribe(),this.sourceBufferTaskQueue?.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null}};var ro=(a,e)=>{a.video.forEach(t=>{let i=t.representations.filter(({fps:r,height:s})=>{let n=e.find(([o])=>o===`${s}p`)?.[1];return n&&Number.isInteger(n)&&r&&Number.isInteger(r)?r<=n:!0});t.representations=i})};var LM=["timeupdate","progress","play","seeked","stalled","waiting"],ES=["timeupdate","progress","loadeddata","playing","seeked"],ao=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new T.Subscription;this.subscriptionRemovable=new T.SubscriptionRemovable;this.representationSubscription=new T.Subscription;this.forceEnded$=new T.Subject;this.destroyController=new me;this.state$=new Z("none");this.currentVideoRepresentation$=new T.ValueSubject(void 0);this.currentVideoRepresentationInit$=new T.ValueSubject(void 0);this.currentAudioRepresentation$=new T.ValueSubject(void 0);this.currentVideoSegmentLength$=new T.ValueSubject(0);this.currentAudioSegmentLength$=new T.ValueSubject(0);this.error$=new T.Subject;this.manifestRequested=new T.Subject;this.manifestReceived=new T.Subject;this.firstBytesRequested=new T.Subject;this.firstBytesReceived=new T.Subject;this.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=new T.ValueSubject(void 0);this.lastConnectionMetrics$=new T.ValueSubject(void 0);this.lastDownloadMetrics$=new T.ValueSubject(void 0);this.currentLiveTextRepresentation$=new T.ValueSubject(null);this.isLive$=new T.ValueSubject(!1);this.isActiveLive$=new T.ValueSubject(!1);this.isLowLatency$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveSeekableDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(0);this.liveStreamStatus$=new T.ValueSubject(void 0);this.currentBuffer$=new T.ValueSubject({from:0,to:0});this.bufferLength$=new T.ValueSubject(0);this.nativeBufferLength$=new T.ValueSubject(0);this.liveLatency$=new T.ValueSubject(void 0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.currentStallDuration$=new T.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new T.ValueSubject(0);this.fetcherRecoverableError$=new T.Subject;this.fetcherError$=new T.Subject;this.initRepresentations=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),(0,T.assertNonNullable)(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?this.audioBufferManager?.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=(0,T.abortable)(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){(0,T.isNullable)(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Qn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}async initManifest(e,t,i){this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:T.ErrorCategory.PARSER,message:"No playable video representations"})}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,T.merge)(...LM.map(t=>(0,T.fromEvent)(this.element,t)),(0,T.fromEvent)((0,T.getWindow)(),"online")).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add((0,T.merge)(...e.map(t=>(0,T.fromEvent)(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,T.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}async seek(e,t=!1){(0,T.assertNonNullable)(this.element),(0,T.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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await this.audioBufferManager?.seek(i),this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.isNonNullable)(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(t=>t.warmUpMediaSource())}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}get isStreamEnded(){return this.source?.readyState==="ended"}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(e=>e.destroy()),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&(0,T.getWindow)().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),(0,T.isNonNullable)(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){return this.source?.readyState!=="open"}async reinitDecoderIfNeeded(e=!1){let t=this.videoNativeBufferManager?.getBufferState()??[];if((0,T.isNullable)(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(r=>i>=r.from&&i<=r.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){(0,T.assertNonNullable)(this.element),(0,T.assertNonNullable)(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=(0,T.now)(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,c=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,d=(0,T.isNonNullable)(this.videoBufferManager)&&u<s&&r-n>i,l=(0,T.isNonNullable)(this.audioBufferManager)&&c<s&&r-o>i;return(d||l)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if((0,T.isNullable)(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",(0,T.flattenObject)(i)),i}parseManifest(e){try{return Gn(e??"",this.manifestUrlString)}catch(t){let i=qn(e)??{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:t};this.error$.next(i)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,c)=>!!(this.element?.canPlayType?.(u)&&st()?.isTypeSupported?.(`${u}; codecs="${c}"`)||o==="text"),r,s;for(let o of["video","audio"]){let c=e.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));t[o]=c;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=c.map(({codecs:p})=>p);o==="audio"&&(s=Zn(l),d=s[0]),o==="video"&&(r=Jn(l),this.forceVideoCodec&&(0,wS.default)(r,this.forceVideoCodec)?d=this.forceVideoCodec:d=r[0]),d&&(t[o]=c.filter(({codecs:p})=>Ar(p)===d))}else{let l=new Set(c.map(({codecs:p})=>p));d=Xn(l),d&&(t[o]=c.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=t.video.some(g=>g.hdr),m=t.video.some(g=>!g.hdr);F.display.isHDR&&l&&p?t.video=t.video.filter(g=>g.hdr):m&&(t.video=t.video.filter(g=>!g.hdr));let{videoStreamRepresentaionsFilter:f}=this.tuning.dash;f.length&&ro(t,f)}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:s}),n}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element);let s=c=>{this.representationSubscription.add((0,T.fromEvent)(c,"error").pipe((0,T.filter)(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=Qs();let n=(0,T.getWindow)().document,o=n.createElement("source");if(s(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),cr())if(r){let c=n.createElement("source");s(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;let u=this.manifest.streams.video.reduce((c,d)=>[...c,...d.representations],[]);if(this.videoNativeBufferManager=new os(this.source),this.videoBufferManager=ns.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],(0,T.isNonNullable)(i)){this.audioNativeBufferManager=new os(this.source);let c=this.manifest.streams.audio.reduce((d,l)=>[...d,...l.representations],[]);this.audioBufferManager=ns.getBufferManager("audio",this.audioNativeBufferManager,c,e),this.bufferManagers.push(this.audioBufferManager),this.nativeBufferManagers.push(this.audioNativeBufferManager)}}async waitStreamToOpen(){if(this.isStreamNotOpen){let e=this.tuning.dash.sourceOpenTimeout>=0;await new Promise(t=>{e&&(this.timeoutSourceOpenId=(0,T.getWindow)().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&(0,T.getWindow)().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),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(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.representationSubscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),(0,T.assertNonNullable)(this.videoBufferManager),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.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add((0,T.merge)(...ES.map(e=>(0,T.fromEvent)(this.element,e))).pipe((0,T.map)(e=>this.videoBufferManager?.getPlaybackBufferState()),(0,T.filter)(T.isNonNullable),(0,T.map)(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add((0,T.merge)(...ES.map(e=>(0,T.fromEvent)(this.element,e))).pipe((0,T.map)(e=>Math.max(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),(0,T.filterChanged)()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe((0,T.filter)(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=(0,T.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if((0,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=(this.videoNativeBufferManager?.getBufferState()??[]).find(r=>e>=r.from&&e<=r.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await this.audioBufferManager?.maintain(e)}};var le=require("@vkontakte/videoplayer-shared");var so=class extends ao{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){(0,le.assertNonNullable)(this.manifest),(0,le.assertNonNullable)(this.source);let e=[this.manifest.duration??0,...(0,ul.default)((0,ul.default)([...this.manifest.streams.audio,...this.manifest.streams.video],t=>t.representations),t=>{let i=[];return t.duration&&i.push(t.duration),Qe(t.segmentReference)&&t.segmentReference.totalSegmentsDurationMs&&i.push(t.segmentReference.totalSegmentsDurationMs),i})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){(0,le.assertNonNullable)(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){(0,le.assertNonNullable)(this.element);let e=(0,le.merge)((0,le.fromEvent)(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe((0,le.filter)(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add((0,le.merge)(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=(0,le.merge)(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe((0,le.map)(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=(0,le.merge)(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe((0,le.map)(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=(0,le.combine)({allBuffersFull:e,someBufferEnded:t}).pipe((0,le.filterChanged)(),(0,le.map)(({allBuffersFull:s,someBufferEnded:n})=>s&&n),(0,le.filter)(s=>s)),r=()=>{try{this.source?.endOfStream()}catch(s){this.error$.next({id:"EndOfStream",category:le.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:s})}};this.representationSubscription.add((0,le.merge)(this.forceEnded$,i).pipe((0,le.filter)(s=>(0,le.isNonNullable)(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var Cr=class extends ka{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,xS.filterChanged)()).subscribe(s=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:l}])=>l.id===s);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[o,{stream:u}]=n,c=this.params.desiredState.videoStream.getTransition();c&&c.to&&c.to.id===u.id&&this.params.desiredState.videoStream.setState(c.to),e.currentVideoTrack$.next(o),e.currentVideoStream$.next(Ln(u));let d=this.player.calculateDurationFromSegments();d&&this.params.output.duration$.next(d/1e3)},r))}getPlayer(){return new so({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var q=require("@vkontakte/videoplayer-shared");var RS=j(Ge(),1),pl=j(Aa(),1);var Si=(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 y=require("@vkontakte/videoplayer-shared");var no=j(Ge(),1),Qi=j(mt(),1),oo=j(Aa(),1);var AS=j(vc(),1);var yi=require("@vkontakte/videoplayer-shared");var DM=18,PS=!1;try{PS=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=DM}catch(a){console.error(a)}var cl=class{constructor(e,t=!1){this.bufferFull$=new yi.Subject;this.error$=new yi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:yi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};PS&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,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(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:yi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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,yi.assertNever)(t)}}},kS=cl;var ll=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var x=require("@vkontakte/videoplayer-shared");var us=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new x.ValueSubject(0);this.currentLowLatencySegmentLength$=new x.ValueSubject(0);this.currentSegmentLength$=new x.ValueSubject(0);this.onLastSegment$=new x.ValueSubject(!1);this.fullyBuffered$=new x.ValueSubject(!1);this.playingRepresentation$=new x.ValueSubject(void 0);this.playingRepresentationInit$=new x.ValueSubject(void 0);this.error$=new x.Subject;this.gaps=[];this.subscription=new x.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new me;this.switchAbortController=new me;this.destroyAbortController=new me;this.useSmartRepresentationSwitch=!1;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,x.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,x.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new kS(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!he(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ll(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let c=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,c<d).catch(l=>{this.handleAsyncError(l,"pruneBuffer")})})),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,x.assertNonNullable)(i,"No init buffer for starting representation"),(0,x.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.switchTo=(0,x.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!he(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,x.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,x.isNullable)(s)||(0,x.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,x.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,x.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=(0,x.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!he(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,x.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,x.isNullable)(s)||(0,x.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,x.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,x.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,x.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,oo.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let c=t.find(p=>p.id===u);c&&this.representations.set(u,c);let d=this.representations.get(u);if(!d||!ut(d.segmentReference)){this.isSeekingLive=!1;return}let l=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,l)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,x.assertNonNullable)(r,`Representation not found by id ${i}`);let s=this.segments.get(i);(0,x.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,x.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!c?.live,this.baseUrls=c?.baseUrls??[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!he(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new me,(0,x.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,x.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,x.isNullable)(o)||(0,x.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,x.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer))){if(yield 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,x.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))}warmUpMediaSource(){!(0,x.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new me,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,x.isNullable)(e)||(0,x.isNullable)(this.downloadingRepresentationId)||(0,x.isNullable)(this.playingRepresentationId)||(0,x.isNullable)(this.sourceBuffer)||!he(this.mediaSource,this.sourceBuffer)||(0,x.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if((0,x.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,x.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,x.isNullable)(r)||(0,x.isNullable)(s))return;let n=r.find(p=>e>=p.time.from&&e<p.time.to);(0,x.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=this.getForwardBufferDuration(e),m=bi(i),f=bi(t),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,x.isNonNullable)(m)&&(0,x.isNonNullable)(f)&&(0,x.isHigher)(m.quality,f.quality),v=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(g||v?o+=Math.min(p,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let E=[...this.segments.entries()].map(([A,w])=>{let D=w.find(N=>e>=N.time.from&&e<N.time.to);return{representationId:A,status:D?.status}}).find(A=>A.status==="fed")?.representationId;E&&(this.playingRepresentationId=E,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&ll(this.sourceBuffer.buffered)>=this.bufferLimit){let p=this.getForwardBufferDuration(e),m=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<m).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,no.default)(d,n))p="high";else{let m=(0,Qi.default)(d,0);m&&m.time.from-n.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(d,t,p).catch(m=>{this.handleAsyncError(m,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!d.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Qi.default)(r,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-l.time.from>0))}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,persistent:!0}),i=s.time.to;(0,x.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}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?.streams[this.kind];if(!t)return;let i=(0,oo.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,oo.default)(e.streams[this.kind],i=>i.representations);for(let i of t){if(!i||!ut(i.segmentReference))return;let r=i.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],o=(0,Qi.default)(n,-1)?.time.to??0,u=r?.findIndex(c=>o>=c.time.from+s&&o<=c.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,c)}else{let c=r.slice(u+1);this.segments.set(i.id,[...n,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,x.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Qi.default)(e,-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!ut(r))return;let s=this.segments.get(i.id)??[],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,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),c=kt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&qi&&qi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&qi&&qi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}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=this.getForwardBufferDuration(i),s=e.findIndex(({status:p,time:{from:m,to:f}},g)=>{let v=m<=i&&f>=i,S=m>i||v||g===0&&i===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&m<=i+E||r<E&&f-m>=E||f<=i+E;return(p==="none"||p==="partially_ejected"&&S&&A&&this.sourceBuffer&&he(this.mediaSource,this.sourceBuffer)&&!(Si(this.sourceBuffer.buffered,m)&&Si(this.sourceBuffer.buffered,f)))&&S&&A});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=d||u<=l);p++){let m=n[p];if(o+=m.byte.to+1-m.byte.from,u+=m.time.to+1-m.time.from,m.status==="none"||m.status==="partially_ejected")c.push(m);else break}return c}async loadSegments(e,t,i="auto"){ut(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,x.abortable)(o,async function*(){let d=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,x.now)(),!d)return;let l=new DataView(d),p=ji(t.mime);if(!isFinite(r.segment.time.to)){let g=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(l,g)}u&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,o);let{serverDataReceivedTimestamp:m,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(l);m&&f&&this.currentLiveSegmentServerLatency$.next(f-m),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Pt(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())ut(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,x.abortable)(n,async function*(){let u=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),(0,x.fromEvent)(window,"online").pipe((0,x.once)()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,x.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Pt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ut(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Qi.default)(e,0).byte.from,to:(0,Qi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,x.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ut(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,x.now)();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,no.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!he(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=ji(n.mime).parseFeedableSegmentChunk(c,this.isLive);d?.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!he(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let d=c.byte.from-i,l=c.byte.to-i,p=l-d+1,m=d<r,f=l<=r;if(!m)continue;let g=ji(o.mime);if(c.status==="downloading"&&f){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-d),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?v:g.parseFeedableSegmentChunk(v);S?.byteLength&&(c.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!((0,x.isNullable)(this.sourceBuffer)||!he(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Si(this.sourceBuffer.buffered,e.segment.time.from,100)&&Si(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",sl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");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||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Fi(()=>(0,AS.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?(0,x.abortable)(this.destroyAbortController.signal,async function*(){let u=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ji(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async u=>{if(!u)return;let{init:c,dataView:d,segments:l}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let m=l;this.isLive&&ut(e.segmentReference)&&(m=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,m),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,u=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:x.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,x.isNullable)(e))return!1;let r=[],s=0,n=u=>{u.sort((d,l)=>d.from-l.from);let c=[u[0]];for(let d=1;d<u.length;d++){let{from:l,to:p}=u[d],m=c[c.length-1];m.to>=l?m.to=Math.max(m.to,p):c.push(u[d])}return c},o=u=>{if(s>=t)return r;r.push({...u.time}),r=n(r);let c=sl(u)?u.size??0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let d=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,l=0;for(let p of this.segments.values())for(let m of p)(0,no.default)(["none","partially_ejected"],m.status)&&Math.round(m.time.from)<=Math.round(c)&&Math.round(m.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:c,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 c of this.segments.values())for(let d of c)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,d)=>c||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,x.isNullable)(e)?0:vi(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let o=s.start(n)*1e3,u=s.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Fi(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:x.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,x.isNullable)(this.sourceBuffer)||!he(this.mediaSource,this.sourceBuffer)||(0,x.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),c=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(c.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")}}handleAsyncError(e,t){this.error$.next({id:t,category:x.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var O=require("@vkontakte/videoplayer-shared");var co=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new O.Subject;this.firstBytesManifest$=new O.Subject;this.firstBytesRequested$=new O.Subject;this.firstBytesReceived$=new O.Subject;this.lastConnectionType$=new O.ValueSubject(void 0);this.lastConnectionReused$=new O.ValueSubject(void 0);this.lastRequestFirstBytes$=new O.ValueSubject(void 0);this.lastConnectionMetrics$=new O.ValueSubject(void 0);this.lastDownloadMetrics$=new O.ValueSubject(void 0);this.recoverableError$=new O.Subject;this.error$=new O.Subject;this.abortAllController=new me;this.subscription=new O.SubscriptionRemovable;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=(0,O.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=mi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Hn(i)),this.trackRequestStart(i,performance.now());let r=(0,O.now)();this.manifestRequested$.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(uo);if(s){let n=(0,O.now)();t.log("success",(0,O.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(s.headers),this.firstBytesManifest$.next();let o=s.headers.get("content-length"),u=0;o&&(u=parseInt(o,10));let c=await s.text();if((!o||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let d=n-r,p=u/(d/1e3)*8/1024,m={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(m)}return c}else return t.error("error",(0,O.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=(0,O.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:d=!1}={}){let l=e,p=new Headers,m=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let P=new URL(l,(0,O.getWindow)().location.href);P.searchParams.append("bytes",`${i.from}-${i.to}`),l=P.toString();break}default:(0,O.assertNever)(t)}this.requestQuic&&(l=mi(l));let f=this.abortAllController.signal,g;if(n){let P=new me;if(g=(0,O.merge)((0,O.fromEvent)(this.abortAllController.signal,"abort"),(0,O.fromEvent)(n,"abort")).subscribe(()=>{try{P.abort()}catch(X){uo(X)}}),this.subscription.add(g),this.abortAllController.signal.aborted||n.aborted)try{P.abort()}catch(X){uo(X)}f=P.signal}let v=0,S=(0,O.now)();m.log("startRequest",(0,O.flattenObject)({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.trackRequestStart(l,performance.now()),this.firstBytesRequested$.next();let E=yield this.doFetch(l,{priority:s,headers:p,signal:f},{ignoreNetworkErrors:d}),A=(0,O.now)();if(!E)return m.error("error",{message:"No response in request"}),m.end(),this.unsubscribeAbortSubscription(g),null;if(this.throughputEstimator?.addRawRtt(A-S),!E.ok||!E.body){this.unsubscribeAbortSubscription(g);let P=`Fetch error ${E.status}: ${E.statusText}`;return m.error("error",{message:P}),m.end(),Promise.reject(new Error(`Fetch error ${E.status}: ${E.statusText}`))}if(this.onHeadersReceived(E.headers),!r&&!o){this.unsubscribeAbortSubscription(g);let P=(0,O.now)(),X={requestStartedAt:S,requestEndedAt:P,duration:P-S};return m.log("endRequest",(0,O.flattenObject)(X)),m.end(),E.arrayBuffer()}let w=E.body;if(o){let P;[w,P]=E.body.tee(),this.throughputEstimator?.trackStream(P,u)}let D=w.getReader(),N,U=parseInt(E.headers.get("content-length")??"",10);Number.isFinite(U)&&(N=U),!N&&i&&(N=i.to-i.from+1);let B=N?new Uint8Array(N):new Uint8Array(0),Q=!1,C=P=>{this.unsubscribeAbortSubscription(g),Q=!0,uo(P)},re=(0,O.abortable)(f,async function*({done:P,value:X}){if(v===0&&(this.lastRequestFirstBytes$.next((0,O.now)()-S),this.firstBytesReceived$.next()),f.aborted){this.unsubscribeAbortSubscription(g);return}if(!P&&X){if(c&&N)B.set(X,v),v+=X.byteLength;else{let V=new Uint8Array(B.length+X.length);V.set(B),V.set(X,B.length),B=V,v+=X.byteLength}r?.(new DataView(B.buffer),v),yield D?.read().then(re,C)}}.bind(this));yield D?.read().then(re,C),this.unsubscribeAbortSubscription(g);let Y=(0,O.now)(),k={failed:Q,requestStartedAt:S,requestEndedAt:Y,duration:Y-S};if(Q)return m.error("endRequest",(0,O.flattenObject)(k)),m.end(),null;if(v>0){let P=Y-S,V=v/(P/1e3)*8/1024,ae={bytes:v,speed:V,url:e};this.lastDownloadMetrics$.next(ae)}return m.log("endRequest",(0,O.flattenObject)(k)),m.end(),B.buffer}.bind(this));this.fetchByteRangeRepresentation=(0,O.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,r),o=Math.max(d,s))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!l)return null;let p=new DataView(l,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let m=t.parseInit(p),f=e.indexRange??t.getIndexRange(m);if(!f)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(l,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,measureThroughput:!1});if(!S)return null;g=new DataView(S)}let v=t.parseSegments(g,m,f);return{init:m,dataView:new DataView(l),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,O.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s,(0,O.getWindow)().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=Un(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new((0,O.getWindow)()).PerformanceObserver(e=>{e.getEntriesByType("resource").forEach(t=>{this.processPerformanceResourceTiming(t)})}),this.performanceObserver.observe({entryTypes:["resource"]})}processPerformanceResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let r=this.extractConnectionMetrics(e);r&&this.lastConnectionMetrics$.next(r)}estimateNetworkType(){if(!("connection"in(0,O.getWindow)().navigator))return"unknown";let e=(0,O.getWindow)().navigator.connection;return e.effectiveType?{"slow-2g":"2g","2g":"2g","3g":"3g","4g":"lte"}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?"2g":e.downlink<5?"3g":e.downlink<50?"lte":"wifi":e.rtt?e.rtt>500?"2g":e.rtt>250?"3g":e.rtt>50?"lte":"wifi":"unknown"}extractConnectionMetrics(e){let t=0,i=0,r=0,s=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(s=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=s),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,s),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),s=r.origin+r.pathname,n=new URL(i.url),o=n.origin+n.pathname;if(s===o&&e.startTime>=i.startTime-10&&e.startTime<=i.startTime+1e3)return t}}catch{this.recoverableError$.next({id:"VideoDataFetchError",message:"Video data fetch error with getting download metrics",category:O.ErrorCategory.WTF})}return null}trackRequestStart(e,t){let i=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(i,{url:e,startTime:t})}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,O.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.pendingConnectionMetrics.clear(),this.tracer.end()}async doFetch(e,t,i){let r=await bt(e,t);if(r.ok)return r;if(i?.ignoreNetworkErrors)return;let s=await r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:O.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:O.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:O.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:O.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:O.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},uo=a=>{if(!Pt(a))throw a};var cs=require("@vkontakte/videoplayer-shared"),Ti=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new cs.ValueSubject(e.initial),this.debounced$=new cs.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new He(`raw_${t}`),this.smoothedSeries$=new He(`smoothed_${t}`),this.reportedSeries$=new He(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,cs.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 lo=class extends Ti{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Wt(this.slow,e,this.params.emaAlphaSlow),this.fast=Wt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var po=class extends Ti{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Vc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Wt(this.emaSmoothed,e,this.params.emaAlpha);let i=yg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var ho=class extends Ti{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?Wt(this.smoothed,t,this.params.emaAlpha):t}};var zi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new lo({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new po({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new ho({initial:e,label:"liveEdgeDelay",...t})}};var dl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var mo=require("@vkontakte/videoplayer-shared");var ls=class a{constructor(e,t){this.currentRepresentation$=new mo.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?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,mo.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,o=r.segments[s-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(c=>c.time.from<=e&&c.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of 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?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&ut(t.segmentReference))}};var _M=["timeupdate","progress","play","seeked","stalled","waiting"],OM=["timeupdate","progress","loadeddata","playing","seeked"];var fo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new y.Subscription;this.subscriptionRemovable=new y.SubscriptionRemovable;this.representationSubscription=new y.Subscription;this.state$=new Z("none");this.currentVideoRepresentation$=new y.ValueSubject(void 0);this.currentVideoRepresentationInit$=new y.ValueSubject(void 0);this.currentAudioRepresentation$=new y.ValueSubject(void 0);this.currentVideoSegmentLength$=new y.ValueSubject(0);this.currentAudioSegmentLength$=new y.ValueSubject(0);this.error$=new y.Subject;this.manifestRequested$=new y.Subject;this.firstBytesManifest$=new y.Subject;this.manifestReceived$=new y.Subject;this.firstBytesRequested$=new y.Subject;this.firstBytesReceived$=new y.Subject;this.lastConnectionType$=new y.ValueSubject(void 0);this.lastConnectionReused$=new y.ValueSubject(void 0);this.lastRequestFirstBytes$=new y.ValueSubject(void 0);this.lastConnectionMetrics$=new y.ValueSubject(void 0);this.lastDownloadMetrics$=new y.ValueSubject(void 0);this.currentLiveTextRepresentation$=new y.ValueSubject(null);this.isLive$=new y.ValueSubject(!1);this.isActiveLive$=new y.ValueSubject(!1);this.isLowLatency$=new y.ValueSubject(!1);this.liveDuration$=new y.ValueSubject(0);this.liveSeekableDuration$=new y.ValueSubject(0);this.liveAvailabilityStartTime$=new y.ValueSubject(0);this.liveStreamStatus$=new y.ValueSubject(void 0);this.bufferLength$=new y.ValueSubject(0);this.liveLatency$=new y.ValueSubject(void 0);this.liveLoadBufferLength$=new y.ValueSubject(0);this.livePositionFromPlayer$=new y.ValueSubject(0);this.currentStallDuration$=new y.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new y.ValueSubject(0);this.fetcherRecoverableError$=new y.Subject;this.fetcherError$=new y.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new y.Subject;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new me;this.initManifest=(0,y.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Oe(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:y.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,y.abortable)(this.destroyController.signal,async function*(){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:y.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Gn(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let c=qn(e)??{id:"ManifestParsing",category:y.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(c)}if(!t)return null;let i=(u,c,d)=>!!(this.element?.canPlayType?.(c)&&st()?.isTypeSupported?.(`${c}; codecs="${d}"`)||u==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:u,latestSegmentPublishTime:c,streamIsUnpublished:d,streamIsAlive:l}=t.live,p=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((c-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";if(l||(m=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m),l&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let f=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(f).catch(g=>{this.error$.next({id:"updateManifest",category:y.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:g})})}}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:m})=>i(u,p,m));r[u]=d;let l;if(this.tuning.dash.codecsPrioritizeEnabled){let p=d.map(({codecs:m})=>m);u==="audio"&&(n=Zn(p),l=n[0]),u==="video"&&(s=Jn(p),this.forceVideoCodec&&(0,RS.default)(s,this.forceVideoCodec)?l=this.forceVideoCodec:l=s[0]),l&&(r[u]=d.filter(({codecs:m})=>Ar(m)===l))}else{let p=new Set(d.map(({codecs:m})=>m));l=Xn(p),l&&(r[u]=d.filter(({codecs:m})=>m.startsWith(l)))}if(u==="video"){let p=this.tuning.preferHDR,m=r.video.some(v=>v.hdr),f=r.video.some(v=>!v.hdr);F.display.isHDR&&p&&m?r.video=r.video.filter(v=>v.hdr):f&&(r.video=r.video.filter(v=>!v.hdr));let{videoStreamRepresentaionsFilter:g}=this.tuning.dash;g.length&&ro(r,g)}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",(0,y.flattenObject)(o)),o}.bind(this));this.initRepresentations=(0,y.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,y.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,y.assertNonNullable)(this.manifest),(0,y.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add((0,y.fromEvent)(l,"error").pipe((0,y.filter)(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=Qs();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),cr())if(i){let l=document.createElement("source");r(l),l.type="application/x-mpegurl",l.src=i.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new us("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,y.isNonNullable)(t)){let l=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new us("audio",this.source,l,n),this.bufferManagers.push(this.audioBufferManager)}if(ls.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ls(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,y.merge)(...OM.map(l=>(0,y.fromEvent)(this.element,l))).pipe((0,y.map)(l=>this.element?vi(this.element.buffered,this.element.currentTime*1e3):0),(0,y.filterChanged)(),(0,y.tap)(l=>{l>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,y.merge)((0,y.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,y.filterChanged)()).subscribe(p=>this.liveStreamEndTimestamp=(0,y.now)())),this.subscription.add((0,y.fromEvent)(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:p}=this.tuning.dash;this.livePauseWatchdogSubscription=(0,y.interval)(p).subscribe(m=>{let f=Os(this.manifestUrlString,2);this.manifestUrlString=Oe(this.manifestUrlString,f+p,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,y.fromEvent)(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,y.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.map)(({isActiveLive:p,isLowLatency:m})=>p&&m),(0,y.filterChanged)()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||dl(this.element,1)})),this.representationSubscription.add((0,y.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.filter)(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let m=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add((0,y.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,y.filter)(({isLive:p})=>p),(0,y.filterChanged)((p,m)=>m.bufferLength<p.bufferLength),(0,y.map)(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let g=Os(this.manifestUrlString,2);return(p/2+m+f+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,y.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=p-g;if(this.isManualDecreasePlaybackInLive())return;let A=1;Math.abs(E)>v&&(A=1+Math.sign(E)*S),dl(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let l=0;this.representationSubscription.add((0,y.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,y.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,g=Os(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,A=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,w=isFinite(p)?p:m,D=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),N=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(N);let U="none";if(D?U="active_low_latency":this.isLowLatency$.getValue()&&N?(this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),U="active_low_latency"):g!==0&&w<S?U="live_forward_buffering":w<S+A&&(U="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),U==="live_forward_buffering"||U==="live_with_target_offset"){let B=l-(S+E),Q=this.normalizeLiveOffset(Math.trunc(g+B/f)),C=Math.abs(Q-g),re=0;!p||C<=this.tuning.dashCmafLive.offsetCalculationError?re=g:Q>0&&C>this.tuning.dashCmafLive.offsetCalculationError&&(re=Q),this.manifestUrlString=Oe(this.manifestUrlString,re,2)}(U==="live_with_target_offset"||U==="live_forward_buffering")&&(l=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:y.ErrorCategory.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let u=(0,y.merge)(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe((0,y.map)(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),c=(0,y.merge)(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe((0,y.map)(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue()))),d=(0,y.combine)({allBuffersFull:u,someBufferEnded:c}).pipe((0,y.filterChanged)(),(0,y.map)(({allBuffersFull:l,someBufferEnded:p})=>l&&p),(0,y.filter)(l=>l));if(this.representationSubscription.add((0,y.merge)(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add((0,y.merge)(...this.bufferManagers.map(l=>l.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"){let l=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{l&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let l=[this.manifest.duration??0,...(0,pl.default)((0,pl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let m=[];return p.duration&&m.push(p.duration),ut(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...l)/1e3}this.audioBufferManager&&(0,y.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=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,y.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:y.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new co({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.subscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.liveBuffer=zi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){(0,y.assertNonNullable)(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?(0,y.now)()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Oe(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){(0,y.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,y.merge)(..._M.map(e=>(0,y.fromEvent)(this.element,e)),(0,y.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:y.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,y.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,y.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&Si(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let d=this.currentStallDuration$.getValue();d+=n,this.currentStallDuration$.next(d);let l={timeInWaiting:d},p=(0,y.now)(),m=100,f=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(f);let g=this.audioBufferManager?.lastDataObtainedTimestamp??0,v=this.videoBufferManager?.getForwardBufferDuration()??0,S=this.audioBufferManager?.getForwardBufferDuration()??0,E=v<m&&p-f>r,A=this.audioBufferManager&&S<m&&p-g>r;if((!t||c)&&((E||A)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(o&&d%s===0){let w=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(w),this.updateManifest()):this.seekLive(w).catch(D=>{this.error$.next({id:"stallIntervalCallback",category:y.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:D})}),l.liveLastOffset=w}else{let w=this.element.currentTime*1e3;this.videoBufferManager?.maintain(w),this.audioBufferManager?.maintain(w),l.position=w}this.tracer.log("stallIntervalCallback",(0,y.flattenObject)(l))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,y.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:y.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(0,y.assertNonNullable)(this.element),(0,y.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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Si(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,y.isNullable)(this.element)||(0,y.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,y.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,y.isNonNullable)(this.element)&&(0,y.isNonNullable)(this.source)&&(0,y.isNonNullable)(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,y.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let c of u.gaps)(r&&c.persistent||u.playingRepresentation$.getValue()===c.representation)&&c.from-o<=s&&c.to+o>s&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?n.push(1/0):n.push(c.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,y.flattenObject)(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var tt=require("@vkontakte/videoplayer-shared"),bo=class{constructor(){this.subscription=new tt.Subscription;this.pipSize$=new tt.ValueSubject(void 0);this.videoSize$=new tt.ValueSubject(void 0);this.elementSize$=new tt.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=tt.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,tt.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,tt.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,tt.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Wi=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new Z("stopped");this.observableVideo=null;this.droppedFramesManager=new Ir;this.stallsManager=new _n;this.elementSizeManager=new bo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new di;this.audioTrackSwitchHistory=new di;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(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(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"),L(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&L(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return(0,q.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Er(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new ht(e.source.url),this.params=e,this.video=Ye(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(Fe(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 fo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,q.isNullable)(this.observableVideo)&&(this.observableVideo=Je(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:q.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,q.filter)(l=>!!l.length),(0,q.once)()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,q.map)(l=>l.to.state!=="none"),(0,q.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.currentBuffer$,e.currentNativeBuffer$),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.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),s(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,q.filter)(q.isNonNullable),(0,q.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,q.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Vt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),hi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Xe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(ft(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams(),m=this.player.getCodecs();if((0,q.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let g=[];for(let v of p.audio){g.push(rl(v));let S=[];for(let E of v.representations){let A=ss(E);S.push(A),this.audioTracksMap.set(A,{stream:v,representation:E})}this.audioStreamsMap.set(v,S)}this.params.output.availableAudioStreams$.next(g)}let f=[];for(let g of p.video){f.push(al(g));let v=[];for(let S of g.representations){let E=bi({...S,streamId:g.id});E&&(v.push(E),this.videoTracksMap.set(E,{stream:g,representation:S}))}this.videoStreamsMap.set(g,v)}this.params.output.availableVideoStreams$.next(f);for(let g of p.text)for(let v of g.representations){let S=gS(g,v);this.textTracksMap.set(S,{stream:g,representation:v})}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),m?.video&&this.params.output.availableVideoCodecs$.next(m.video),m?.audio&&this.params.output.availableAudioCodecs$.next(m.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=(0,q.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,q.fromEvent)(this.video,"progress")).pipe((0,q.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe((0,q.throttle)(u))),this.subscription.add(o.subscribe(async()=>{let l=this.player.state$.getState(),p=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let m=this.selectVideoAudioRepresentations();if(!m)return;let[f,g]=m,v=[...this.videoTracksMap.keys()].find(E=>this.videoTracksMap.get(E)?.representation.id===f.id);(0,q.isNonNullable)(v)&&(this.stallsManager.lastVideoTrackSelected=v);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),l==="manifest_ready")await this.player.initRepresentations(f.id,g?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),g){let E=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",g.id,E)}},r)),this.subscription.add((0,q.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,q.merge)((0,q.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,q.map)(l=>l.to)))}).pipe((0,q.map)(({videoState:l,autoVideoTrackState:p})=>l.to!=="stopped"&&p),(0,q.filterChanged)()).subscribe(l=>this.player.setSmartRepresentationSwitch(l))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,q.filterChanged)()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:S}])=>S.id===l);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[m,{stream:f}]=p,g=this.params.desiredState.videoStream.getTransition();g&&g.to&&g.to.id===f.id&&this.params.desiredState.videoStream.setState(g.to),e.currentVideoTrack$.next(m),e.currentVideoStream$.next(al(f));let v=this.player.calculateDurationFromSegments();v&&this.params.output.duration$.next(v/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,q.filterChanged)()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:v}])=>v.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[m,{stream:f}]=p,g=this.params.desiredState.audioStream.getTransition();g&&g.to&&g.to.id===f.id&&this.params.desiredState.audioStream.setState(g.to),e.currentAudioStream$.next(rl(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),this.params.tuning.spherical?.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)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe((0,q.map)(({to:l})=>l==="ready"),(0,q.filterChanged)());this.subscription.add((0,q.merge)(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,q.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),m=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(m)})),this.subscription.add((0,q.merge)(c,this.player.state$.stateChangeEnded$,(0,q.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=(0,q.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ya:Sa,t=this.params.tuning.useNewAutoSelectVideoTrack?Mn:Rn,i=this.params.tuning.useNewAutoSelectVideoTrack?_t:An,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:B})=>B===o),c=s.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:B})=>B===d.id),p=l&&this.videoStreamsMap.get(l);if(!p)return;let m=vi(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,v=Math.min(m/Math.min(f,g||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),E=[...this.audioStreamsMap.keys()].find(({id:B})=>B===S?.id)??this.audioStreamsMap.keys().next().value,A=0;if(E){if(u&&!n){let B=e(u,p,this.audioStreamsMap.get(E)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);A=Math.max(A,B?.bitrate??-1/0)}if(c){let B=e(c,p,this.audioStreamsMap.get(E)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);A=Math.max(A,B?.bitrate??-1/0)}}let w=u;(n||!w)&&(w=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:A,forwardBufferHealth:v,current:c,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}));let D=E&&t(w,p,this.audioStreamsMap.get(E)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),N=this.videoTracksMap.get(w)?.representation,U=D&&this.audioTracksMap.get(D)?.representation;if(N&&U)return[N,U];if(N&&!U&&this.audioTracksMap.size===0)return[N,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ze(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(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}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ke(this.video),this.tracer.end()}};var ds=class extends Wi{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 pe=require("@vkontakte/videoplayer-shared");var ps=class extends Wi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new pe.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,pe.filterChanged)()).subscribe(u=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!u&&!c&&l?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe((0,pe.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,pe.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,pe.map)(({liveBufferTime:u,liveAvailabilityStartTime:c})=>u&&c?u*1e3+c+t:void 0)).subscribe(i.liveTime$)).add((0,pe.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,pe.merge)(r.playbackRateState$,new pe.ValueSubject(1))}).pipe((0,pe.filter)(({liveStreamStatus:u,liveDuration:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let d=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-p||this.video.paused||(0,pe.isNullable)(d)||(t=u-d)})).add((0,pe.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,pe.merge)(r.playbackRateState$,new pe.ValueSubject(1))}).pipe((0,pe.filterChanged)((u,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||(0,pe.isNullable)(u)||(0,pe.isNullable)(c))return;let m=-1*(c-u-t);i.position$.next(Math.min(m,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=vS(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,pe.filter)(u=>(0,pe.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var MS="X-Playback-Duration",hl=async a=>{let e=await bt(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(MS)?parseInt(e.headers.get(MS),10):void 0};var ie=require("@vkontakte/videoplayer-shared");var fl=j(Cu(),1);var go=require("@vkontakte/videoplayer-shared");var FM=a=>{let e=null;if(a.QUALITY&&(e=li(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,go.videoSizeToQuality)({width:t,height:i})}return e??null},qM=(a,e)=>{let t=a.split(`
179
179
  `),i=[],r=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let c=(0,fl.default)(o[1].split(",").map(v=>v.split("="))),d=c.QUALITY??`stream-${c.BANDWIDTH}`,l=FM(c),p;c.BANDWIDTH&&(p=parseInt(c.BANDWIDTH,10)/1e3||void 0),!p&&c["AVERAGE-BANDWIDTH"]&&(p=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,f;if(c.RESOLUTION){let[v,S]=c.RESOLUTION.split("x").map(E=>parseInt(E,10));v&&S&&(f={width:v,height:S})}let g=new URL(t[++s],e).toString();l&&i.push({id:d,quality:l,url:g,bandwidth:p,size:f,fps:m})}if(u){let c=(0,fl.default)(u[1].split(",").map(m=>{let f=m.indexOf("=");return[m.substring(0,f),m.substring(f+1)]}).map(([m,f])=>[m,f.replace(/^"|"$/g,"")])),d=c.URI?.replace(/playlist$/,"subtitles.vtt"),l=c.LANGUAGE,p=c.NAME;d&&l&&r.push({type:"internal",id:l,label:p,language:l,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},UM=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),ml=0,$S=async(a,e=a,t,i)=>{let s=await(await bt(a,i)).text();ml+=1;try{let{qualityManifests:n,textTracks:o}=qM(s,e);return{qualityManifests:n,textTracks:o}}catch{if(ml<=t.manifestRetryMaxCount)return await UM((0,go.getExponentialDelay)(ml-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),$S(a,e,t)}return{qualityManifests:[],textTracks:[]}},vo=$S;var ct=require("@vkontakte/videoplayer-shared");var So=class{constructor(e,t,i,r,s){this.subscription=new ct.Subscription;this.abortControllers={destroy:new me,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new ct.ValueSubject(null);this.getCurrentTime$=new ct.ValueSubject(null);this.error$=new ct.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe((0,ct.throttle)(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),n=await(await bt(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
180
180
  `),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],c=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:c}),s=s+d,!i.segmentStartTime){let l=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-l}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 c=new Date(u);c.setMilliseconds(0),s=c.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,ct.isNonNullable)(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new me;let{textTracks:e}=await this.fetchManifestData(),t=await 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}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:ct.ErrorCategory.WTF,thrown:t,message:e})}};var hs=class{constructor(e){this.subscription=new ie.Subscription;this.videoState=new Z("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new ie.ValueSubject([]);this.liveOffset=new _i;this.manifestStartTime$=new ie.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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position&&c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?L(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),L(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?.to==="playing"&&L(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?.to==="paused"&&(L(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,ie.assertNever)(t)}};this.params=e,this.video=Ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ie.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,r)=>vo(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new So(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ht(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ie.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:ie.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(Fe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new ie.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:ie.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Je(this.video);this.subscription.add(()=>r.destroy());let 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.currentBuffer$,e.currentNativeBuffer$),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(Xe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),s(ft(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"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.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,ie.filterChanged)(),(0,ie.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,ie.isNonNullable)(c.to)){let l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let p=this.manifests$.getValue().find(m=>m.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Fe(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(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,ie.combine)({startTime:this.manifestStartTime$.pipe((0,ie.filter)(ie.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,ie.map)(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:p})=>({id:u,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,ie.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ie.observableFrom)(["init"])).pipe((0,ie.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Ke(this.video)}prepare(){let e=this.selectManifest();if((0,ie.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}=t?.to??i??{};for(let[c,d]of[[o,"mq"],[u,"lq"]]){let l=String(parseFloat(c||""));d&&c&&r.searchParams.set(d,l)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Oe(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),hl(n).then(o=>{if(!(0,ie.isNullable)(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();((0,ie.isNullable)(u)||!isFinite(u))&&bt(n).then(c=>c.text()).then(c=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(c)?.[1];if(d){let l=new URL(d,n).toString();hl(l).then(p=>{(0,ie.isNullable)(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){Ze(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ie.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=Oe(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 ue=require("@vkontakte/videoplayer-shared");var ms=class{constructor(e){this.subscription=new ue.Subscription;this.videoState=new Z("stopped");this.manifests$=new ue.ValueSubject([]);this.unmuteAfterBrowserResetsHappened=new ue.ValueSubject(!1);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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":i==="ready"?L(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),L(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?.to==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&L(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,ue.assertNever)(t)}};this.textTracksManager=new ht(e.source.url),this.params=e,this.video=Ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ue.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(Fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),vo(Oe(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.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:ue.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:ue.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Je(this.video);this.subscription.add(()=>r.destroy());let 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.currentBuffer$,e.currentNativeBuffer$),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,ue.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Vt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),hi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Xe(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,ue.isNonNullable)(c.to)){let m=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let f=this.manifests$.getValue().find(g=>g.id===m);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Fe(f.url)))}let l=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(l!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(l),m.playbackRate=l)}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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe((0,ue.map)(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:p})=>({id:u,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!F.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,ue.merge)((0,ue.fromEvent)(o,"addtrack"),(0,ue.fromEvent)(o,"removetrack"),(0,ue.fromEvent)(o,"change"),(0,ue.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,ue.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ue.observableFrom)(["init"])).pipe((0,ue.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ke(this.video)}prepare(){let e=this.selectManifest();if((0,ue.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:s,min:n}=t?.to??i??{};for(let[o,u]of[[s,"mq"],[n,"lq"]]){let c=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ze(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var CS=j(oi(),1),bl=j(Mi(),1),LS=j(mt(),1);var ge=require("@vkontakte/videoplayer-shared");var fs=class{constructor(e){this.subscription=new ge.Subscription;this.videoState=new Z("stopped");this.trackUrls={};this.textTracksManager=new ht;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.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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(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);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?L(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),L(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?.to==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return(0,ge.assertNever)(e)}};this.params=e,this.video=Ye(e.container,e.tuning),this.params.output.element$.next(this.video),(0,CS.default)(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((0,bl.default)(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:ge.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Je(this.video);this.subscription.add(()=>r.destroy());let 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.currentNativeBuffer$),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,ge.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Vt(this.video,t.isLooped,i)),hi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Xe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),s(ft(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,ge.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(u!==c){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=(0,ge.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ge.observableFrom)(["init"])).pipe((0,ge.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),Ke(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,ge.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,ge.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=mi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Fe(t))}playIfAllowed(){Ze(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ge.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let d=_t(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(d)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,bl.default)(this.trackUrls).map(c=>c.track);if(!r||!s||Sr(e,n[0].quality,(0,LS.default)(n,-1)?.quality)){i();return}let o=e.max?(0,ge.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,ge.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var ve=require("@vkontakte/videoplayer-shared");var BS=require("@vkontakte/videoplayer-shared"),DS=["stun:videostun.mycdn.me:80"],HM=1e3,jM=3,gl=()=>null,yo=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=gl;this.externalStopCallback=gl;this.externalErrorCallback=gl;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:DS}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:BS.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{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),HM)}normalizeOptions(e={}){let t={stunServerList:DS,maxRetryNumber:jM,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var bs=class{constructor(e){this.videoState=new Z("stopped");this.maxSeekBackTime$=new ve.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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(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"),L(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?.to==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return(0,ve.assertNever)(e)}};this.subscription=new ve.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ye(e.container,e.tuning),this.liveStreamClient=new yo(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),Ke(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ve.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,ve.merge)(this.videoState.stateChangeStarted$.pipe((0,ve.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ve.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Je(this.video);this.subscription.add(()=>r.destroy());let 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(r.currentBuffer$,e.currentNativeBuffer$),s(ft(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(()=>{this.videoState.getTransition()?.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(Xe(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,ve.assertNever)(n.to)}},i)).add((0,ve.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ve.observableFrom)(["init"])).pipe((0,ve.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(Fe(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:ve.VideoQuality.INVARIANT}),this.video.srcObject=e,L(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.currentNativeBuffer$.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:ve.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ze(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ve.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Lr=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};var I=require("@vkontakte/videoplayer-shared");var Xt=require("@vkontakte/videoplayer-shared");var VS=a=>new Xt.Observable(e=>{let t=new Xt.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Xt.map)(({from:c,to:d})=>`${c}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Xt.map)(({type:c})=>c!==void 0)),n=new Xt.Subject,o=0,u="unknown";return t.add(i.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval),W({m:"hangup.set",l:c,id:o})})),t.add(r.subscribe(()=>{W({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(c=>{o&&(W({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval),W({m:"hangup.rs.1",id:o})))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var gt=require("@vkontakte/videoplayer-shared");function _S(){return new(window.AudioContext||window.webkitAudioContext)}var Dr=class a{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new me;this.subscriptions=new gt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,gt.filter)(s=>!!s.type),(0,gt.once)()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){F.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,gt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,gt.filter)(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,gt.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}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=_S();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await 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){this.volumeMultiplierError$.next({id:a.errorId,category:gt.ErrorCategory.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var QM={chunkDuration:5e3,maxParallelRequests:5},gs=class{constructor(e){this.current$=new I.ValueSubject({type:void 0});this.providerError$=new I.Subject;this.noAvailableProvidersError$=new I.Subject;this.volumeMultiplierError$=new I.Subject;this.providerOutput={position$:new I.ValueSubject(0),duration$:new I.ValueSubject(1/0),volume$:new I.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new I.ValueSubject([]),currentVideoStream$:new I.ValueSubject(void 0),availableVideoTracks$:new I.ValueSubject([]),currentVideoTrack$:new I.ValueSubject(void 0),availableVideoCodecs$:new I.ValueSubject([]),availableAudioStreams$:new I.ValueSubject([]),currentAudioStream$:new I.ValueSubject(void 0),availableAudioTracks$:new I.ValueSubject([]),availableAudioCodecs$:new I.ValueSubject([]),currentVideoSegmentLength$:new I.ValueSubject(0),currentAudioSegmentLength$:new I.ValueSubject(0),isAudioAvailable$:new I.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new I.ValueSubject(!1),autoVideoTrackLimits$:new I.ValueSubject(void 0),currentBuffer$:new I.ValueSubject(void 0),currentNativeBuffer$:new I.ValueSubject(void 0),isBuffering$:new I.ValueSubject(!0),error$:new I.Subject,fetcherError$:new I.Subject,fetcherRecoverableError$:new I.Subject,warning$:new I.Subject,willSeekEvent$:new I.Subject,soundProhibitedEvent$:new I.Subject,seekedEvent$:new I.Subject,loopedEvent$:new I.Subject,endedEvent$:new I.Subject,manifestRequested$:new I.Subject,firstBytesManifest$:new I.Subject,manifestReceived$:new I.Subject,firstBytesRequested$:new I.Subject,firstBytesReceived$:new I.Subject,firstBytesEvent$:new I.Subject,loadedMetadataEvent$:new I.Subject,firstFrameEvent$:new I.Subject,canplay$:new I.Subject,isLive$:new I.ValueSubject(void 0),isLiveEnded$:new I.ValueSubject(null),canPlayLiveTailBuffer$:new I.ValueSubject(!1),isLowLatency$:new I.ValueSubject(!1),canChangePlaybackSpeed$:new I.ValueSubject(!0),liveTime$:new I.ValueSubject(void 0),liveBufferTime$:new I.ValueSubject(void 0),liveLatency$:new I.ValueSubject(void 0),severeStallOccurred$:new I.Subject,availableTextTracks$:new I.ValueSubject([]),currentTextTrack$:new I.ValueSubject(void 0),hostname$:new I.ValueSubject(void 0),httpConnectionType$:new I.ValueSubject(void 0),httpConnectionReused$:new I.ValueSubject(void 0),httpConnectionMetrics$:new I.ValueSubject(void 0),httpDownloadMetrics$:new I.ValueSubject(void 0),inPiP$:new I.ValueSubject(!1),inFullscreen$:new I.ValueSubject(!1),element$:new I.ValueSubject(void 0),elementVisible$:new I.ValueSubject(!0),availableSources$:new I.ValueSubject(void 0),is3DVideo$:new I.ValueSubject(!1),playbackState$:new I.ValueSubject(""),getCurrentTime$:new I.ValueSubject(null)};this.subscription=new I.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=lu([...aS(this.params.tuning),...rS(this.params.tuning)]).filter(c=>(0,I.isNonNullable)(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(c=>!(0,vl.default)(r,c)),...t.filter(c=>(0,vl.default)(r,c))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,I.flattenObject)(s)),this.screenFormatsIterator=new Lr(s);let n=[...tl(!0),...tl(!1)];this.chromecastFormatsIterator=new Lr(n.filter(c=>(0,I.isNonNullable)(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Dr.isSupported()&&(this.volumeMultiplierManager=new Dr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){W.reset(),this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Lr(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,I.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:I.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()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();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})}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,I.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),c=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,I.assertNonNullable)(u),this.params.tuning.useDashProviderVirtual&&!F.device.isMobile?new Cr({...o,source:u,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&F.device.isMobile?new Cr({...o,source:u,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new ds({...o,source:u,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(u),new ps({...o,source:u})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let u=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(u),new ms({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(u),new hs({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(u),new fs({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(u),new hg({...o,source:u,config:{...QM,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(u),new bs({container:i,source:u,desiredState:r,output:n,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,I.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o={meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof Ht){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return(0,I.assertNonNullable)(c),new ta({...o,chromecastConnector:c})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,I.assertNonNullable)(u),new fa({...o,connection:u})}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,I.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,I.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,I.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,OS.default)((0,Sl.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new I.Subscription,t=!1,i=0;e.add((0,I.merge)(this.providerOutput.error$.pipe((0,I.filter)(s=>!this.params.tuning.ignoreAudioRendererError||!s.message||!/AUDIO_RENDERER_ERROR/ig.test(s.message))),VS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,I.map)(s=>({id:`ProviderHangup:${s}`,category:I.ErrorCategory.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let s=this.params.desiredState.playbackState.transitionEnded$.pipe((0,I.filter)(({to:n})=>n==="playing"),(0,I.once)()).subscribe(()=>t=!0);e.add(s)}));let r=()=>{let s=W.drain(),{logDashLiveDebug:n,sendDashLiveDebug:o}=this.params.tuning;if(n&&(0,I.getWindow)().console.log(`===== DASH_LIVE DEBUG START ====
181
181
  `,s.map(({time:u,data:c,stack:d})=>`${u}: ${JSON.stringify(c)}${d?`