@vkontakte/videoplayer-core 2.0.131-dev.ba1a65a9.0 → 2.0.131-dev.c7ccfbe4.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.
Files changed (71) hide show
  1. package/es2015.cjs.js +91 -30
  2. package/es2015.esm.js +93 -32
  3. package/es2018.cjs.js +91 -30
  4. package/es2018.esm.js +93 -32
  5. package/es2024.cjs.js +98 -37
  6. package/es2024.esm.js +95 -34
  7. package/esnext.cjs.js +98 -37
  8. package/esnext.esm.js +95 -34
  9. package/evergreen.esm.js +91 -30
  10. package/package.json +2 -2
  11. package/types/player/Player.d.ts +0 -5
  12. package/types/providers/DashProvider/baseDashProvider.d.ts +1 -0
  13. package/types/providers/DashProvider/lib/buffer.d.ts +3 -0
  14. package/types/providers/DashProvider/lib/fetcher.d.ts +2 -1
  15. package/types/providers/DashProvider/lib/player.d.ts +1 -0
  16. package/types/providers/DashProvider/lib/sourceBufferBufferedDiff.d.ts +19 -0
  17. package/types/providers/DashProvider/lib/utils.d.ts +11 -0
  18. package/types/providers/DashProviderNew/baseDashProvider.d.ts +57 -0
  19. package/types/providers/DashProviderNew/consts.d.ts +3 -0
  20. package/types/providers/DashProviderNew/index.d.ts +2 -0
  21. package/types/providers/DashProviderNew/lib/ElementSizeManager.d.ts +19 -0
  22. package/types/providers/DashProviderNew/lib/LiveTextManager.d.ts +23 -0
  23. package/types/providers/DashProviderNew/lib/buffer.d.ts +117 -0
  24. package/types/providers/DashProviderNew/lib/fetcher.d.ts +59 -0
  25. package/types/providers/DashProviderNew/lib/parsers/ietf/index.d.ts +13 -0
  26. package/types/providers/DashProviderNew/lib/parsers/index.d.ts +3 -0
  27. package/types/providers/DashProviderNew/lib/parsers/mpd.d.ts +3 -0
  28. package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxModel.d.ts +20 -0
  29. package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxParser.d.ts +21 -0
  30. package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxTypeEnum.d.ts +30 -0
  31. package/types/providers/DashProviderNew/lib/parsers/mpeg/box.d.ts +74 -0
  32. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/avc1.d.ts +8 -0
  33. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/equi.d.ts +21 -0
  34. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/ftyp.d.ts +17 -0
  35. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/index.d.ts +26 -0
  36. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mdat.d.ts +15 -0
  37. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mdia.d.ts +8 -0
  38. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mfhd.d.ts +11 -0
  39. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/minf.d.ts +8 -0
  40. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/moof.d.ts +8 -0
  41. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/moov.d.ts +8 -0
  42. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mvhd.d.ts +35 -0
  43. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/prhd.d.ts +16 -0
  44. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/proj.d.ts +8 -0
  45. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/sidx.d.ts +48 -0
  46. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/st3d.d.ts +23 -0
  47. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/stbl.d.ts +8 -0
  48. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/stsd.d.ts +11 -0
  49. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/sv3d.d.ts +8 -0
  50. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tfdt.d.ts +17 -0
  51. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tfhd.d.ts +22 -0
  52. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tkhd.d.ts +42 -0
  53. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/traf.d.ts +8 -0
  54. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/trak.d.ts +8 -0
  55. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/trun.d.ts +31 -0
  56. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/unknown.d.ts +6 -0
  57. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/uuid.d.ts +11 -0
  58. package/types/providers/DashProviderNew/lib/parsers/mpeg/fullBox.d.ts +15 -0
  59. package/types/providers/DashProviderNew/lib/parsers/mpeg/isobmff.d.ts +12 -0
  60. package/types/providers/DashProviderNew/lib/parsers/webm/ebml.d.ts +76 -0
  61. package/types/providers/DashProviderNew/lib/parsers/webm/webm.d.ts +3 -0
  62. package/types/providers/DashProviderNew/lib/player.d.ts +92 -0
  63. package/types/providers/DashProviderNew/lib/sourceBufferTaskQueue.d.ts +19 -0
  64. package/types/providers/DashProviderNew/lib/types.d.ts +186 -0
  65. package/types/providers/DashProviderNew/lib/utils.d.ts +21 -0
  66. package/types/providers/DashProviderNew/newDashCmafLiveProvider.d.ts +8 -0
  67. package/types/providers/DashProviderNew/newDashProvider.d.ts +6 -0
  68. package/types/providers/utils/StallsManager.d.ts +18 -4
  69. package/types/utils/autoSelectTrack.d.ts +6 -3
  70. package/types/utils/qualityLimits.d.ts +3 -18
  71. package/types/utils/tuningConfig.d.ts +28 -7
package/es2018.cjs.js CHANGED
@@ -1,73 +1,127 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.131-dev.ba1a65a9.0
3
- * Mon, 14 Apr 2025 14:27:25 GMT
2
+ * @vkontakte/videoplayer-core v2.0.131-dev.c7ccfbe4.0
3
+ * Mon, 05 May 2025 10:43:12 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-131/doc/
5
5
  */
6
- "use strict";var kS=Object.create;var fr=Object.defineProperty;var nc=Object.getOwnPropertyDescriptor;var RS=Object.getOwnPropertyNames;var $S=Object.getPrototypeOf,LS=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),MS=(a,e)=>{for(var t in e)fr(a,t,{get:e[t],enumerable:!0})},oc=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of RS(e))!LS.call(a,r)&&r!==t&&fr(a,r,{get:()=>e[r],enumerable:!(i=nc(e,r))||i.enumerable});return a};var j=(a,e,t)=>(t=a!=null?kS($S(a)):{},oc(e||!a||!a.__esModule?fr(t,"default",{value:a,enumerable:!0}):t,a)),DS=a=>oc(fr({},"__esModule",{value:!0}),a),wn=(a,e,t,i)=>{for(var r=i>1?void 0:i?nc(e,t):e,s=a.length-1,n;s>=0;s--)(n=a[s])&&(r=(i?n(e,t,r):n(r))||r);return i&&r&&fr(e,t,r),r};var me=b((kn,uc)=>{"use strict";var vr=function(a){return a&&a.Math===Math&&a};uc.exports=vr(typeof globalThis=="object"&&globalThis)||vr(typeof window=="object"&&window)||vr(typeof self=="object"&&self)||vr(typeof global=="object"&&global)||vr(typeof kn=="object"&&kn)||function(){return this}()||Function("return this")()});var xe=b((p$,lc)=>{"use strict";lc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Sr=b((h$,cc)=>{"use strict";var CS=xe();cc.exports=!CS(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Rn=b((m$,mc)=>{"use strict";var VS=Sr(),hc=Function.prototype,dc=hc.apply,pc=hc.call;mc.exports=typeof Reflect=="object"&&Reflect.apply||(VS?pc.bind(dc):function(){return pc.apply(dc,arguments)})});var ye=b((f$,gc)=>{"use strict";var fc=Sr(),bc=Function.prototype,$n=bc.call,OS=fc&&bc.bind.bind($n,$n);gc.exports=fc?OS:function(a){return function(){return $n.apply(a,arguments)}}});var oi=b((b$,Sc)=>{"use strict";var vc=ye(),BS=vc({}.toString),_S=vc("".slice);Sc.exports=function(a){return _S(BS(a),8,-1)}});var Ln=b((g$,yc)=>{"use strict";var NS=oi(),FS=ye();yc.exports=function(a){if(NS(a)==="Function")return FS(a)}});var pe=b((v$,Tc)=>{"use strict";var Mn=typeof document=="object"&&document.all;Tc.exports=typeof Mn=="undefined"&&Mn!==void 0?function(a){return typeof a=="function"||a===Mn}:function(a){return typeof a=="function"}});var qe=b((S$,Ic)=>{"use strict";var qS=xe();Ic.exports=!qS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ue=b((y$,Ec)=>{"use strict";var US=Sr(),ss=Function.prototype.call;Ec.exports=US?ss.bind(ss):function(){return ss.apply(ss,arguments)}});var Dn=b(wc=>{"use strict";var xc={}.propertyIsEnumerable,Pc=Object.getOwnPropertyDescriptor,HS=Pc&&!xc.call({1:2},1);wc.f=HS?function(e){var t=Pc(this,e);return!!t&&t.enumerable}:xc});var yr=b((I$,Ac)=>{"use strict";Ac.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Rc=b((E$,kc)=>{"use strict";var jS=ye(),QS=xe(),GS=oi(),Cn=Object,WS=jS("".split);kc.exports=QS(function(){return!Cn("z").propertyIsEnumerable(0)})?function(a){return GS(a)==="String"?WS(a,""):Cn(a)}:Cn});var Li=b((x$,$c)=>{"use strict";$c.exports=function(a){return a==null}});var qt=b((P$,Lc)=>{"use strict";var YS=Li(),zS=TypeError;Lc.exports=function(a){if(YS(a))throw new zS("Can't call method on "+a);return a}});var ui=b((w$,Mc)=>{"use strict";var KS=Rc(),XS=qt();Mc.exports=function(a){return KS(XS(a))}});var He=b((A$,Dc)=>{"use strict";var JS=pe();Dc.exports=function(a){return typeof a=="object"?a!==null:JS(a)}});var Mi=b((k$,Cc)=>{"use strict";Cc.exports={}});var Et=b((R$,Oc)=>{"use strict";var Vn=Mi(),On=me(),ZS=pe(),Vc=function(a){return ZS(a)?a:void 0};Oc.exports=function(a,e){return arguments.length<2?Vc(Vn[a])||Vc(On[a]):Vn[a]&&Vn[a][e]||On[a]&&On[a][e]}});var Tr=b(($$,Bc)=>{"use strict";var ey=ye();Bc.exports=ey({}.isPrototypeOf)});var li=b((L$,Fc)=>{"use strict";var ty=me(),_c=ty.navigator,Nc=_c&&_c.userAgent;Fc.exports=Nc?String(Nc):""});var _n=b((M$,Gc)=>{"use strict";var Qc=me(),Bn=li(),qc=Qc.process,Uc=Qc.Deno,Hc=qc&&qc.versions||Uc&&Uc.version,jc=Hc&&Hc.v8,it,ns;jc&&(it=jc.split("."),ns=it[0]>0&&it[0]<4?1:+(it[0]+it[1]));!ns&&Bn&&(it=Bn.match(/Edge\/(\d+)/),(!it||it[1]>=74)&&(it=Bn.match(/Chrome\/(\d+)/),it&&(ns=+it[1])));Gc.exports=ns});var Nn=b((D$,Yc)=>{"use strict";var Wc=_n(),iy=xe(),ry=me(),ay=ry.String;Yc.exports=!!Object.getOwnPropertySymbols&&!iy(function(){var a=Symbol("symbol detection");return!ay(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Wc&&Wc<41})});var Fn=b((C$,zc)=>{"use strict";var sy=Nn();zc.exports=sy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var qn=b((V$,Kc)=>{"use strict";var ny=Et(),oy=pe(),uy=Tr(),ly=Fn(),cy=Object;Kc.exports=ly?function(a){return typeof a=="symbol"}:function(a){var e=ny("Symbol");return oy(e)&&uy(e.prototype,cy(a))}});var Ir=b((O$,Xc)=>{"use strict";var dy=String;Xc.exports=function(a){try{return dy(a)}catch(e){return"Object"}}});var ht=b((B$,Jc)=>{"use strict";var py=pe(),hy=Ir(),my=TypeError;Jc.exports=function(a){if(py(a))return a;throw new my(hy(a)+" is not a function")}});var Er=b((_$,Zc)=>{"use strict";var fy=ht(),by=Li();Zc.exports=function(a,e){var t=a[e];return by(t)?void 0:fy(t)}});var td=b((N$,ed)=>{"use strict";var Un=Ue(),Hn=pe(),jn=He(),gy=TypeError;ed.exports=function(a,e){var t,i;if(e==="string"&&Hn(t=a.toString)&&!jn(i=Un(t,a))||Hn(t=a.valueOf)&&!jn(i=Un(t,a))||e!=="string"&&Hn(t=a.toString)&&!jn(i=Un(t,a)))return i;throw new gy("Can't convert object to primitive value")}});var rt=b((F$,id)=>{"use strict";id.exports=!0});var sd=b((q$,ad)=>{"use strict";var rd=me(),vy=Object.defineProperty;ad.exports=function(a,e){try{vy(rd,a,{value:e,configurable:!0,writable:!0})}catch(t){rd[a]=e}return e}});var xr=b((U$,ud)=>{"use strict";var Sy=rt(),yy=me(),Ty=sd(),nd="__core-js_shared__",od=ud.exports=yy[nd]||Ty(nd,{});(od.versions||(od.versions=[])).push({version:"3.38.0",mode:Sy?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Qn=b((H$,cd)=>{"use strict";var ld=xr();cd.exports=function(a,e){return ld[a]||(ld[a]=e||{})}});var Di=b((j$,dd)=>{"use strict";var Iy=qt(),Ey=Object;dd.exports=function(a){return Ey(Iy(a))}});var at=b((Q$,pd)=>{"use strict";var xy=ye(),Py=Di(),wy=xy({}.hasOwnProperty);pd.exports=Object.hasOwn||function(e,t){return wy(Py(e),t)}});var Gn=b((G$,hd)=>{"use strict";var Ay=ye(),ky=0,Ry=Math.random(),$y=Ay(1 .toString);hd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+$y(++ky+Ry,36)}});var Pe=b((W$,fd)=>{"use strict";var Ly=me(),My=Qn(),md=at(),Dy=Gn(),Cy=Nn(),Vy=Fn(),Ci=Ly.Symbol,Wn=My("wks"),Oy=Vy?Ci.for||Ci:Ci&&Ci.withoutSetter||Dy;fd.exports=function(a){return md(Wn,a)||(Wn[a]=Cy&&md(Ci,a)?Ci[a]:Oy("Symbol."+a)),Wn[a]}});var Sd=b((Y$,vd)=>{"use strict";var By=Ue(),bd=He(),gd=qn(),_y=Er(),Ny=td(),Fy=Pe(),qy=TypeError,Uy=Fy("toPrimitive");vd.exports=function(a,e){if(!bd(a)||gd(a))return a;var t=_y(a,Uy),i;if(t){if(e===void 0&&(e="default"),i=By(t,a,e),!bd(i)||gd(i))return i;throw new qy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ny(a,e)}});var Yn=b((z$,yd)=>{"use strict";var Hy=Sd(),jy=qn();yd.exports=function(a){var e=Hy(a,"string");return jy(e)?e:e+""}});var os=b((K$,Id)=>{"use strict";var Qy=me(),Td=He(),zn=Qy.document,Gy=Td(zn)&&Td(zn.createElement);Id.exports=function(a){return Gy?zn.createElement(a):{}}});var Kn=b((X$,Ed)=>{"use strict";var Wy=qe(),Yy=xe(),zy=os();Ed.exports=!Wy&&!Yy(function(){return Object.defineProperty(zy("div"),"a",{get:function(){return 7}}).a!==7})});var wd=b(Pd=>{"use strict";var Ky=qe(),Xy=Ue(),Jy=Dn(),Zy=yr(),eT=ui(),tT=Yn(),iT=at(),rT=Kn(),xd=Object.getOwnPropertyDescriptor;Pd.f=Ky?xd:function(e,t){if(e=eT(e),t=tT(t),rT)try{return xd(e,t)}catch(i){}if(iT(e,t))return Zy(!Xy(Jy.f,e,t),e[t])}});var Xn=b((Z$,Ad)=>{"use strict";var aT=xe(),sT=pe(),nT=/#|\.prototype\./,Pr=function(a,e){var t=uT[oT(a)];return t===cT?!0:t===lT?!1:sT(e)?aT(e):!!e},oT=Pr.normalize=function(a){return String(a).replace(nT,".").toLowerCase()},uT=Pr.data={},lT=Pr.NATIVE="N",cT=Pr.POLYFILL="P";Ad.exports=Pr});var Vi=b((eL,Rd)=>{"use strict";var kd=Ln(),dT=ht(),pT=Sr(),hT=kd(kd.bind);Rd.exports=function(a,e){return dT(a),e===void 0?a:pT?hT(a,e):function(){return a.apply(e,arguments)}}});var Jn=b((tL,$d)=>{"use strict";var mT=qe(),fT=xe();$d.exports=mT&&fT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var mt=b((iL,Ld)=>{"use strict";var bT=He(),gT=String,vT=TypeError;Ld.exports=function(a){if(bT(a))return a;throw new vT(gT(a)+" is not an object")}});var ci=b(Dd=>{"use strict";var ST=qe(),yT=Kn(),TT=Jn(),us=mt(),Md=Yn(),IT=TypeError,Zn=Object.defineProperty,ET=Object.getOwnPropertyDescriptor,eo="enumerable",to="configurable",io="writable";Dd.f=ST?TT?function(e,t,i){if(us(e),t=Md(t),us(i),typeof e=="function"&&t==="prototype"&&"value"in i&&io in i&&!i[io]){var r=ET(e,t);r&&r[io]&&(e[t]=i.value,i={configurable:to in i?i[to]:r[to],enumerable:eo in i?i[eo]:r[eo],writable:!1})}return Zn(e,t,i)}:Zn:function(e,t,i){if(us(e),t=Md(t),us(i),yT)try{return Zn(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new IT("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Oi=b((aL,Cd)=>{"use strict";var xT=qe(),PT=ci(),wT=yr();Cd.exports=xT?function(a,e,t){return PT.f(a,e,wT(1,t))}:function(a,e,t){return a[e]=t,a}});var ve=b((sL,Od)=>{"use strict";var wr=me(),AT=Rn(),kT=Ln(),RT=pe(),$T=wd().f,LT=Xn(),Bi=Mi(),MT=Vi(),_i=Oi(),Vd=at();xr();var DT=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 AT(a,this,arguments)};return e.prototype=a.prototype,e};Od.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?wr:r?wr[t]:wr[t]&&wr[t].prototype,o=i?Bi:Bi[t]||_i(Bi,t,{})[t],u=o.prototype,l,c,d,m,h,f,g,S,y;for(m in e)l=LT(i?m:t+(r?".":"#")+m,a.forced),c=!l&&n&&Vd(n,m),f=o[m],c&&(a.dontCallGetSet?(y=$T(n,m),g=y&&y.value):g=n[m]),h=c&&g?g:e[m],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?S=MT(h,wr):a.wrap&&c?S=DT(h):s&&RT(h)?S=kT(h):S=h,(a.sham||h&&h.sham||f&&f.sham)&&_i(S,"sham",!0),_i(o,m,S),s&&(d=t+"Prototype",Vd(Bi,d)||_i(Bi,d,{}),_i(Bi[d],m,h),a.real&&u&&(l||!u[m])&&_i(u,m,h)))}});var _d=b((nL,Bd)=>{"use strict";var CT=Math.ceil,VT=Math.floor;Bd.exports=Math.trunc||function(e){var t=+e;return(t>0?VT:CT)(t)}});var Ar=b((oL,Nd)=>{"use strict";var OT=_d();Nd.exports=function(a){var e=+a;return e!==e||e===0?0:OT(e)}});var qd=b((uL,Fd)=>{"use strict";var BT=Ar(),_T=Math.max,NT=Math.min;Fd.exports=function(a,e){var t=BT(a);return t<0?_T(t+e,0):NT(t,e)}});var ro=b((lL,Ud)=>{"use strict";var FT=Ar(),qT=Math.min;Ud.exports=function(a){var e=FT(a);return e>0?qT(e,9007199254740991):0}});var Ni=b((cL,Hd)=>{"use strict";var UT=ro();Hd.exports=function(a){return UT(a.length)}});var ao=b((dL,Qd)=>{"use strict";var HT=ui(),jT=qd(),QT=Ni(),jd=function(a){return function(e,t,i){var r=HT(e),s=QT(r);if(s===0)return!a&&-1;var n=jT(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}};Qd.exports={includes:jd(!0),indexOf:jd(!1)}});var kr=b((pL,Gd)=>{"use strict";Gd.exports=function(){}});var Wd=b(()=>{"use strict";var GT=ve(),WT=ao().includes,YT=xe(),zT=kr(),KT=YT(function(){return!Array(1).includes()});GT({target:"Array",proto:!0,forced:KT},{includes:function(e){return WT(this,e,arguments.length>1?arguments[1]:void 0)}});zT("includes")});var Ut=b((fL,Yd)=>{"use strict";var XT=Et();Yd.exports=XT});var Kd=b((bL,zd)=>{"use strict";Wd();var JT=Ut();zd.exports=JT("Array","includes")});var Jd=b((gL,Xd)=>{"use strict";var ZT=Kd();Xd.exports=ZT});var Ye=b((vL,Zd)=>{"use strict";var eI=Jd();Zd.exports=eI});var cs=b((RL,ip)=>{"use strict";var iI=Qn(),rI=Gn(),tp=iI("keys");ip.exports=function(a){return tp[a]||(tp[a]=rI(a))}});var ap=b(($L,rp)=>{"use strict";var aI=xe();rp.exports=!aI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ds=b((LL,np)=>{"use strict";var sI=at(),nI=pe(),oI=Di(),uI=cs(),lI=ap(),sp=uI("IE_PROTO"),so=Object,cI=so.prototype;np.exports=lI?so.getPrototypeOf:function(a){var e=oI(a);if(sI(e,sp))return e[sp];var t=e.constructor;return nI(t)&&e instanceof t?t.prototype:e instanceof so?cI:null}});var ps=b((ML,op)=>{"use strict";op.exports={}});var cp=b((DL,lp)=>{"use strict";var dI=ye(),no=at(),pI=ui(),hI=ao().indexOf,mI=ps(),up=dI([].push);lp.exports=function(a,e){var t=pI(a),i=0,r=[],s;for(s in t)!no(mI,s)&&no(t,s)&&up(r,s);for(;e.length>i;)no(t,s=e[i++])&&(~hI(r,s)||up(r,s));return r}});var oo=b((CL,dp)=>{"use strict";dp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var uo=b((VL,pp)=>{"use strict";var fI=cp(),bI=oo();pp.exports=Object.keys||function(e){return fI(e,bI)}});var lo=b((OL,gp)=>{"use strict";var mp=qe(),gI=xe(),fp=ye(),vI=ds(),SI=uo(),yI=ui(),TI=Dn().f,bp=fp(TI),II=fp([].push),EI=mp&&gI(function(){var a=Object.create(null);return a[2]=2,!bp(a,2)}),hp=function(a){return function(e){for(var t=yI(e),i=SI(t),r=EI&&vI(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!mp||(r?u in t:bp(t,u)))&&II(o,a?[u,t[u]]:t[u]);return o}};gp.exports={entries:hp(!0),values:hp(!1)}});var vp=b(()=>{"use strict";var xI=ve(),PI=lo().entries;xI({target:"Object",stat:!0},{entries:function(e){return PI(e)}})});var yp=b((NL,Sp)=>{"use strict";vp();var wI=Mi();Sp.exports=wI.Object.entries});var Ip=b((FL,Tp)=>{"use strict";var AI=yp();Tp.exports=AI});var Fi=b((qL,Ep)=>{"use strict";var kI=Ip();Ep.exports=kI});var di=b((UL,xp)=>{"use strict";xp.exports={}});var Ap=b((HL,wp)=>{"use strict";var RI=me(),$I=pe(),Pp=RI.WeakMap;wp.exports=$I(Pp)&&/native code/.test(String(Pp))});var mo=b((jL,$p)=>{"use strict";var LI=Ap(),Rp=me(),MI=He(),DI=Oi(),co=at(),po=xr(),CI=cs(),VI=ps(),kp="Object already initialized",ho=Rp.TypeError,OI=Rp.WeakMap,hs,Rr,ms,BI=function(a){return ms(a)?Rr(a):hs(a,{})},_I=function(a){return function(e){var t;if(!MI(e)||(t=Rr(e)).type!==a)throw new ho("Incompatible receiver, "+a+" required");return t}};LI||po.state?(st=po.state||(po.state=new OI),st.get=st.get,st.has=st.has,st.set=st.set,hs=function(a,e){if(st.has(a))throw new ho(kp);return e.facade=a,st.set(a,e),e},Rr=function(a){return st.get(a)||{}},ms=function(a){return st.has(a)}):(pi=CI("state"),VI[pi]=!0,hs=function(a,e){if(co(a,pi))throw new ho(kp);return e.facade=a,DI(a,pi,e),e},Rr=function(a){return co(a,pi)?a[pi]:{}},ms=function(a){return co(a,pi)});var st,pi;$p.exports={set:hs,get:Rr,has:ms,enforce:BI,getterFor:_I}});var go=b((QL,Mp)=>{"use strict";var fo=qe(),NI=at(),Lp=Function.prototype,FI=fo&&Object.getOwnPropertyDescriptor,bo=NI(Lp,"name"),qI=bo&&function(){}.name==="something",UI=bo&&(!fo||fo&&FI(Lp,"name").configurable);Mp.exports={EXISTS:bo,PROPER:qI,CONFIGURABLE:UI}});var Cp=b(Dp=>{"use strict";var HI=qe(),jI=Jn(),QI=ci(),GI=mt(),WI=ui(),YI=uo();Dp.f=HI&&!jI?Object.defineProperties:function(e,t){GI(e);for(var i=WI(t),r=YI(t),s=r.length,n=0,o;s>n;)QI.f(e,o=r[n++],i[o]);return e}});var vo=b((WL,Vp)=>{"use strict";var zI=Et();Vp.exports=zI("document","documentElement")});var Io=b((YL,Up)=>{"use strict";var KI=mt(),XI=Cp(),Op=oo(),JI=ps(),ZI=vo(),eE=os(),tE=cs(),Bp=">",_p="<",yo="prototype",To="script",Fp=tE("IE_PROTO"),So=function(){},qp=function(a){return _p+To+Bp+a+_p+"/"+To+Bp},Np=function(a){a.write(qp("")),a.close();var e=a.parentWindow.Object;return a=null,e},iE=function(){var a=eE("iframe"),e="java"+To+":",t;return a.style.display="none",ZI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(qp("document.F=Object")),t.close(),t.F},fs,bs=function(){try{fs=new ActiveXObject("htmlfile")}catch(e){}bs=typeof document!="undefined"?document.domain&&fs?Np(fs):iE():Np(fs);for(var a=Op.length;a--;)delete bs[yo][Op[a]];return bs()};JI[Fp]=!0;Up.exports=Object.create||function(e,t){var i;return e!==null?(So[yo]=KI(e),i=new So,So[yo]=null,i[Fp]=e):i=bs(),t===void 0?i:XI.f(i,t)}});var qi=b((zL,Hp)=>{"use strict";var rE=Oi();Hp.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:rE(a,e,t),a}});var wo=b((KL,Gp)=>{"use strict";var aE=xe(),sE=pe(),nE=He(),oE=Io(),jp=ds(),uE=qi(),lE=Pe(),cE=rt(),Po=lE("iterator"),Qp=!1,xt,Eo,xo;[].keys&&(xo=[].keys(),"next"in xo?(Eo=jp(jp(xo)),Eo!==Object.prototype&&(xt=Eo)):Qp=!0);var dE=!nE(xt)||aE(function(){var a={};return xt[Po].call(a)!==a});dE?xt={}:cE&&(xt=oE(xt));sE(xt[Po])||uE(xt,Po,function(){return this});Gp.exports={IteratorPrototype:xt,BUGGY_SAFARI_ITERATORS:Qp}});var gs=b((XL,Yp)=>{"use strict";var pE=Pe(),hE=pE("toStringTag"),Wp={};Wp[hE]="z";Yp.exports=String(Wp)==="[object z]"});var $r=b((JL,zp)=>{"use strict";var mE=gs(),fE=pe(),vs=oi(),bE=Pe(),gE=bE("toStringTag"),vE=Object,SE=vs(function(){return arguments}())==="Arguments",yE=function(a,e){try{return a[e]}catch(t){}};zp.exports=mE?vs:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=yE(e=vE(a),gE))=="string"?t:SE?vs(e):(i=vs(e))==="Object"&&fE(e.callee)?"Arguments":i}});var Xp=b((ZL,Kp)=>{"use strict";var TE=gs(),IE=$r();Kp.exports=TE?{}.toString:function(){return"[object "+IE(this)+"]"}});var Lr=b((eM,Zp)=>{"use strict";var EE=gs(),xE=ci().f,PE=Oi(),wE=at(),AE=Xp(),kE=Pe(),Jp=kE("toStringTag");Zp.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(wE(r,Jp)||xE(r,Jp,{configurable:!0,value:e}),i&&!EE&&PE(r,"toString",AE))}});var th=b((tM,eh)=>{"use strict";var RE=wo().IteratorPrototype,$E=Io(),LE=yr(),ME=Lr(),DE=di(),CE=function(){return this};eh.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=$E(RE,{next:LE(+!i,t)}),ME(a,r,!1,!0),DE[r]=CE,a}});var rh=b((iM,ih)=>{"use strict";var VE=ye(),OE=ht();ih.exports=function(a,e,t){try{return VE(OE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var sh=b((rM,ah)=>{"use strict";var BE=He();ah.exports=function(a){return BE(a)||a===null}});var oh=b((aM,nh)=>{"use strict";var _E=sh(),NE=String,FE=TypeError;nh.exports=function(a){if(_E(a))return a;throw new FE("Can't set "+NE(a)+" as a prototype")}});var Ao=b((sM,uh)=>{"use strict";var qE=rh(),UE=He(),HE=qt(),jE=oh();uh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=qE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return HE(r),jE(s),UE(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Sh=b((nM,vh)=>{"use strict";var QE=ve(),GE=Ue(),Ss=rt(),bh=go(),WE=pe(),YE=th(),lh=ds(),ch=Ao(),zE=Lr(),KE=Oi(),ko=qi(),XE=Pe(),dh=di(),gh=wo(),JE=bh.PROPER,ZE=bh.CONFIGURABLE,ph=gh.IteratorPrototype,ys=gh.BUGGY_SAFARI_ITERATORS,Mr=XE("iterator"),hh="keys",Dr="values",mh="entries",fh=function(){return this};vh.exports=function(a,e,t,i,r,s,n){YE(t,e,i);var o=function(y){if(y===r&&m)return m;if(!ys&&y&&y in c)return c[y];switch(y){case hh:return function(){return new t(this,y)};case Dr:return function(){return new t(this,y)};case mh:return function(){return new t(this,y)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Mr]||c["@@iterator"]||r&&c[r],m=!ys&&d||o(r),h=e==="Array"&&c.entries||d,f,g,S;if(h&&(f=lh(h.call(new a)),f!==Object.prototype&&f.next&&(!Ss&&lh(f)!==ph&&(ch?ch(f,ph):WE(f[Mr])||ko(f,Mr,fh)),zE(f,u,!0,!0),Ss&&(dh[u]=fh))),JE&&r===Dr&&d&&d.name!==Dr&&(!Ss&&ZE?KE(c,"name",Dr):(l=!0,m=function(){return GE(d,this)})),r)if(g={values:o(Dr),keys:s?m:o(hh),entries:o(mh)},n)for(S in g)(ys||l||!(S in c))&&ko(c,S,g[S]);else QE({target:e,proto:!0,forced:ys||l},g);return(!Ss||n)&&c[Mr]!==m&&ko(c,Mr,m,{name:r}),dh[e]=m,g}});var Th=b((oM,yh)=>{"use strict";yh.exports=function(a,e){return{value:a,done:e}}});var $o=b((uM,wh)=>{"use strict";var ex=ui(),Ro=kr(),Ih=di(),xh=mo(),tx=ci().f,ix=Sh(),Ts=Th(),rx=rt(),ax=qe(),Ph="Array Iterator",sx=xh.set,nx=xh.getterFor(Ph);wh.exports=ix(Array,"Array",function(a,e){sx(this,{type:Ph,target:ex(a),index:0,kind:e})},function(){var a=nx(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ts(void 0,!0);switch(a.kind){case"keys":return Ts(t,!1);case"values":return Ts(e[t],!1)}return Ts([t,e[t]],!1)},"values");var Eh=Ih.Arguments=Ih.Array;Ro("keys");Ro("values");Ro("entries");if(!rx&&ax&&Eh.name!=="values")try{tx(Eh,"name",{value:"values"})}catch(a){}});var kh=b((lM,Ah)=>{"use strict";var ox=Pe(),ux=di(),lx=ox("iterator"),cx=Array.prototype;Ah.exports=function(a){return a!==void 0&&(ux.Array===a||cx[lx]===a)}});var Lo=b((cM,$h)=>{"use strict";var dx=$r(),Rh=Er(),px=Li(),hx=di(),mx=Pe(),fx=mx("iterator");$h.exports=function(a){if(!px(a))return Rh(a,fx)||Rh(a,"@@iterator")||hx[dx(a)]}});var Mh=b((dM,Lh)=>{"use strict";var bx=Ue(),gx=ht(),vx=mt(),Sx=Ir(),yx=Lo(),Tx=TypeError;Lh.exports=function(a,e){var t=arguments.length<2?yx(a):e;if(gx(t))return vx(bx(t,a));throw new Tx(Sx(a)+" is not iterable")}});var Vh=b((pM,Ch)=>{"use strict";var Ix=Ue(),Dh=mt(),Ex=Er();Ch.exports=function(a,e,t){var i,r;Dh(a);try{if(i=Ex(a,"return"),!i){if(e==="throw")throw t;return t}i=Ix(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Dh(i),t}});var Es=b((hM,Nh)=>{"use strict";var xx=Vi(),Px=Ue(),wx=mt(),Ax=Ir(),kx=kh(),Rx=Ni(),Oh=Tr(),$x=Mh(),Lx=Lo(),Bh=Vh(),Mx=TypeError,Is=function(a,e){this.stopped=a,this.result=e},_h=Is.prototype;Nh.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=xx(e,i),l,c,d,m,h,f,g,S=function(E){return l&&Bh(l,"normal",E),new Is(!0,E)},y=function(E){return r?(wx(E),o?u(E[0],E[1],S):u(E[0],E[1])):o?u(E,S):u(E)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Lx(a),!c)throw new Mx(Ax(a)+" is not iterable");if(kx(c)){for(d=0,m=Rx(a);m>d;d++)if(h=y(a[d]),h&&Oh(_h,h))return h;return new Is(!1)}l=$x(a,c)}for(f=s?a.next:l.next;!(g=Px(f,l)).done;){try{h=y(g.value)}catch(E){Bh(l,"throw",E)}if(typeof h=="object"&&h&&Oh(_h,h))return h}return new Is(!1)}});var qh=b((mM,Fh)=>{"use strict";var Dx=qe(),Cx=ci(),Vx=yr();Fh.exports=function(a,e,t){Dx?Cx.f(a,e,Vx(0,t)):a[e]=t}});var Uh=b(()=>{"use strict";var Ox=ve(),Bx=Es(),_x=qh();Ox({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Bx(e,function(i,r){_x(t,i,r)},{AS_ENTRIES:!0}),t}})});var jh=b((gM,Hh)=>{"use strict";$o();Uh();var Nx=Mi();Hh.exports=Nx.Object.fromEntries});var Gh=b((vM,Qh)=>{"use strict";Qh.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 Yh=b(()=>{"use strict";$o();var Fx=Gh(),qx=me(),Ux=Lr(),Wh=di();for(xs in Fx)Ux(qx[xs],xs),Wh[xs]=Wh.Array;var xs});var Kh=b((TM,zh)=>{"use strict";var Hx=jh();Yh();zh.exports=Hx});var Mo=b((IM,Xh)=>{"use strict";var jx=Kh();Xh.exports=jx});var Jh=b(()=>{"use strict"});var Do=b((PM,Zh)=>{"use strict";var Cr=me(),Qx=li(),Gx=oi(),Ps=function(a){return Qx.slice(0,a.length)===a};Zh.exports=function(){return Ps("Bun/")?"BUN":Ps("Cloudflare-Workers")?"CLOUDFLARE":Ps("Deno/")?"DENO":Ps("Node.js/")?"NODE":Cr.Bun&&typeof Bun.version=="string"?"BUN":Cr.Deno&&typeof Deno.version=="object"?"DENO":Gx(Cr.process)==="process"?"NODE":Cr.window&&Cr.document?"BROWSER":"REST"}()});var ws=b((wM,em)=>{"use strict";var Wx=Do();em.exports=Wx==="NODE"});var im=b((AM,tm)=>{"use strict";var Yx=ci();tm.exports=function(a,e,t){return Yx.f(a,e,t)}});var sm=b((kM,am)=>{"use strict";var zx=Et(),Kx=im(),Xx=Pe(),Jx=qe(),rm=Xx("species");am.exports=function(a){var e=zx(a);Jx&&e&&!e[rm]&&Kx(e,rm,{configurable:!0,get:function(){return this}})}});var om=b((RM,nm)=>{"use strict";var Zx=Tr(),eP=TypeError;nm.exports=function(a,e){if(Zx(e,a))return a;throw new eP("Incorrect invocation")}});var Vo=b(($M,um)=>{"use strict";var tP=ye(),iP=pe(),Co=xr(),rP=tP(Function.toString);iP(Co.inspectSource)||(Co.inspectSource=function(a){return rP(a)});um.exports=Co.inspectSource});var Bo=b((LM,hm)=>{"use strict";var aP=ye(),sP=xe(),lm=pe(),nP=$r(),oP=Et(),uP=Vo(),cm=function(){},dm=oP("Reflect","construct"),Oo=/^\s*(?:class|function)\b/,lP=aP(Oo.exec),cP=!Oo.test(cm),Vr=function(e){if(!lm(e))return!1;try{return dm(cm,[],e),!0}catch(t){return!1}},pm=function(e){if(!lm(e))return!1;switch(nP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return cP||!!lP(Oo,uP(e))}catch(t){return!0}};pm.sham=!0;hm.exports=!dm||sP(function(){var a;return Vr(Vr.call)||!Vr(Object)||!Vr(function(){a=!0})||a})?pm:Vr});var fm=b((MM,mm)=>{"use strict";var dP=Bo(),pP=Ir(),hP=TypeError;mm.exports=function(a){if(dP(a))return a;throw new hP(pP(a)+" is not a constructor")}});var _o=b((DM,gm)=>{"use strict";var bm=mt(),mP=fm(),fP=Li(),bP=Pe(),gP=bP("species");gm.exports=function(a,e){var t=bm(a).constructor,i;return t===void 0||fP(i=bm(t)[gP])?e:mP(i)}});var Sm=b((CM,vm)=>{"use strict";var vP=ye();vm.exports=vP([].slice)});var Tm=b((VM,ym)=>{"use strict";var SP=TypeError;ym.exports=function(a,e){if(a<e)throw new SP("Not enough arguments");return a}});var No=b((OM,Im)=>{"use strict";var yP=li();Im.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(yP)});var Yo=b((BM,Lm)=>{"use strict";var je=me(),TP=Rn(),IP=Vi(),Em=pe(),EP=at(),$m=xe(),xm=vo(),xP=Sm(),Pm=os(),PP=Tm(),wP=No(),AP=ws(),Qo=je.setImmediate,Go=je.clearImmediate,kP=je.process,Fo=je.Dispatch,RP=je.Function,wm=je.MessageChannel,$P=je.String,qo=0,Or={},Am="onreadystatechange",Br,hi,Uo,Ho;$m(function(){Br=je.location});var Wo=function(a){if(EP(Or,a)){var e=Or[a];delete Or[a],e()}},jo=function(a){return function(){Wo(a)}},km=function(a){Wo(a.data)},Rm=function(a){je.postMessage($P(a),Br.protocol+"//"+Br.host)};(!Qo||!Go)&&(Qo=function(e){PP(arguments.length,1);var t=Em(e)?e:RP(e),i=xP(arguments,1);return Or[++qo]=function(){TP(t,void 0,i)},hi(qo),qo},Go=function(e){delete Or[e]},AP?hi=function(a){kP.nextTick(jo(a))}:Fo&&Fo.now?hi=function(a){Fo.now(jo(a))}:wm&&!wP?(Uo=new wm,Ho=Uo.port2,Uo.port1.onmessage=km,hi=IP(Ho.postMessage,Ho)):je.addEventListener&&Em(je.postMessage)&&!je.importScripts&&Br&&Br.protocol!=="file:"&&!$m(Rm)?(hi=Rm,je.addEventListener("message",km,!1)):Am in Pm("script")?hi=function(a){xm.appendChild(Pm("script"))[Am]=function(){xm.removeChild(this),Wo(a)}}:hi=function(a){setTimeout(jo(a),0)});Lm.exports={set:Qo,clear:Go}});var Cm=b((_M,Dm)=>{"use strict";var Mm=me(),LP=qe(),MP=Object.getOwnPropertyDescriptor;Dm.exports=function(a){if(!LP)return Mm[a];var e=MP(Mm,a);return e&&e.value}});var zo=b((NM,Om)=>{"use strict";var Vm=function(){this.head=null,this.tail=null};Vm.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}}};Om.exports=Vm});var _m=b((FM,Bm)=>{"use strict";var DP=li();Bm.exports=/ipad|iphone|ipod/i.test(DP)&&typeof Pebble!="undefined"});var Fm=b((qM,Nm)=>{"use strict";var CP=li();Nm.exports=/web0s(?!.*chrome)/i.test(CP)});var Wm=b((UM,Gm)=>{"use strict";var Hi=me(),VP=Cm(),qm=Vi(),Ko=Yo().set,OP=zo(),BP=No(),_P=_m(),NP=Fm(),Xo=ws(),Um=Hi.MutationObserver||Hi.WebKitMutationObserver,Hm=Hi.document,jm=Hi.process,As=Hi.Promise,eu=VP("queueMicrotask"),Ui,Jo,Zo,ks,Qm;eu||(_r=new OP,Nr=function(){var a,e;for(Xo&&(a=jm.domain)&&a.exit();e=_r.get();)try{e()}catch(t){throw _r.head&&Ui(),t}a&&a.enter()},!BP&&!Xo&&!NP&&Um&&Hm?(Jo=!0,Zo=Hm.createTextNode(""),new Um(Nr).observe(Zo,{characterData:!0}),Ui=function(){Zo.data=Jo=!Jo}):!_P&&As&&As.resolve?(ks=As.resolve(void 0),ks.constructor=As,Qm=qm(ks.then,ks),Ui=function(){Qm(Nr)}):Xo?Ui=function(){jm.nextTick(Nr)}:(Ko=qm(Ko,Hi),Ui=function(){Ko(Nr)}),eu=function(a){_r.head||Ui(),_r.add(a)});var _r,Nr;Gm.exports=eu});var zm=b((HM,Ym)=>{"use strict";Ym.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Rs=b((jM,Km)=>{"use strict";Km.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var mi=b((QM,Xm)=>{"use strict";var FP=me();Xm.exports=FP.Promise});var ji=b((GM,tf)=>{"use strict";var qP=me(),Fr=mi(),UP=pe(),HP=Xn(),jP=Vo(),QP=Pe(),Jm=Do(),GP=rt(),tu=_n(),Zm=Fr&&Fr.prototype,WP=QP("species"),iu=!1,ef=UP(qP.PromiseRejectionEvent),YP=HP("Promise",function(){var a=jP(Fr),e=a!==String(Fr);if(!e&&tu===66||GP&&!(Zm.catch&&Zm.finally))return!0;if(!tu||tu<51||!/native code/.test(a)){var t=new Fr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[WP]=i,iu=t.then(function(){})instanceof i,!iu)return!0}return!e&&(Jm==="BROWSER"||Jm==="DENO")&&!ef});tf.exports={CONSTRUCTOR:YP,REJECTION_EVENT:ef,SUBCLASSING:iu}});var Qi=b((WM,af)=>{"use strict";var rf=ht(),zP=TypeError,KP=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new zP("Bad Promise constructor");e=i,t=r}),this.resolve=rf(e),this.reject=rf(t)};af.exports.f=function(a){return new KP(a)}});var Ef=b(()=>{"use strict";var XP=ve(),JP=rt(),Ds=ws(),Ht=me(),zi=Ue(),sf=qi(),nf=Ao(),ZP=Lr(),ew=sm(),tw=ht(),Ms=pe(),iw=He(),rw=om(),aw=_o(),df=Yo().set,ou=Wm(),sw=zm(),nw=Rs(),ow=zo(),pf=mo(),Cs=mi(),uu=ji(),hf=Qi(),Vs="Promise",mf=uu.CONSTRUCTOR,uw=uu.REJECTION_EVENT,lw=uu.SUBCLASSING,ru=pf.getterFor(Vs),cw=pf.set,Gi=Cs&&Cs.prototype,fi=Cs,$s=Gi,ff=Ht.TypeError,au=Ht.document,lu=Ht.process,su=hf.f,dw=su,pw=!!(au&&au.createEvent&&Ht.dispatchEvent),bf="unhandledrejection",hw="rejectionhandled",of=0,gf=1,mw=2,cu=1,vf=2,Ls,uf,fw,lf,Sf=function(a){var e;return iw(a)&&Ms(e=a.then)?e:!1},yf=function(a,e){var t=e.value,i=e.state===gf,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===vf&&gw(e),e.rejection=cu),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new ff("Promise-chain cycle")):(l=Sf(u))?zi(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Tf=function(a,e){a.notified||(a.notified=!0,ou(function(){for(var t=a.reactions,i;i=t.get();)yf(i,a);a.notified=!1,e&&!a.rejection&&bw(a)}))},If=function(a,e,t){var i,r;pw?(i=au.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Ht.dispatchEvent(i)):i={promise:e,reason:t},!uw&&(r=Ht["on"+a])?r(i):a===bf&&sw("Unhandled promise rejection",t)},bw=function(a){zi(df,Ht,function(){var e=a.facade,t=a.value,i=cf(a),r;if(i&&(r=nw(function(){Ds?lu.emit("unhandledRejection",t,e):If(bf,e,t)}),a.rejection=Ds||cf(a)?vf:cu,r.error))throw r.value})},cf=function(a){return a.rejection!==cu&&!a.parent},gw=function(a){zi(df,Ht,function(){var e=a.facade;Ds?lu.emit("rejectionHandled",e):If(hw,e,a.value)})},Wi=function(a,e,t){return function(i){a(e,i,t)}},Yi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=mw,Tf(a,!0))},nu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new ff("Promise can't be resolved itself");var i=Sf(e);i?ou(function(){var r={done:!1};try{zi(i,e,Wi(nu,r,a),Wi(Yi,r,a))}catch(s){Yi(r,s,a)}}):(a.value=e,a.state=gf,Tf(a,!1))}catch(r){Yi({done:!1},r,a)}}};if(mf&&(fi=function(e){rw(this,$s),tw(e),zi(Ls,this);var t=ru(this);try{e(Wi(nu,t),Wi(Yi,t))}catch(i){Yi(t,i)}},$s=fi.prototype,Ls=function(e){cw(this,{type:Vs,done:!1,notified:!1,parent:!1,reactions:new ow,rejection:!1,state:of,value:void 0})},Ls.prototype=sf($s,"then",function(e,t){var i=ru(this),r=su(aw(this,fi));return i.parent=!0,r.ok=Ms(e)?e:!0,r.fail=Ms(t)&&t,r.domain=Ds?lu.domain:void 0,i.state===of?i.reactions.add(r):ou(function(){yf(r,i)}),r.promise}),uf=function(){var a=new Ls,e=ru(a);this.promise=a,this.resolve=Wi(nu,e),this.reject=Wi(Yi,e)},hf.f=su=function(a){return a===fi||a===fw?new uf(a):dw(a)},!JP&&Ms(Cs)&&Gi!==Object.prototype)){lf=Gi.then,lw||sf(Gi,"then",function(e,t){var i=this;return new fi(function(r,s){zi(lf,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Gi.constructor}catch(a){}nf&&nf(Gi,$s)}XP({global:!0,constructor:!0,wrap:!0,forced:mf},{Promise:fi});ZP(fi,Vs,!1,!0);ew(Vs)});var kf=b((KM,Af)=>{"use strict";var vw=Pe(),Pf=vw("iterator"),wf=!1;try{xf=0,du={next:function(){return{done:!!xf++}},return:function(){wf=!0}},du[Pf]=function(){return this},Array.from(du,function(){throw 2})}catch(a){}var xf,du;Af.exports=function(a,e){try{if(!e&&!wf)return!1}catch(r){return!1}var t=!1;try{var i={};i[Pf]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var pu=b((XM,Rf)=>{"use strict";var Sw=mi(),yw=kf(),Tw=ji().CONSTRUCTOR;Rf.exports=Tw||!yw(function(a){Sw.all(a).then(void 0,function(){})})});var $f=b(()=>{"use strict";var Iw=ve(),Ew=Ue(),xw=ht(),Pw=Qi(),ww=Rs(),Aw=Es(),kw=pu();Iw({target:"Promise",stat:!0,forced:kw},{all:function(e){var t=this,i=Pw.f(t),r=i.resolve,s=i.reject,n=ww(function(){var o=xw(t.resolve),u=[],l=0,c=1;Aw(e,function(d){var m=l++,h=!1;c++,Ew(o,t,d).then(function(f){h||(h=!0,u[m]=f,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var Mf=b(()=>{"use strict";var Rw=ve(),$w=rt(),Lw=ji().CONSTRUCTOR,mu=mi(),Mw=Et(),Dw=pe(),Cw=qi(),Lf=mu&&mu.prototype;Rw({target:"Promise",proto:!0,forced:Lw,real:!0},{catch:function(a){return this.then(void 0,a)}});!$w&&Dw(mu)&&(hu=Mw("Promise").prototype.catch,Lf.catch!==hu&&Cw(Lf,"catch",hu,{unsafe:!0}));var hu});var Df=b(()=>{"use strict";var Vw=ve(),Ow=Ue(),Bw=ht(),_w=Qi(),Nw=Rs(),Fw=Es(),qw=pu();Vw({target:"Promise",stat:!0,forced:qw},{race:function(e){var t=this,i=_w.f(t),r=i.reject,s=Nw(function(){var n=Bw(t.resolve);Fw(e,function(o){Ow(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Cf=b(()=>{"use strict";var Uw=ve(),Hw=Qi(),jw=ji().CONSTRUCTOR;Uw({target:"Promise",stat:!0,forced:jw},{reject:function(e){var t=Hw.f(this),i=t.reject;return i(e),t.promise}})});var fu=b((nD,Vf)=>{"use strict";var Qw=mt(),Gw=He(),Ww=Qi();Vf.exports=function(a,e){if(Qw(a),Gw(e)&&e.constructor===a)return e;var t=Ww.f(a),i=t.resolve;return i(e),t.promise}});var _f=b(()=>{"use strict";var Yw=ve(),zw=Et(),Of=rt(),Kw=mi(),Bf=ji().CONSTRUCTOR,Xw=fu(),Jw=zw("Promise"),Zw=Of&&!Bf;Yw({target:"Promise",stat:!0,forced:Of||Bf},{resolve:function(e){return Xw(Zw&&this===Jw?Kw:this,e)}})});var Nf=b(()=>{"use strict";Ef();$f();Mf();Df();Cf();_f()});var Hf=b(()=>{"use strict";var eA=ve(),tA=rt(),Os=mi(),iA=xe(),qf=Et(),Uf=pe(),rA=_o(),Ff=fu(),aA=qi(),gu=Os&&Os.prototype,sA=!!Os&&iA(function(){gu.finally.call({then:function(){}},function(){})});eA({target:"Promise",proto:!0,real:!0,forced:sA},{finally:function(a){var e=rA(this,qf("Promise")),t=Uf(a);return this.then(t?function(i){return Ff(e,a()).then(function(){return i})}:a,t?function(i){return Ff(e,a()).then(function(){throw i})}:a)}});!tA&&Uf(Os)&&(bu=qf("Promise").prototype.finally,gu.finally!==bu&&aA(gu,"finally",bu,{unsafe:!0}));var bu});var Qf=b((hD,jf)=>{"use strict";Jh();Nf();Hf();var nA=Ut();jf.exports=nA("Promise","finally")});var Wf=b((mD,Gf)=>{"use strict";var oA=Qf();Gf.exports=oA});var Bs=b((fD,Yf)=>{"use strict";var uA=Wf();Yf.exports=uA});var tb=b(()=>{"use strict";var hA=ve(),mA=lo().values;hA({target:"Object",stat:!0},{values:function(e){return mA(e)}})});var rb=b((GD,ib)=>{"use strict";tb();var fA=Mi();ib.exports=fA.Object.values});var sb=b((WD,ab)=>{"use strict";var bA=rb();ab.exports=bA});var Ki=b((YD,nb)=>{"use strict";var gA=sb();nb.exports=gA});var vb=b(()=>{"use strict";var AA=ve(),kA=Di(),RA=Ni(),$A=Ar(),LA=kr();AA({target:"Array",proto:!0},{at:function(e){var t=kA(this),i=RA(t),r=$A(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});LA("at")});var yb=b((JC,Sb)=>{"use strict";vb();var MA=Ut();Sb.exports=MA("Array","at")});var Ib=b((ZC,Tb)=>{"use strict";var DA=yb();Tb.exports=DA});var Wt=b((e0,Eb)=>{"use strict";var CA=Ib();Eb.exports=CA});var Bu=b((kV,Qb)=>{"use strict";var GA=oi();Qb.exports=Array.isArray||function(e){return GA(e)==="Array"}});var Wb=b((RV,Gb)=>{"use strict";var WA=TypeError,YA=9007199254740991;Gb.exports=function(a){if(a>YA)throw WA("Maximum allowed index exceeded");return a}});var Kb=b(($V,zb)=>{"use strict";var zA=Bu(),KA=Ni(),XA=Wb(),JA=Vi(),Yb=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?JA(n,o):!1,d,m;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&zA(d)?(m=KA(d),u=Yb(a,e,d,m,u,s-1)-1):(XA(u+1),a[u]=d),u++),l++;return u};zb.exports=Yb});var eg=b((LV,Zb)=>{"use strict";var Xb=Bu(),ZA=Bo(),ek=He(),tk=Pe(),ik=tk("species"),Jb=Array;Zb.exports=function(a){var e;return Xb(a)&&(e=a.constructor,ZA(e)&&(e===Jb||Xb(e.prototype))?e=void 0:ek(e)&&(e=e[ik],e===null&&(e=void 0))),e===void 0?Jb:e}});var ig=b((MV,tg)=>{"use strict";var rk=eg();tg.exports=function(a,e){return new(rk(a))(e===0?0:e)}});var rg=b(()=>{"use strict";var ak=ve(),sk=Kb(),nk=ht(),ok=Di(),uk=Ni(),lk=ig();ak({target:"Array",proto:!0},{flatMap:function(e){var t=ok(this),i=uk(t),r;return nk(e),r=lk(t,0),r.length=sk(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var ag=b(()=>{"use strict";var ck=kr();ck("flatMap")});var ng=b((BV,sg)=>{"use strict";rg();ag();var dk=Ut();sg.exports=dk("Array","flatMap")});var ug=b((_V,og)=>{"use strict";var pk=ng();og.exports=pk});var _u=b((NV,lg)=>{"use strict";var hk=ug();lg.exports=hk});var Jr=b((FV,cg)=>{"use strict";var mk=$r(),fk=String;cg.exports=function(a){if(mk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return fk(a)}});var Nu=b((qV,dg)=>{"use strict";dg.exports=`
7
- \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var mg=b((UV,hg)=>{"use strict";var bk=ye(),gk=qt(),vk=Jr(),qu=Nu(),pg=bk("".replace),Sk=RegExp("^["+qu+"]+"),yk=RegExp("(^|[^"+qu+"])["+qu+"]+$"),Fu=function(a){return function(e){var t=vk(gk(e));return a&1&&(t=pg(t,Sk,"")),a&2&&(t=pg(t,yk,"$1")),t}};hg.exports={start:Fu(1),end:Fu(2),trim:Fu(3)}});var vg=b((HV,gg)=>{"use strict";var Tk=go().PROPER,Ik=xe(),fg=Nu(),bg="\u200B\x85\u180E";gg.exports=function(a){return Ik(function(){return!!fg[a]()||bg[a]()!==bg||Tk&&fg[a].name!==a})}});var Uu=b((jV,Sg)=>{"use strict";var Ek=mg().start,xk=vg();Sg.exports=xk("trimStart")?function(){return Ek(this)}:"".trimStart});var Tg=b(()=>{"use strict";var Pk=ve(),yg=Uu();Pk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==yg},{trimLeft:yg})});var Eg=b(()=>{"use strict";Tg();var wk=ve(),Ig=Uu();wk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Ig},{trimStart:Ig})});var Pg=b((zV,xg)=>{"use strict";Eg();var Ak=Ut();xg.exports=Ak("String","trimLeft")});var Ag=b((KV,wg)=>{"use strict";var kk=Pg();wg.exports=kk});var Rg=b((XV,kg)=>{"use strict";var Rk=Ag();kg.exports=Rk});var Hg=b(()=>{"use strict"});var jg=b(()=>{"use strict"});var Gg=b((A_,Qg)=>{"use strict";var zk=He(),Kk=oi(),Xk=Pe(),Jk=Xk("match");Qg.exports=function(a){var e;return zk(a)&&((e=a[Jk])!==void 0?!!e:Kk(a)==="RegExp")}});var Yg=b((k_,Wg)=>{"use strict";var Zk=mt();Wg.exports=function(){var a=Zk(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 Xg=b((R_,Kg)=>{"use strict";var eR=Ue(),tR=at(),iR=Tr(),rR=Yg(),zg=RegExp.prototype;Kg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in zg)&&!tR(a,"flags")&&iR(zg,a)?eR(rR,a):e}});var Zg=b(($_,Jg)=>{"use strict";var zu=ye(),aR=Di(),sR=Math.floor,Wu=zu("".charAt),nR=zu("".replace),Yu=zu("".slice),oR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,uR=/\$([$&'`]|\d{1,2})/g;Jg.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=uR;return r!==void 0&&(r=aR(r),u=oR),nR(s,u,function(l,c){var d;switch(Wu(c,0)){case"$":return"$";case"&":return a;case"`":return Yu(e,0,t);case"'":return Yu(e,n);case"<":d=r[Yu(c,1,-1)];break;default:var m=+c;if(m===0)return l;if(m>o){var h=sR(m/10);return h===0?l:h<=o?i[h-1]===void 0?Wu(c,1):i[h-1]+Wu(c,1):l}d=i[m-1]}return d===void 0?"":d})}});var iv=b(()=>{"use strict";var lR=ve(),cR=Ue(),Xu=ye(),ev=qt(),dR=pe(),pR=Li(),hR=Gg(),rr=Jr(),mR=Er(),fR=Xg(),bR=Zg(),gR=Pe(),vR=rt(),SR=gR("replace"),yR=TypeError,Ku=Xu("".indexOf),TR=Xu("".replace),tv=Xu("".slice),IR=Math.max;lR({target:"String",proto:!0},{replaceAll:function(e,t){var i=ev(this),r,s,n,o,u,l,c,d,m,h,f=0,g="";if(!pR(e)){if(r=hR(e),r&&(s=rr(ev(fR(e))),!~Ku(s,"g")))throw new yR("`.replaceAll` does not allow non-global regexes");if(n=mR(e,SR),n)return cR(n,e,i,t);if(vR&&r)return TR(rr(i),e,t)}for(o=rr(i),u=rr(e),l=dR(t),l||(t=rr(t)),c=u.length,d=IR(1,c),m=Ku(o,u);m!==-1;)h=l?rr(t(u,m,o)):bR(u,o,m,[],void 0,t),g+=tv(o,f,m)+h,f=m+c,m=m+d>o.length?-1:Ku(o,u,m+d);return f<o.length&&(g+=tv(o,f)),g}})});var av=b((D_,rv)=>{"use strict";Hg();jg();iv();var ER=Ut();rv.exports=ER("String","replaceAll")});var nv=b((C_,sv)=>{"use strict";var xR=av();sv.exports=xR});var uv=b((V_,ov)=>{"use strict";var PR=nv();ov.exports=PR});var cv=b((O_,lv)=>{"use strict";var wR=Ar(),AR=Jr(),kR=qt(),RR=RangeError;lv.exports=function(e){var t=AR(kR(this)),i="",r=wR(e);if(r<0||r===1/0)throw new RR("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var fv=b((B_,mv)=>{"use strict";var hv=ye(),$R=ro(),dv=Jr(),LR=cv(),MR=qt(),DR=hv(LR),CR=hv("".slice),VR=Math.ceil,pv=function(a){return function(e,t,i){var r=dv(MR(e)),s=$R(t),n=r.length,o=i===void 0?" ":dv(i),u,l;return s<=n||o===""?r:(u=s-n,l=DR(o,VR(u/o.length)),l.length>u&&(l=CR(l,0,u)),a?r+l:l+r)}};mv.exports={start:pv(!1),end:pv(!0)}});var gv=b((__,bv)=>{"use strict";var OR=li();bv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(OR)});var vv=b(()=>{"use strict";var BR=ve(),_R=fv().start,NR=gv();BR({target:"String",proto:!0,forced:NR},{padStart:function(e){return _R(this,e,arguments.length>1?arguments[1]:void 0)}})});var yv=b((q_,Sv)=>{"use strict";vv();var FR=Ut();Sv.exports=FR("String","padStart")});var Iv=b((U_,Tv)=>{"use strict";var qR=yv();Tv.exports=qR});var xv=b((H_,Ev)=>{"use strict";var UR=Iv();Ev.exports=UR});var u$={};MS(u$,{ChromecastState:()=>br,HttpConnectionType:()=>rs,Observable:()=>St.Observable,PlaybackState:()=>Ce,Player:()=>Ha,PredefinedQualityLimits:()=>gr,SDK_VERSION:()=>o$,Subject:()=>St.Subject,Subscription:()=>St.Subscription,Surface:()=>as,VERSION:()=>An,ValueSubject:()=>St.ValueSubject,VideoFormat:()=>pt,VideoQuality:()=>St.VideoQuality,clientChecker:()=>K,isMobile:()=>Xi});module.exports=DS(u$);var An="2.0.131-dev.ba1a65a9.0";var Ce=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ce||{}),pt=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(pt||{});var br=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(br||{}),rs=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(rs||{});var as=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(as||{}),gr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(gr||{});var yS=j(Ye(),1);var H=require("@vkontakte/videoplayer-shared/es2018");var ep=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 ls=class{constructor(e){this.connection$=new H.ValueSubject(void 0);this.castState$=new H.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new H.Subject;this.realCastState$=new H.ValueSubject("NOT_AVAILABLE");this.subscription=new H.Subscription;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,H.isNonNullable)((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||ep("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:H.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,H.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,H.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,H.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,H.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,H.assertNever)(r.sessionState)}})).add((0,H.merge)((0,H.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,H.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,H.map)(r=>r.castState)),(0,H.observableFrom)([i.getCastState()])).pipe((0,H.filterChanged)(),(0,H.map)(tI),(0,H.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=(0,H.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();(0,H.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,H.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,H.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:H.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},tI=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,H.assertNever)(a)}};var Sl=j(Ye(),1),oS=j(Fi(),1),uS=j(Mo(),1);var Jf=j(Bs(),1);var vu=require("@vkontakte/videoplayer-shared/es2018");var we=(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,vu.assertNever)(t)}return a},_s=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,vu.assertNever)(e)}};var R=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var ft=require("@vkontakte/videoplayer-shared/es2018"),Q=class{constructor(e){this.transitionStarted$=new ft.Subject;this.transitionEnded$=new ft.Subject;this.transitionUpdated$=new ft.Subject;this.forceChanged$=new ft.Subject;this.stateChangeStarted$=(0,ft.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,ft.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,ft.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var zf=require("@vkontakte/videoplayer-shared/es2018"),Kf=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,zf.assertNever)(a)}};var M=require("@vkontakte/videoplayer-shared/es2018");var lA=5,cA=5,dA=500,Xf=7e3,qr=class{constructor(e){this.subscription=new M.Subscription;this.loadMediaTimeoutSubscription=new M.Subscription;this.videoState=new Q("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,M.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,M.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,M.assertNever)(e)}break}default:(0,M.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(Kf(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 M.Subscription;this.subscription.add(e),this.subscription.add((0,M.merge)(this.videoState.stateChangeStarted$.pipe((0,M.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,M.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 M.Subject;e.add(r.pipe((0,M.debounce)(dA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,M.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)>lA)&&r.next(o),s=o})),e.add((0,M.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,M.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,M.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,M.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<cA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(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,M.assertNever)(n)}}),t((0,M.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,M.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,M.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,M.observableFrom)(["init"])).pipe((0,M.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"),R(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),R(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),R(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&R(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];(0,M.assertNonNullable)(c);let d=(0,M.getHighestQuality)(Object.keys(c));(0,M.assertNonNullable)(d);let m=c[d];(0,M.assertNonNullable)(m),i=m,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,M.assertNonNullable)(c),i=c.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];(0,M.assertNonNullable)(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,M.assertNonNullable)(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,M.assertNonNullable)(c),i=we(c.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:M.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,M.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,M.isNonNullable)(o)&&(n.metadata.title=o),(0,M.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add((0,M.timeout)(Xf).subscribe(()=>s(`timeout(${Xf})`)))});(0,Jf.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:M.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Vu=j(Ye(),1);var Iu=require("@vkontakte/videoplayer-shared/es2018");var Zf=require("@vkontakte/videoplayer-shared/es2018"),eb=a=>{try{a.pause(),a.playbackRate=0,(0,Zf.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Ns=require("@vkontakte/videoplayer-shared/es2018"),Su=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)}},yu=window.WeakMap?new WeakMap:new Su,Tu=window.WeakMap?new WeakMap:new Map,pA=(a,e=20)=>{let t=0;return(0,Ns.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ve=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?(0,Iu.clearVideoElement)(i):(i=document.createElement("video"),a.appendChild(i)),yu.set(i,r);let s=new Ns.Subscription;return s.add(pA(i,e)),Tu.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},Oe=a=>{let e=Tu.get(a);e==null||e.unsubscribe(),Tu.delete(a);let t=yu.get(a);yu.delete(a),t?(0,Iu.clearVideoElement)(a):eb(a)};var Eu=j(Ki(),1),D=require("@vkontakte/videoplayer-shared/es2018");var jt=require("@vkontakte/videoplayer-shared/es2018"),Fs=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,jt.isNullable)(r),l=new jt.Subscription;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},bt=(a,e,t)=>Fs(e,()=>a.loop,i=>{(0,jt.isNonNullable)(i)&&(a.loop=i)},{onError:t}),Be=(a,e,t,i)=>Fs(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,jt.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),ze=(a,e,t,i)=>Fs(e,()=>a.playbackRate,r=>{(0,jt.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Qt=Fs;var vA=a=>["__",a.language,a.label].join("|"),SA=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},xu=class a{constructor(e){this.available$=new D.Subject;this.current$=new D.ValueSubject(void 0);this.error$=new D.Subject;this.subscription=new D.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:D.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(Qt(t.internalTextTracks,()=>(0,Eu.default)(this.internalTracks),s=>{(0,D.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,D.isNonNullable)(s)&&(0,D.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,D.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Qt(t.externalTextTracks,()=>(0,Eu.default)(this.externalTracks),s=>{(0,D.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,D.isNonNullable)(s)&&(0,D.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,D.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Qt(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(Qt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,D.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,D.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,D.merge)((0,D.fromEvent)(e,"addtrack"),(0,D.fromEvent)(e,"removetrack"),(0,D.observableFrom)(["init"])).pipe((0,D.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,D.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,D.merge)((0,D.fromEvent)(e,"change"),(0,D.observableFrom)(["init"])).pipe((0,D.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,D.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,D.filterChanged)()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add((0,D.fromEvent)(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,m,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((m=(d=o.target)==null?void 0:d.cues)!=null?m:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,D.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,D.isNonNullable)(t.align)&&(r.align=t.align),(0,D.isNonNullable)(t.position)&&(r.position=t.position),(0,D.isNonNullable)(t.size)&&(r.size=t.size),(0,D.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,D.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:i}=e,r=e.id?e.id:vA(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==null?void 0:d.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,D.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,D.isNullable)(e)||!SA(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,D.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,D.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ke=xu;var bi=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 ob=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Pu=a=>{let e=ob(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ub=a=>{let e=ob(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var A=require("@vkontakte/videoplayer-shared/es2018");var yA=3,lb=(a,e,t=yA)=>{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 qs=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}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,l=/edg/i.test(e)?"Edge":void 0;this._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var cb=j(Ye(),1);var Xi=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Us=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,cb.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||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.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Xi()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}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(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Hs=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}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(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var nt=()=>window.ManagedMediaSource||window.MediaSource,js=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},db=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},pb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var TA=document.createElement("video"),IA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',EA='video/mp4; codecs="hev1.1.6.L93.B0"',hb='video/webm; codecs="vp09.00.10.08"',mb='video/webm; codecs="av01.0.00M.08"',xA='audio/mp4; codecs="mp4a.40.2"',PA='audio/webm; codecs="opus"',fb,wA=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:mb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:hb}})]);fb={DASH_WEBM_AV1:e,DASH_WEBM:t}};wA().catch(a=>{console.log(TA),console.error(a)});var Qs=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 fb}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,o,u,l,c,d,m,h,f,g,S,y,E,x,w;this._video=document.createElement("video");try{this._protocols={mms:js(),mse:db(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let P=!!((c=(l=nt())==null?void 0:l.isTypeSupported)!=null&&c.call(l,IA)),V=!!((m=(d=nt())==null?void 0:d.isTypeSupported)!=null&&m.call(d,EA)),J=!!((f=(h=nt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,xA));this._codecs={h264:P,h265:V,vp9:!!((S=(g=nt())==null?void 0:g.isTypeSupported)!=null&&S.call(g,hb)),av1:!!((E=(y=nt())==null?void 0:y.isTypeSupported)!=null&&E.call(y,mb)),aac:J,opus:!!((w=(x=nt())==null?void 0:x.isTypeSupported)!=null&&w.call(x,PA)),mpeg:(P||V)&&J},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(P){console.error(P)}this.destroyVideoElement()}destroyVideoElement(){var t;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);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var bb="audio/mpeg",Gs=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,bb))},this._codecs={mp3:!!((r=(i=nt())==null?void 0:i.isTypeSupported)!=null&&r.call(i,bb))}}catch(s){console.error(s)}this.destroyAudioElement()}destroyAudioElement(){var t;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);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};var gb=require("@vkontakte/videoplayer-shared/es2018"),wu=class{constructor(){this.isInited$=new gb.ValueSubject(!1);this._displayChecker=new Hs,this._deviceChecker=new Us(this._displayChecker),this._browserChecker=new qs,this._videoChecker=new Qs(this._deviceChecker,this._browserChecker),this._audioChecker=new Gs,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(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},K=new wu;var _e=a=>{let e=$=>(0,A.fromEvent)(a,$).pipe((0,A.mapTo)(void 0)),t=new A.Subscription,i=()=>t.unsubscribe(),s=(0,A.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map($=>(0,A.fromEvent)(a,$))).pipe((0,A.map)($=>$.type==="ended"?a.readyState<2:a.readyState<3),(0,A.filterChanged)()),n=(0,A.merge)((0,A.fromEvent)(a,"progress"),(0,A.fromEvent)(a,"timeupdate")).pipe((0,A.map)(()=>lb(a.buffered,a.currentTime))),o=K.browser.isSafari?(0,A.combine)({play:e("play").pipe((0,A.once)()),playing:e("playing")}).pipe((0,A.mapTo)(void 0)):e("playing"),u=(0,A.fromEvent)(a,"volumechange").pipe((0,A.map)(()=>({muted:a.muted,volume:a.volume}))),l=(0,A.fromEvent)(a,"ratechange").pipe((0,A.map)(()=>a.playbackRate)),c=(0,A.fromEvent)(a,"error").pipe((0,A.filter)(()=>!!(a.error||a.played.length)),(0,A.map)(()=>{var Z;let $=a.error;return{id:$?`MediaError#${$.code}`:"HtmlVideoError",category:A.ErrorCategory.VIDEO_PIPELINE,message:$?$.message:"Error event from HTML video element",thrown:(Z=a.error)!=null?Z:void 0}})),d=(0,A.fromEvent)(a,"timeupdate").pipe((0,A.map)(()=>a.currentTime)),m=new A.Subject,h=.3,f;t.add(d.subscribe($=>{a.loop&&(0,A.isNonNullable)(f)&&(0,A.isNonNullable)($)&&f>=a.duration-h&&$<=h&&m.next(f),f=$}));let g=e("pause").pipe((0,A.filter)(()=>!a.error&&f!==a.duration)),S=(0,A.fromEvent)(a,"enterpictureinpicture"),y=(0,A.fromEvent)(a,"leavepictureinpicture"),E=new A.ValueSubject(ub(a));t.add(S.subscribe(()=>E.next(!0))),t.add(y.subscribe(()=>E.next(!1)));let x=new A.ValueSubject(Pu(a)),w=(0,A.fromEvent)(a,"fullscreenchange");t.add(w.pipe((0,A.map)(()=>Pu(a))).subscribe(x));let P=.1,V=1e3,J=(0,A.fromEvent)(a,"timeupdate").pipe((0,A.filter)($=>a.duration-a.currentTime<P)),W=(0,A.merge)(J.pipe((0,A.filter)($=>!a.loop)),(0,A.fromEvent)(a,"ended")).pipe((0,A.throttle)(V),(0,A.mapTo)(void 0)),X=J.pipe((0,A.filter)($=>a.loop));return{playing$:o,pause$:g,canplay$:e("canplay"),ended$:W,looped$:m,loopExpected$:X,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:(0,A.fromEvent)(a,"durationchange").pipe((0,A.map)(()=>a.duration)),isBuffering$:s,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:E,inFullscreen$:x,enterPip$:S,leavePip$:y,destroy:i}};var wt=require("@vkontakte/videoplayer-shared/es2018"),Gt=a=>{switch(a){case"mobile":return wt.VideoQuality.Q_144P;case"lowest":return wt.VideoQuality.Q_240P;case"low":return wt.VideoQuality.Q_360P;case"sd":case"medium":return wt.VideoQuality.Q_480P;case"hd":case"high":return wt.VideoQuality.Q_720P;case"fullhd":case"full":return wt.VideoQuality.Q_1080P;case"quadhd":case"quad":return wt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return wt.VideoQuality.Q_2160P}};var Yt=j(Wt(),1),Rb=j(Ye(),1),Ws=j(Fi(),1),N=require("@vkontakte/videoplayer-shared/es2018");var Au=!1,At={},xb=a=>{Au=a},Pb=()=>{At={}},wb=a=>{a(At)},Ur=(a,e)=>{var t;Au&&(At.meta=(t=At.meta)!=null?t:{},At.meta[a]=e)},$e=class{constructor(e){this.name=e}next(e){var i,r;if(!Au)return;At.series=(i=At.series)!=null?i:{};let t=(r=At.series[this.name])!=null?r:[];t.push([Date.now(),e]),At.series[this.name]=t}};var Se=require("@vkontakte/videoplayer-shared/es2018");function ku({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Ru({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&ku({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Hr({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return(0,Se.isNullable)(a)||(0,Se.isNonNullable)(a.min)&&(0,Se.isNonNullable)(a.max)&&(0,Se.isLower)(a.max,a.min)||(0,Se.isNonNullable)(a.min)&&e&&(0,Se.isHigher)(a.min,e)||(0,Se.isNonNullable)(a.max)&&t&&(0,Se.isLower)(a.max,t)}function Ab({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Hr({limits:{max:a!=null&&a.max?(0,Se.videoHeightToQuality)(a.max):void 0,min:a!=null&&a.min?(0,Se.videoHeightToQuality)(a.min):void 0},highestAvailableQuality:e?(0,Se.videoHeightToQuality)(e):void 0,lowestAvailableQuality:t?(0,Se.videoHeightToQuality)(t):void 0})}var VA=new $e("best_bitrate"),$b=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var $u=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),jr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,N.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Lb='Assertion "ABR Tracks is empty array" failed',Ys=(a,e,t,i)=>{var u;let r=[...e].sort($u(1)),s=[...t].sort($u(1)),n=s.filter(l=>(0,N.isNonNullable)(l.bitrate)&&(0,N.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Yt.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Yt.default)(s,-1);return o&&(0,Rb.default)(n,o)?o:n.length?(0,Yt.default)(n,-1):(0,Yt.default)(s,0)},kb=a=>"quality"in a,Mb=(a,e,t,i)=>{var n;let r=(0,N.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,N.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,N.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=kb(o)?"video":"audio",l=kb(o)?o.quality:o.bitrate;return e({message:`
6
+ "use strict";var AT=Object.create;var ao=Object.defineProperty;var PT=Object.getOwnPropertyDescriptor;var kT=Object.getOwnPropertyNames;var RT=Object.getPrototypeOf,LT=Object.prototype.hasOwnProperty;var g=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),MT=(s,e)=>{for(var t in e)ao(s,t,{get:e[t],enumerable:!0})},Jd=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of kT(e))!LT.call(s,r)&&r!==t&&ao(s,r,{get:()=>e[r],enumerable:!(i=PT(e,r))||i.enumerable});return s};var Y=(s,e,t)=>(t=s!=null?AT(RT(s)):{},Jd(e||!s||!s.__esModule?ao(t,"default",{value:s,enumerable:!0}):t,s)),$T=s=>Jd(ao({},"__esModule",{value:!0}),s);var Ce=g((Xu,Zd)=>{"use strict";var ea=function(s){return s&&s.Math===Math&&s};Zd.exports=ea(typeof globalThis=="object"&&globalThis)||ea(typeof window=="object"&&window)||ea(typeof self=="object"&&self)||ea(typeof global=="object"&&global)||ea(typeof Xu=="object"&&Xu)||function(){return this}()||Function("return this")()});var Je=g((V$,ep)=>{"use strict";ep.exports=function(s){try{return!!s()}catch(e){return!0}}});var ta=g((O$,tp)=>{"use strict";var BT=Je();tp.exports=!BT(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Ju=g((_$,ap)=>{"use strict";var DT=ta(),sp=Function.prototype,ip=sp.apply,rp=sp.call;ap.exports=typeof Reflect=="object"&&Reflect.apply||(DT?rp.bind(ip):function(){return rp.apply(ip,arguments)})});var Ye=g((F$,up)=>{"use strict";var np=ta(),op=Function.prototype,Zu=op.call,CT=np&&op.bind.bind(Zu,Zu);up.exports=np?CT:function(s){return function(){return Zu.apply(s,arguments)}}});var ur=g((N$,cp)=>{"use strict";var lp=Ye(),VT=lp({}.toString),OT=lp("".slice);cp.exports=function(s){return OT(VT(s),8,-1)}});var el=g((U$,dp)=>{"use strict";var _T=ur(),FT=Ye();dp.exports=function(s){if(_T(s)==="Function")return FT(s)}});var Be=g((q$,pp)=>{"use strict";var tl=typeof document=="object"&&document.all;pp.exports=typeof tl=="undefined"&&tl!==void 0?function(s){return typeof s=="function"||s===tl}:function(s){return typeof s=="function"}});var Lt=g((j$,hp)=>{"use strict";var NT=Je();hp.exports=!NT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Mt=g((H$,fp)=>{"use strict";var UT=ta(),uo=Function.prototype.call;fp.exports=UT?uo.bind(uo):function(){return uo.apply(uo,arguments)}});var il=g(gp=>{"use strict";var mp={}.propertyIsEnumerable,bp=Object.getOwnPropertyDescriptor,qT=bp&&!mp.call({1:2},1);gp.f=qT?function(e){var t=bp(this,e);return!!t&&t.enumerable}:mp});var ia=g((z$,Sp)=>{"use strict";Sp.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var yp=g((Q$,vp)=>{"use strict";var jT=Ye(),HT=Je(),GT=ur(),rl=Object,zT=jT("".split);vp.exports=HT(function(){return!rl("z").propertyIsEnumerable(0)})?function(s){return GT(s)==="String"?zT(s,""):rl(s)}:rl});var Lr=g((W$,Tp)=>{"use strict";Tp.exports=function(s){return s==null}});var Hi=g((Y$,Ip)=>{"use strict";var QT=Lr(),WT=TypeError;Ip.exports=function(s){if(QT(s))throw new WT("Can't call method on "+s);return s}});var lr=g((K$,xp)=>{"use strict";var YT=yp(),KT=Hi();xp.exports=function(s){return YT(KT(s))}});var $t=g((X$,Ep)=>{"use strict";var XT=Be();Ep.exports=function(s){return typeof s=="object"?s!==null:XT(s)}});var Mr=g((J$,wp)=>{"use strict";wp.exports={}});var ki=g((Z$,Pp)=>{"use strict";var sl=Mr(),al=Ce(),JT=Be(),Ap=function(s){return JT(s)?s:void 0};Pp.exports=function(s,e){return arguments.length<2?Ap(sl[s])||Ap(al[s]):sl[s]&&sl[s][e]||al[s]&&al[s][e]}});var ra=g((eB,kp)=>{"use strict";var ZT=Ye();kp.exports=ZT({}.isPrototypeOf)});var cr=g((tB,Mp)=>{"use strict";var eI=Ce(),Rp=eI.navigator,Lp=Rp&&Rp.userAgent;Mp.exports=Lp?String(Lp):""});var ol=g((iB,Op)=>{"use strict";var Vp=Ce(),nl=cr(),$p=Vp.process,Bp=Vp.Deno,Dp=$p&&$p.versions||Bp&&Bp.version,Cp=Dp&&Dp.v8,Yt,lo;Cp&&(Yt=Cp.split("."),lo=Yt[0]>0&&Yt[0]<4?1:+(Yt[0]+Yt[1]));!lo&&nl&&(Yt=nl.match(/Edge\/(\d+)/),(!Yt||Yt[1]>=74)&&(Yt=nl.match(/Chrome\/(\d+)/),Yt&&(lo=+Yt[1])));Op.exports=lo});var ul=g((rB,Fp)=>{"use strict";var _p=ol(),tI=Je(),iI=Ce(),rI=iI.String;Fp.exports=!!Object.getOwnPropertySymbols&&!tI(function(){var s=Symbol("symbol detection");return!rI(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&_p&&_p<41})});var ll=g((sB,Np)=>{"use strict";var sI=ul();Np.exports=sI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var cl=g((aB,Up)=>{"use strict";var aI=ki(),nI=Be(),oI=ra(),uI=ll(),lI=Object;Up.exports=uI?function(s){return typeof s=="symbol"}:function(s){var e=aI("Symbol");return nI(e)&&oI(e.prototype,lI(s))}});var sa=g((nB,qp)=>{"use strict";var cI=String;qp.exports=function(s){try{return cI(s)}catch(e){return"Object"}}});var ai=g((oB,jp)=>{"use strict";var dI=Be(),pI=sa(),hI=TypeError;jp.exports=function(s){if(dI(s))return s;throw new hI(pI(s)+" is not a function")}});var aa=g((uB,Hp)=>{"use strict";var fI=ai(),mI=Lr();Hp.exports=function(s,e){var t=s[e];return mI(t)?void 0:fI(t)}});var zp=g((lB,Gp)=>{"use strict";var dl=Mt(),pl=Be(),hl=$t(),bI=TypeError;Gp.exports=function(s,e){var t,i;if(e==="string"&&pl(t=s.toString)&&!hl(i=dl(t,s))||pl(t=s.valueOf)&&!hl(i=dl(t,s))||e!=="string"&&pl(t=s.toString)&&!hl(i=dl(t,s)))return i;throw new bI("Can't convert object to primitive value")}});var Kt=g((cB,Qp)=>{"use strict";Qp.exports=!0});var Kp=g((dB,Yp)=>{"use strict";var Wp=Ce(),gI=Object.defineProperty;Yp.exports=function(s,e){try{gI(Wp,s,{value:e,configurable:!0,writable:!0})}catch(t){Wp[s]=e}return e}});var na=g((pB,Zp)=>{"use strict";var SI=Kt(),vI=Ce(),yI=Kp(),Xp="__core-js_shared__",Jp=Zp.exports=vI[Xp]||yI(Xp,{});(Jp.versions||(Jp.versions=[])).push({version:"3.38.0",mode:SI?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var fl=g((hB,th)=>{"use strict";var eh=na();th.exports=function(s,e){return eh[s]||(eh[s]=e||{})}});var $r=g((fB,ih)=>{"use strict";var TI=Hi(),II=Object;ih.exports=function(s){return II(TI(s))}});var Xt=g((mB,rh)=>{"use strict";var xI=Ye(),EI=$r(),wI=xI({}.hasOwnProperty);rh.exports=Object.hasOwn||function(e,t){return wI(EI(e),t)}});var ml=g((bB,sh)=>{"use strict";var AI=Ye(),PI=0,kI=Math.random(),RI=AI(1 .toString);sh.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+RI(++PI+kI,36)}});var Ze=g((gB,nh)=>{"use strict";var LI=Ce(),MI=fl(),ah=Xt(),$I=ml(),BI=ul(),DI=ll(),Br=LI.Symbol,bl=MI("wks"),CI=DI?Br.for||Br:Br&&Br.withoutSetter||$I;nh.exports=function(s){return ah(bl,s)||(bl[s]=BI&&ah(Br,s)?Br[s]:CI("Symbol."+s)),bl[s]}});var ch=g((SB,lh)=>{"use strict";var VI=Mt(),oh=$t(),uh=cl(),OI=aa(),_I=zp(),FI=Ze(),NI=TypeError,UI=FI("toPrimitive");lh.exports=function(s,e){if(!oh(s)||uh(s))return s;var t=OI(s,UI),i;if(t){if(e===void 0&&(e="default"),i=VI(t,s,e),!oh(i)||uh(i))return i;throw new NI("Can't convert object to primitive value")}return e===void 0&&(e="number"),_I(s,e)}});var gl=g((vB,dh)=>{"use strict";var qI=ch(),jI=cl();dh.exports=function(s){var e=qI(s,"string");return jI(e)?e:e+""}});var co=g((yB,hh)=>{"use strict";var HI=Ce(),ph=$t(),Sl=HI.document,GI=ph(Sl)&&ph(Sl.createElement);hh.exports=function(s){return GI?Sl.createElement(s):{}}});var vl=g((TB,fh)=>{"use strict";var zI=Lt(),QI=Je(),WI=co();fh.exports=!zI&&!QI(function(){return Object.defineProperty(WI("div"),"a",{get:function(){return 7}}).a!==7})});var gh=g(bh=>{"use strict";var YI=Lt(),KI=Mt(),XI=il(),JI=ia(),ZI=lr(),ex=gl(),tx=Xt(),ix=vl(),mh=Object.getOwnPropertyDescriptor;bh.f=YI?mh:function(e,t){if(e=ZI(e),t=ex(t),ix)try{return mh(e,t)}catch(i){}if(tx(e,t))return JI(!KI(XI.f,e,t),e[t])}});var yl=g((xB,Sh)=>{"use strict";var rx=Je(),sx=Be(),ax=/#|\.prototype\./,oa=function(s,e){var t=ox[nx(s)];return t===lx?!0:t===ux?!1:sx(e)?rx(e):!!e},nx=oa.normalize=function(s){return String(s).replace(ax,".").toLowerCase()},ox=oa.data={},ux=oa.NATIVE="N",lx=oa.POLYFILL="P";Sh.exports=oa});var Dr=g((EB,yh)=>{"use strict";var vh=el(),cx=ai(),dx=ta(),px=vh(vh.bind);yh.exports=function(s,e){return cx(s),e===void 0?s:dx?px(s,e):function(){return s.apply(e,arguments)}}});var Tl=g((wB,Th)=>{"use strict";var hx=Lt(),fx=Je();Th.exports=hx&&fx(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ni=g((AB,Ih)=>{"use strict";var mx=$t(),bx=String,gx=TypeError;Ih.exports=function(s){if(mx(s))return s;throw new gx(bx(s)+" is not an object")}});var dr=g(Eh=>{"use strict";var Sx=Lt(),vx=vl(),yx=Tl(),po=ni(),xh=gl(),Tx=TypeError,Il=Object.defineProperty,Ix=Object.getOwnPropertyDescriptor,xl="enumerable",El="configurable",wl="writable";Eh.f=Sx?yx?function(e,t,i){if(po(e),t=xh(t),po(i),typeof e=="function"&&t==="prototype"&&"value"in i&&wl in i&&!i[wl]){var r=Ix(e,t);r&&r[wl]&&(e[t]=i.value,i={configurable:El in i?i[El]:r[El],enumerable:xl in i?i[xl]:r[xl],writable:!1})}return Il(e,t,i)}:Il:function(e,t,i){if(po(e),t=xh(t),po(i),vx)try{return Il(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Tx("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Cr=g((kB,wh)=>{"use strict";var xx=Lt(),Ex=dr(),wx=ia();wh.exports=xx?function(s,e,t){return Ex.f(s,e,wx(1,t))}:function(s,e,t){return s[e]=t,s}});var Ne=g((RB,Ph)=>{"use strict";var ua=Ce(),Ax=Ju(),Px=el(),kx=Be(),Rx=gh().f,Lx=yl(),Vr=Mr(),Mx=Dr(),Or=Cr(),Ah=Xt();na();var $x=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Ax(s,this,arguments)};return e.prototype=s.prototype,e};Ph.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?ua:r?ua[t]:ua[t]&&ua[t].prototype,o=i?Vr:Vr[t]||Or(Vr,t,{})[t],u=o.prototype,l,d,c,p,h,f,b,S,v;for(p in e)l=Lx(i?p:t+(r?".":"#")+p,s.forced),d=!l&&n&&Ah(n,p),f=o[p],d&&(s.dontCallGetSet?(v=Rx(n,p),b=v&&v.value):b=n[p]),h=d&&b?b:e[p],!(!l&&!a&&typeof f==typeof h)&&(s.bind&&d?S=Mx(h,ua):s.wrap&&d?S=$x(h):a&&kx(h)?S=Px(h):S=h,(s.sham||h&&h.sham||f&&f.sham)&&Or(S,"sham",!0),Or(o,p,S),a&&(c=t+"Prototype",Ah(Vr,c)||Or(Vr,c,{}),Or(Vr[c],p,h),s.real&&u&&(l||!u[p])&&Or(u,p,h)))}});var Rh=g((LB,kh)=>{"use strict";var Bx=Math.ceil,Dx=Math.floor;kh.exports=Math.trunc||function(e){var t=+e;return(t>0?Dx:Bx)(t)}});var la=g((MB,Lh)=>{"use strict";var Cx=Rh();Lh.exports=function(s){var e=+s;return e!==e||e===0?0:Cx(e)}});var $h=g(($B,Mh)=>{"use strict";var Vx=la(),Ox=Math.max,_x=Math.min;Mh.exports=function(s,e){var t=Vx(s);return t<0?Ox(t+e,0):_x(t,e)}});var Al=g((BB,Bh)=>{"use strict";var Fx=la(),Nx=Math.min;Bh.exports=function(s){var e=Fx(s);return e>0?Nx(e,9007199254740991):0}});var _r=g((DB,Dh)=>{"use strict";var Ux=Al();Dh.exports=function(s){return Ux(s.length)}});var Pl=g((CB,Vh)=>{"use strict";var qx=lr(),jx=$h(),Hx=_r(),Ch=function(s){return function(e,t,i){var r=qx(e),a=Hx(r);if(a===0)return!s&&-1;var n=jx(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};Vh.exports={includes:Ch(!0),indexOf:Ch(!1)}});var ca=g((VB,Oh)=>{"use strict";Oh.exports=function(){}});var _h=g(()=>{"use strict";var Gx=Ne(),zx=Pl().includes,Qx=Je(),Wx=ca(),Yx=Qx(function(){return!Array(1).includes()});Gx({target:"Array",proto:!0,forced:Yx},{includes:function(e){return zx(this,e,arguments.length>1?arguments[1]:void 0)}});Wx("includes")});var Gi=g((FB,Fh)=>{"use strict";var Kx=ki();Fh.exports=Kx});var Uh=g((NB,Nh)=>{"use strict";_h();var Xx=Gi();Nh.exports=Xx("Array","includes")});var jh=g((UB,qh)=>{"use strict";var Jx=Uh();qh.exports=Jx});var _t=g((qB,Hh)=>{"use strict";var Zx=jh();Hh.exports=Zx});var fo=g((ZB,Qh)=>{"use strict";var tE=fl(),iE=ml(),zh=tE("keys");Qh.exports=function(s){return zh[s]||(zh[s]=iE(s))}});var Yh=g((eD,Wh)=>{"use strict";var rE=Je();Wh.exports=!rE(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var mo=g((tD,Xh)=>{"use strict";var sE=Xt(),aE=Be(),nE=$r(),oE=fo(),uE=Yh(),Kh=oE("IE_PROTO"),kl=Object,lE=kl.prototype;Xh.exports=uE?kl.getPrototypeOf:function(s){var e=nE(s);if(sE(e,Kh))return e[Kh];var t=e.constructor;return aE(t)&&e instanceof t?t.prototype:e instanceof kl?lE:null}});var bo=g((iD,Jh)=>{"use strict";Jh.exports={}});var tf=g((rD,ef)=>{"use strict";var cE=Ye(),Rl=Xt(),dE=lr(),pE=Pl().indexOf,hE=bo(),Zh=cE([].push);ef.exports=function(s,e){var t=dE(s),i=0,r=[],a;for(a in t)!Rl(hE,a)&&Rl(t,a)&&Zh(r,a);for(;e.length>i;)Rl(t,a=e[i++])&&(~pE(r,a)||Zh(r,a));return r}});var Ll=g((sD,rf)=>{"use strict";rf.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Ml=g((aD,sf)=>{"use strict";var fE=tf(),mE=Ll();sf.exports=Object.keys||function(e){return fE(e,mE)}});var $l=g((nD,lf)=>{"use strict";var nf=Lt(),bE=Je(),of=Ye(),gE=mo(),SE=Ml(),vE=lr(),yE=il().f,uf=of(yE),TE=of([].push),IE=nf&&bE(function(){var s=Object.create(null);return s[2]=2,!uf(s,2)}),af=function(s){return function(e){for(var t=vE(e),i=SE(t),r=IE&&gE(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!nf||(r?u in t:uf(t,u)))&&TE(o,s?[u,t[u]]:t[u]);return o}};lf.exports={entries:af(!0),values:af(!1)}});var cf=g(()=>{"use strict";var xE=Ne(),EE=$l().entries;xE({target:"Object",stat:!0},{entries:function(e){return EE(e)}})});var pf=g((lD,df)=>{"use strict";cf();var wE=Mr();df.exports=wE.Object.entries});var ff=g((cD,hf)=>{"use strict";var AE=pf();hf.exports=AE});var pr=g((dD,mf)=>{"use strict";var PE=ff();mf.exports=PE});var hr=g((pD,bf)=>{"use strict";bf.exports={}});var vf=g((hD,Sf)=>{"use strict";var kE=Ce(),RE=Be(),gf=kE.WeakMap;Sf.exports=RE(gf)&&/native code/.test(String(gf))});var Vl=g((fD,If)=>{"use strict";var LE=vf(),Tf=Ce(),ME=$t(),$E=Cr(),Bl=Xt(),Dl=na(),BE=fo(),DE=bo(),yf="Object already initialized",Cl=Tf.TypeError,CE=Tf.WeakMap,go,da,So,VE=function(s){return So(s)?da(s):go(s,{})},OE=function(s){return function(e){var t;if(!ME(e)||(t=da(e)).type!==s)throw new Cl("Incompatible receiver, "+s+" required");return t}};LE||Dl.state?(Jt=Dl.state||(Dl.state=new CE),Jt.get=Jt.get,Jt.has=Jt.has,Jt.set=Jt.set,go=function(s,e){if(Jt.has(s))throw new Cl(yf);return e.facade=s,Jt.set(s,e),e},da=function(s){return Jt.get(s)||{}},So=function(s){return Jt.has(s)}):(fr=BE("state"),DE[fr]=!0,go=function(s,e){if(Bl(s,fr))throw new Cl(yf);return e.facade=s,$E(s,fr,e),e},da=function(s){return Bl(s,fr)?s[fr]:{}},So=function(s){return Bl(s,fr)});var Jt,fr;If.exports={set:go,get:da,has:So,enforce:VE,getterFor:OE}});var Fl=g((mD,Ef)=>{"use strict";var Ol=Lt(),_E=Xt(),xf=Function.prototype,FE=Ol&&Object.getOwnPropertyDescriptor,_l=_E(xf,"name"),NE=_l&&function(){}.name==="something",UE=_l&&(!Ol||Ol&&FE(xf,"name").configurable);Ef.exports={EXISTS:_l,PROPER:NE,CONFIGURABLE:UE}});var Af=g(wf=>{"use strict";var qE=Lt(),jE=Tl(),HE=dr(),GE=ni(),zE=lr(),QE=Ml();wf.f=qE&&!jE?Object.defineProperties:function(e,t){GE(e);for(var i=zE(t),r=QE(t),a=r.length,n=0,o;a>n;)HE.f(e,o=r[n++],i[o]);return e}});var Nl=g((gD,Pf)=>{"use strict";var WE=ki();Pf.exports=WE("document","documentElement")});var Hl=g((SD,Df)=>{"use strict";var YE=ni(),KE=Af(),kf=Ll(),XE=bo(),JE=Nl(),ZE=co(),ew=fo(),Rf=">",Lf="<",ql="prototype",jl="script",$f=ew("IE_PROTO"),Ul=function(){},Bf=function(s){return Lf+jl+Rf+s+Lf+"/"+jl+Rf},Mf=function(s){s.write(Bf("")),s.close();var e=s.parentWindow.Object;return s=null,e},tw=function(){var s=ZE("iframe"),e="java"+jl+":",t;return s.style.display="none",JE.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Bf("document.F=Object")),t.close(),t.F},vo,yo=function(){try{vo=new ActiveXObject("htmlfile")}catch(e){}yo=typeof document!="undefined"?document.domain&&vo?Mf(vo):tw():Mf(vo);for(var s=kf.length;s--;)delete yo[ql][kf[s]];return yo()};XE[$f]=!0;Df.exports=Object.create||function(e,t){var i;return e!==null?(Ul[ql]=YE(e),i=new Ul,Ul[ql]=null,i[$f]=e):i=yo(),t===void 0?i:KE.f(i,t)}});var Fr=g((vD,Cf)=>{"use strict";var iw=Cr();Cf.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:iw(s,e,t),s}});var Wl=g((yD,_f)=>{"use strict";var rw=Je(),sw=Be(),aw=$t(),nw=Hl(),Vf=mo(),ow=Fr(),uw=Ze(),lw=Kt(),Ql=uw("iterator"),Of=!1,Ri,Gl,zl;[].keys&&(zl=[].keys(),"next"in zl?(Gl=Vf(Vf(zl)),Gl!==Object.prototype&&(Ri=Gl)):Of=!0);var cw=!aw(Ri)||rw(function(){var s={};return Ri[Ql].call(s)!==s});cw?Ri={}:lw&&(Ri=nw(Ri));sw(Ri[Ql])||ow(Ri,Ql,function(){return this});_f.exports={IteratorPrototype:Ri,BUGGY_SAFARI_ITERATORS:Of}});var To=g((TD,Nf)=>{"use strict";var dw=Ze(),pw=dw("toStringTag"),Ff={};Ff[pw]="z";Nf.exports=String(Ff)==="[object z]"});var pa=g((ID,Uf)=>{"use strict";var hw=To(),fw=Be(),Io=ur(),mw=Ze(),bw=mw("toStringTag"),gw=Object,Sw=Io(function(){return arguments}())==="Arguments",vw=function(s,e){try{return s[e]}catch(t){}};Uf.exports=hw?Io:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=vw(e=gw(s),bw))=="string"?t:Sw?Io(e):(i=Io(e))==="Object"&&fw(e.callee)?"Arguments":i}});var jf=g((xD,qf)=>{"use strict";var yw=To(),Tw=pa();qf.exports=yw?{}.toString:function(){return"[object "+Tw(this)+"]"}});var ha=g((ED,Gf)=>{"use strict";var Iw=To(),xw=dr().f,Ew=Cr(),ww=Xt(),Aw=jf(),Pw=Ze(),Hf=Pw("toStringTag");Gf.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(ww(r,Hf)||xw(r,Hf,{configurable:!0,value:e}),i&&!Iw&&Ew(r,"toString",Aw))}});var Qf=g((wD,zf)=>{"use strict";var kw=Wl().IteratorPrototype,Rw=Hl(),Lw=ia(),Mw=ha(),$w=hr(),Bw=function(){return this};zf.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Rw(kw,{next:Lw(+!i,t)}),Mw(s,r,!1,!0),$w[r]=Bw,s}});var Yf=g((AD,Wf)=>{"use strict";var Dw=Ye(),Cw=ai();Wf.exports=function(s,e,t){try{return Dw(Cw(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Xf=g((PD,Kf)=>{"use strict";var Vw=$t();Kf.exports=function(s){return Vw(s)||s===null}});var Zf=g((kD,Jf)=>{"use strict";var Ow=Xf(),_w=String,Fw=TypeError;Jf.exports=function(s){if(Ow(s))return s;throw new Fw("Can't set "+_w(s)+" as a prototype")}});var Yl=g((RD,em)=>{"use strict";var Nw=Yf(),Uw=$t(),qw=Hi(),jw=Zf();em.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=Nw(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return qw(r),jw(a),Uw(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var dm=g((LD,cm)=>{"use strict";var Hw=Ne(),Gw=Mt(),xo=Kt(),um=Fl(),zw=Be(),Qw=Qf(),tm=mo(),im=Yl(),Ww=ha(),Yw=Cr(),Kl=Fr(),Kw=Ze(),rm=hr(),lm=Wl(),Xw=um.PROPER,Jw=um.CONFIGURABLE,sm=lm.IteratorPrototype,Eo=lm.BUGGY_SAFARI_ITERATORS,fa=Kw("iterator"),am="keys",ma="values",nm="entries",om=function(){return this};cm.exports=function(s,e,t,i,r,a,n){Qw(t,e,i);var o=function(v){if(v===r&&p)return p;if(!Eo&&v&&v in d)return d[v];switch(v){case am:return function(){return new t(this,v)};case ma:return function(){return new t(this,v)};case nm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[fa]||d["@@iterator"]||r&&d[r],p=!Eo&&c||o(r),h=e==="Array"&&d.entries||c,f,b,S;if(h&&(f=tm(h.call(new s)),f!==Object.prototype&&f.next&&(!xo&&tm(f)!==sm&&(im?im(f,sm):zw(f[fa])||Kl(f,fa,om)),Ww(f,u,!0,!0),xo&&(rm[u]=om))),Xw&&r===ma&&c&&c.name!==ma&&(!xo&&Jw?Yw(d,"name",ma):(l=!0,p=function(){return Gw(c,this)})),r)if(b={values:o(ma),keys:a?p:o(am),entries:o(nm)},n)for(S in b)(Eo||l||!(S in d))&&Kl(d,S,b[S]);else Hw({target:e,proto:!0,forced:Eo||l},b);return(!xo||n)&&d[fa]!==p&&Kl(d,fa,p,{name:r}),rm[e]=p,b}});var hm=g((MD,pm)=>{"use strict";pm.exports=function(s,e){return{value:s,done:e}}});var Jl=g(($D,Sm)=>{"use strict";var Zw=lr(),Xl=ca(),fm=hr(),bm=Vl(),eA=dr().f,tA=dm(),wo=hm(),iA=Kt(),rA=Lt(),gm="Array Iterator",sA=bm.set,aA=bm.getterFor(gm);Sm.exports=tA(Array,"Array",function(s,e){sA(this,{type:gm,target:Zw(s),index:0,kind:e})},function(){var s=aA(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,wo(void 0,!0);switch(s.kind){case"keys":return wo(t,!1);case"values":return wo(e[t],!1)}return wo([t,e[t]],!1)},"values");var mm=fm.Arguments=fm.Array;Xl("keys");Xl("values");Xl("entries");if(!iA&&rA&&mm.name!=="values")try{eA(mm,"name",{value:"values"})}catch(s){}});var ym=g((BD,vm)=>{"use strict";var nA=Ze(),oA=hr(),uA=nA("iterator"),lA=Array.prototype;vm.exports=function(s){return s!==void 0&&(oA.Array===s||lA[uA]===s)}});var Zl=g((DD,Im)=>{"use strict";var cA=pa(),Tm=aa(),dA=Lr(),pA=hr(),hA=Ze(),fA=hA("iterator");Im.exports=function(s){if(!dA(s))return Tm(s,fA)||Tm(s,"@@iterator")||pA[cA(s)]}});var Em=g((CD,xm)=>{"use strict";var mA=Mt(),bA=ai(),gA=ni(),SA=sa(),vA=Zl(),yA=TypeError;xm.exports=function(s,e){var t=arguments.length<2?vA(s):e;if(bA(t))return gA(mA(t,s));throw new yA(SA(s)+" is not iterable")}});var Pm=g((VD,Am)=>{"use strict";var TA=Mt(),wm=ni(),IA=aa();Am.exports=function(s,e,t){var i,r;wm(s);try{if(i=IA(s,"return"),!i){if(e==="throw")throw t;return t}i=TA(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return wm(i),t}});var Po=g((OD,Mm)=>{"use strict";var xA=Dr(),EA=Mt(),wA=ni(),AA=sa(),PA=ym(),kA=_r(),km=ra(),RA=Em(),LA=Zl(),Rm=Pm(),MA=TypeError,Ao=function(s,e){this.stopped=s,this.result=e},Lm=Ao.prototype;Mm.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=xA(e,i),l,d,c,p,h,f,b,S=function(y){return l&&Rm(l,"normal",y),new Ao(!0,y)},v=function(y){return r?(wA(y),o?u(y[0],y[1],S):u(y[0],y[1])):o?u(y,S):u(y)};if(a)l=s.iterator;else if(n)l=s;else{if(d=LA(s),!d)throw new MA(AA(s)+" is not iterable");if(PA(d)){for(c=0,p=kA(s);p>c;c++)if(h=v(s[c]),h&&km(Lm,h))return h;return new Ao(!1)}l=RA(s,d)}for(f=a?s.next:l.next;!(b=EA(f,l)).done;){try{h=v(b.value)}catch(y){Rm(l,"throw",y)}if(typeof h=="object"&&h&&km(Lm,h))return h}return new Ao(!1)}});var Bm=g((_D,$m)=>{"use strict";var $A=Lt(),BA=dr(),DA=ia();$m.exports=function(s,e,t){$A?BA.f(s,e,DA(0,t)):s[e]=t}});var Dm=g(()=>{"use strict";var CA=Ne(),VA=Po(),OA=Bm();CA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return VA(e,function(i,r){OA(t,i,r)},{AS_ENTRIES:!0}),t}})});var Vm=g((UD,Cm)=>{"use strict";Jl();Dm();var _A=Mr();Cm.exports=_A.Object.fromEntries});var _m=g((qD,Om)=>{"use strict";Om.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 Nm=g(()=>{"use strict";Jl();var FA=_m(),NA=Ce(),UA=ha(),Fm=hr();for(ko in FA)UA(NA[ko],ko),Fm[ko]=Fm.Array;var ko});var qm=g((GD,Um)=>{"use strict";var qA=Vm();Nm();Um.exports=qA});var ec=g((zD,jm)=>{"use strict";var jA=qm();jm.exports=jA});var Hm=g(()=>{"use strict"});var tc=g((YD,Gm)=>{"use strict";var ba=Ce(),HA=cr(),GA=ur(),Ro=function(s){return HA.slice(0,s.length)===s};Gm.exports=function(){return Ro("Bun/")?"BUN":Ro("Cloudflare-Workers")?"CLOUDFLARE":Ro("Deno/")?"DENO":Ro("Node.js/")?"NODE":ba.Bun&&typeof Bun.version=="string"?"BUN":ba.Deno&&typeof Deno.version=="object"?"DENO":GA(ba.process)==="process"?"NODE":ba.window&&ba.document?"BROWSER":"REST"}()});var Lo=g((KD,zm)=>{"use strict";var zA=tc();zm.exports=zA==="NODE"});var Wm=g((XD,Qm)=>{"use strict";var QA=dr();Qm.exports=function(s,e,t){return QA.f(s,e,t)}});var Xm=g((JD,Km)=>{"use strict";var WA=ki(),YA=Wm(),KA=Ze(),XA=Lt(),Ym=KA("species");Km.exports=function(s){var e=WA(s);XA&&e&&!e[Ym]&&YA(e,Ym,{configurable:!0,get:function(){return this}})}});var Zm=g((ZD,Jm)=>{"use strict";var JA=ra(),ZA=TypeError;Jm.exports=function(s,e){if(JA(e,s))return s;throw new ZA("Incorrect invocation")}});var rc=g((e0,eb)=>{"use strict";var eP=Ye(),tP=Be(),ic=na(),iP=eP(Function.toString);tP(ic.inspectSource)||(ic.inspectSource=function(s){return iP(s)});eb.exports=ic.inspectSource});var ac=g((t0,ab)=>{"use strict";var rP=Ye(),sP=Je(),tb=Be(),aP=pa(),nP=ki(),oP=rc(),ib=function(){},rb=nP("Reflect","construct"),sc=/^\s*(?:class|function)\b/,uP=rP(sc.exec),lP=!sc.test(ib),ga=function(e){if(!tb(e))return!1;try{return rb(ib,[],e),!0}catch(t){return!1}},sb=function(e){if(!tb(e))return!1;switch(aP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return lP||!!uP(sc,oP(e))}catch(t){return!0}};sb.sham=!0;ab.exports=!rb||sP(function(){var s;return ga(ga.call)||!ga(Object)||!ga(function(){s=!0})||s})?sb:ga});var ob=g((i0,nb)=>{"use strict";var cP=ac(),dP=sa(),pP=TypeError;nb.exports=function(s){if(cP(s))return s;throw new pP(dP(s)+" is not a constructor")}});var nc=g((r0,lb)=>{"use strict";var ub=ni(),hP=ob(),fP=Lr(),mP=Ze(),bP=mP("species");lb.exports=function(s,e){var t=ub(s).constructor,i;return t===void 0||fP(i=ub(t)[bP])?e:hP(i)}});var db=g((s0,cb)=>{"use strict";var gP=Ye();cb.exports=gP([].slice)});var hb=g((a0,pb)=>{"use strict";var SP=TypeError;pb.exports=function(s,e){if(s<e)throw new SP("Not enough arguments");return s}});var oc=g((n0,fb)=>{"use strict";var vP=cr();fb.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(vP)});var bc=g((o0,xb)=>{"use strict";var Bt=Ce(),yP=Ju(),TP=Dr(),mb=Be(),IP=Xt(),Ib=Je(),bb=Nl(),xP=db(),gb=co(),EP=hb(),wP=oc(),AP=Lo(),hc=Bt.setImmediate,fc=Bt.clearImmediate,PP=Bt.process,uc=Bt.Dispatch,kP=Bt.Function,Sb=Bt.MessageChannel,RP=Bt.String,lc=0,Sa={},vb="onreadystatechange",va,mr,cc,dc;Ib(function(){va=Bt.location});var mc=function(s){if(IP(Sa,s)){var e=Sa[s];delete Sa[s],e()}},pc=function(s){return function(){mc(s)}},yb=function(s){mc(s.data)},Tb=function(s){Bt.postMessage(RP(s),va.protocol+"//"+va.host)};(!hc||!fc)&&(hc=function(e){EP(arguments.length,1);var t=mb(e)?e:kP(e),i=xP(arguments,1);return Sa[++lc]=function(){yP(t,void 0,i)},mr(lc),lc},fc=function(e){delete Sa[e]},AP?mr=function(s){PP.nextTick(pc(s))}:uc&&uc.now?mr=function(s){uc.now(pc(s))}:Sb&&!wP?(cc=new Sb,dc=cc.port2,cc.port1.onmessage=yb,mr=TP(dc.postMessage,dc)):Bt.addEventListener&&mb(Bt.postMessage)&&!Bt.importScripts&&va&&va.protocol!=="file:"&&!Ib(Tb)?(mr=Tb,Bt.addEventListener("message",yb,!1)):vb in gb("script")?mr=function(s){bb.appendChild(gb("script"))[vb]=function(){bb.removeChild(this),mc(s)}}:mr=function(s){setTimeout(pc(s),0)});xb.exports={set:hc,clear:fc}});var Ab=g((u0,wb)=>{"use strict";var Eb=Ce(),LP=Lt(),MP=Object.getOwnPropertyDescriptor;wb.exports=function(s){if(!LP)return Eb[s];var e=MP(Eb,s);return e&&e.value}});var gc=g((l0,kb)=>{"use strict";var Pb=function(){this.head=null,this.tail=null};Pb.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};kb.exports=Pb});var Lb=g((c0,Rb)=>{"use strict";var $P=cr();Rb.exports=/ipad|iphone|ipod/i.test($P)&&typeof Pebble!="undefined"});var $b=g((d0,Mb)=>{"use strict";var BP=cr();Mb.exports=/web0s(?!.*chrome)/i.test(BP)});var Fb=g((p0,_b)=>{"use strict";var Ur=Ce(),DP=Ab(),Bb=Dr(),Sc=bc().set,CP=gc(),VP=oc(),OP=Lb(),_P=$b(),vc=Lo(),Db=Ur.MutationObserver||Ur.WebKitMutationObserver,Cb=Ur.document,Vb=Ur.process,Mo=Ur.Promise,Ic=DP("queueMicrotask"),Nr,yc,Tc,$o,Ob;Ic||(ya=new CP,Ta=function(){var s,e;for(vc&&(s=Vb.domain)&&s.exit();e=ya.get();)try{e()}catch(t){throw ya.head&&Nr(),t}s&&s.enter()},!VP&&!vc&&!_P&&Db&&Cb?(yc=!0,Tc=Cb.createTextNode(""),new Db(Ta).observe(Tc,{characterData:!0}),Nr=function(){Tc.data=yc=!yc}):!OP&&Mo&&Mo.resolve?($o=Mo.resolve(void 0),$o.constructor=Mo,Ob=Bb($o.then,$o),Nr=function(){Ob(Ta)}):vc?Nr=function(){Vb.nextTick(Ta)}:(Sc=Bb(Sc,Ur),Nr=function(){Sc(Ta)}),Ic=function(s){ya.head||Nr(),ya.add(s)});var ya,Ta;_b.exports=Ic});var Ub=g((h0,Nb)=>{"use strict";Nb.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var Bo=g((f0,qb)=>{"use strict";qb.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var br=g((m0,jb)=>{"use strict";var FP=Ce();jb.exports=FP.Promise});var qr=g((b0,Qb)=>{"use strict";var NP=Ce(),Ia=br(),UP=Be(),qP=yl(),jP=rc(),HP=Ze(),Hb=tc(),GP=Kt(),xc=ol(),Gb=Ia&&Ia.prototype,zP=HP("species"),Ec=!1,zb=UP(NP.PromiseRejectionEvent),QP=qP("Promise",function(){var s=jP(Ia),e=s!==String(Ia);if(!e&&xc===66||GP&&!(Gb.catch&&Gb.finally))return!0;if(!xc||xc<51||!/native code/.test(s)){var t=new Ia(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[zP]=i,Ec=t.then(function(){})instanceof i,!Ec)return!0}return!e&&(Hb==="BROWSER"||Hb==="DENO")&&!zb});Qb.exports={CONSTRUCTOR:QP,REJECTION_EVENT:zb,SUBCLASSING:Ec}});var jr=g((g0,Yb)=>{"use strict";var Wb=ai(),WP=TypeError,YP=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new WP("Bad Promise constructor");e=i,t=r}),this.resolve=Wb(e),this.reject=Wb(t)};Yb.exports.f=function(s){return new YP(s)}});var fg=g(()=>{"use strict";var KP=Ne(),XP=Kt(),Oo=Lo(),zi=Ce(),Qr=Mt(),Kb=Fr(),Xb=Yl(),JP=ha(),ZP=Xm(),ek=ai(),Vo=Be(),tk=$t(),ik=Zm(),rk=nc(),ig=bc().set,Rc=Fb(),sk=Ub(),ak=Bo(),nk=gc(),rg=Vl(),_o=br(),Lc=qr(),sg=jr(),Fo="Promise",ag=Lc.CONSTRUCTOR,ok=Lc.REJECTION_EVENT,uk=Lc.SUBCLASSING,wc=rg.getterFor(Fo),lk=rg.set,Hr=_o&&_o.prototype,gr=_o,Do=Hr,ng=zi.TypeError,Ac=zi.document,Mc=zi.process,Pc=sg.f,ck=Pc,dk=!!(Ac&&Ac.createEvent&&zi.dispatchEvent),og="unhandledrejection",pk="rejectionhandled",Jb=0,ug=1,hk=2,$c=1,lg=2,Co,Zb,fk,eg,cg=function(s){var e;return tk(s)&&Vo(e=s.then)?e:!1},dg=function(s,e){var t=e.value,i=e.state===ug,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===lg&&bk(e),e.rejection=$c),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new ng("Promise-chain cycle")):(l=cg(u))?Qr(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},pg=function(s,e){s.notified||(s.notified=!0,Rc(function(){for(var t=s.reactions,i;i=t.get();)dg(i,s);s.notified=!1,e&&!s.rejection&&mk(s)}))},hg=function(s,e,t){var i,r;dk?(i=Ac.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),zi.dispatchEvent(i)):i={promise:e,reason:t},!ok&&(r=zi["on"+s])?r(i):s===og&&sk("Unhandled promise rejection",t)},mk=function(s){Qr(ig,zi,function(){var e=s.facade,t=s.value,i=tg(s),r;if(i&&(r=ak(function(){Oo?Mc.emit("unhandledRejection",t,e):hg(og,e,t)}),s.rejection=Oo||tg(s)?lg:$c,r.error))throw r.value})},tg=function(s){return s.rejection!==$c&&!s.parent},bk=function(s){Qr(ig,zi,function(){var e=s.facade;Oo?Mc.emit("rejectionHandled",e):hg(pk,e,s.value)})},Gr=function(s,e,t){return function(i){s(e,i,t)}},zr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=hk,pg(s,!0))},kc=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new ng("Promise can't be resolved itself");var i=cg(e);i?Rc(function(){var r={done:!1};try{Qr(i,e,Gr(kc,r,s),Gr(zr,r,s))}catch(a){zr(r,a,s)}}):(s.value=e,s.state=ug,pg(s,!1))}catch(r){zr({done:!1},r,s)}}};if(ag&&(gr=function(e){ik(this,Do),ek(e),Qr(Co,this);var t=wc(this);try{e(Gr(kc,t),Gr(zr,t))}catch(i){zr(t,i)}},Do=gr.prototype,Co=function(e){lk(this,{type:Fo,done:!1,notified:!1,parent:!1,reactions:new nk,rejection:!1,state:Jb,value:void 0})},Co.prototype=Kb(Do,"then",function(e,t){var i=wc(this),r=Pc(rk(this,gr));return i.parent=!0,r.ok=Vo(e)?e:!0,r.fail=Vo(t)&&t,r.domain=Oo?Mc.domain:void 0,i.state===Jb?i.reactions.add(r):Rc(function(){dg(r,i)}),r.promise}),Zb=function(){var s=new Co,e=wc(s);this.promise=s,this.resolve=Gr(kc,e),this.reject=Gr(zr,e)},sg.f=Pc=function(s){return s===gr||s===fk?new Zb(s):ck(s)},!XP&&Vo(_o)&&Hr!==Object.prototype)){eg=Hr.then,uk||Kb(Hr,"then",function(e,t){var i=this;return new gr(function(r,a){Qr(eg,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Hr.constructor}catch(s){}Xb&&Xb(Hr,Do)}KP({global:!0,constructor:!0,wrap:!0,forced:ag},{Promise:gr});JP(gr,Fo,!1,!0);ZP(Fo)});var vg=g((y0,Sg)=>{"use strict";var gk=Ze(),bg=gk("iterator"),gg=!1;try{mg=0,Bc={next:function(){return{done:!!mg++}},return:function(){gg=!0}},Bc[bg]=function(){return this},Array.from(Bc,function(){throw 2})}catch(s){}var mg,Bc;Sg.exports=function(s,e){try{if(!e&&!gg)return!1}catch(r){return!1}var t=!1;try{var i={};i[bg]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var Dc=g((T0,yg)=>{"use strict";var Sk=br(),vk=vg(),yk=qr().CONSTRUCTOR;yg.exports=yk||!vk(function(s){Sk.all(s).then(void 0,function(){})})});var Tg=g(()=>{"use strict";var Tk=Ne(),Ik=Mt(),xk=ai(),Ek=jr(),wk=Bo(),Ak=Po(),Pk=Dc();Tk({target:"Promise",stat:!0,forced:Pk},{all:function(e){var t=this,i=Ek.f(t),r=i.resolve,a=i.reject,n=wk(function(){var o=xk(t.resolve),u=[],l=0,d=1;Ak(e,function(c){var p=l++,h=!1;d++,Ik(o,t,c).then(function(f){h||(h=!0,u[p]=f,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),i.promise}})});var xg=g(()=>{"use strict";var kk=Ne(),Rk=Kt(),Lk=qr().CONSTRUCTOR,Vc=br(),Mk=ki(),$k=Be(),Bk=Fr(),Ig=Vc&&Vc.prototype;kk({target:"Promise",proto:!0,forced:Lk,real:!0},{catch:function(s){return this.then(void 0,s)}});!Rk&&$k(Vc)&&(Cc=Mk("Promise").prototype.catch,Ig.catch!==Cc&&Bk(Ig,"catch",Cc,{unsafe:!0}));var Cc});var Eg=g(()=>{"use strict";var Dk=Ne(),Ck=Mt(),Vk=ai(),Ok=jr(),_k=Bo(),Fk=Po(),Nk=Dc();Dk({target:"Promise",stat:!0,forced:Nk},{race:function(e){var t=this,i=Ok.f(t),r=i.reject,a=_k(function(){var n=Vk(t.resolve);Fk(e,function(o){Ck(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var wg=g(()=>{"use strict";var Uk=Ne(),qk=jr(),jk=qr().CONSTRUCTOR;Uk({target:"Promise",stat:!0,forced:jk},{reject:function(e){var t=qk.f(this),i=t.reject;return i(e),t.promise}})});var Oc=g((L0,Ag)=>{"use strict";var Hk=ni(),Gk=$t(),zk=jr();Ag.exports=function(s,e){if(Hk(s),Gk(e)&&e.constructor===s)return e;var t=zk.f(s),i=t.resolve;return i(e),t.promise}});var Rg=g(()=>{"use strict";var Qk=Ne(),Wk=ki(),Pg=Kt(),Yk=br(),kg=qr().CONSTRUCTOR,Kk=Oc(),Xk=Wk("Promise"),Jk=Pg&&!kg;Qk({target:"Promise",stat:!0,forced:Pg||kg},{resolve:function(e){return Kk(Jk&&this===Xk?Yk:this,e)}})});var Lg=g(()=>{"use strict";fg();Tg();xg();Eg();wg();Rg()});var Dg=g(()=>{"use strict";var Zk=Ne(),eR=Kt(),No=br(),tR=Je(),$g=ki(),Bg=Be(),iR=nc(),Mg=Oc(),rR=Fr(),Fc=No&&No.prototype,sR=!!No&&tR(function(){Fc.finally.call({then:function(){}},function(){})});Zk({target:"Promise",proto:!0,real:!0,forced:sR},{finally:function(s){var e=iR(this,$g("Promise")),t=Bg(s);return this.then(t?function(i){return Mg(e,s()).then(function(){return i})}:s,t?function(i){return Mg(e,s()).then(function(){throw i})}:s)}});!eR&&Bg(No)&&(_c=$g("Promise").prototype.finally,Fc.finally!==_c&&rR(Fc,"finally",_c,{unsafe:!0}));var _c});var Vg=g((O0,Cg)=>{"use strict";Hm();Lg();Dg();var aR=Gi();Cg.exports=aR("Promise","finally")});var _g=g((_0,Og)=>{"use strict";var nR=Vg();Og.exports=nR});var xa=g((F0,Fg)=>{"use strict";var oR=_g();Fg.exports=oR});var zg=g(()=>{"use strict";var pR=Ne(),hR=$l().values;pR({target:"Object",stat:!0},{values:function(e){return hR(e)}})});var Wg=g((bC,Qg)=>{"use strict";zg();var fR=Mr();Qg.exports=fR.Object.values});var Kg=g((gC,Yg)=>{"use strict";var mR=Wg();Yg.exports=mR});var Sr=g((SC,Xg)=>{"use strict";var bR=Kg();Xg.exports=bR});var uS=g(()=>{"use strict";var AR=Ne(),PR=$r(),kR=_r(),RR=la(),LR=ca();AR({target:"Array",proto:!0},{at:function(e){var t=PR(this),i=kR(t),r=RR(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});LR("at")});var cS=g((IV,lS)=>{"use strict";uS();var MR=Gi();lS.exports=MR("Array","at")});var pS=g((xV,dS)=>{"use strict";var $R=cS();dS.exports=$R});var Zt=g((EV,hS)=>{"use strict";var BR=pS();hS.exports=BR});var sd=g((JO,DS)=>{"use strict";var GR=ur();DS.exports=Array.isArray||function(e){return GR(e)==="Array"}});var VS=g((ZO,CS)=>{"use strict";var zR=TypeError,QR=9007199254740991;CS.exports=function(s){if(s>QR)throw zR("Maximum allowed index exceeded");return s}});var FS=g((e_,_S)=>{"use strict";var WR=sd(),YR=_r(),KR=VS(),XR=Dr(),OS=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?XR(n,o):!1,c,p;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&WR(c)?(p=YR(c),u=OS(s,e,c,p,u,a-1)-1):(KR(u+1),s[u]=c),u++),l++;return u};_S.exports=OS});var jS=g((t_,qS)=>{"use strict";var NS=sd(),JR=ac(),ZR=$t(),eL=Ze(),tL=eL("species"),US=Array;qS.exports=function(s){var e;return NS(s)&&(e=s.constructor,JR(e)&&(e===US||NS(e.prototype))?e=void 0:ZR(e)&&(e=e[tL],e===null&&(e=void 0))),e===void 0?US:e}});var GS=g((i_,HS)=>{"use strict";var iL=jS();HS.exports=function(s,e){return new(iL(s))(e===0?0:e)}});var zS=g(()=>{"use strict";var rL=Ne(),sL=FS(),aL=ai(),nL=$r(),oL=_r(),uL=GS();rL({target:"Array",proto:!0},{flatMap:function(e){var t=nL(this),i=oL(t),r;return aL(e),r=uL(t,0),r.length=sL(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var QS=g(()=>{"use strict";var lL=ca();lL("flatMap")});var YS=g((o_,WS)=>{"use strict";zS();QS();var cL=Gi();WS.exports=cL("Array","flatMap")});var XS=g((u_,KS)=>{"use strict";var dL=YS();KS.exports=dL});var Ca=g((l_,JS)=>{"use strict";var pL=XS();JS.exports=pL});var Va=g((c_,ZS)=>{"use strict";var hL=pa(),fL=String;ZS.exports=function(s){if(hL(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return fL(s)}});var ad=g((d_,ev)=>{"use strict";ev.exports=`
7
+ \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var rv=g((p_,iv)=>{"use strict";var mL=Ye(),bL=Hi(),gL=Va(),od=ad(),tv=mL("".replace),SL=RegExp("^["+od+"]+"),vL=RegExp("(^|[^"+od+"])["+od+"]+$"),nd=function(s){return function(e){var t=gL(bL(e));return s&1&&(t=tv(t,SL,"")),s&2&&(t=tv(t,vL,"$1")),t}};iv.exports={start:nd(1),end:nd(2),trim:nd(3)}});var ov=g((h_,nv)=>{"use strict";var yL=Fl().PROPER,TL=Je(),sv=ad(),av="\u200B\x85\u180E";nv.exports=function(s){return TL(function(){return!!sv[s]()||av[s]()!==av||yL&&sv[s].name!==s})}});var ud=g((f_,uv)=>{"use strict";var IL=rv().start,xL=ov();uv.exports=xL("trimStart")?function(){return IL(this)}:"".trimStart});var cv=g(()=>{"use strict";var EL=Ne(),lv=ud();EL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==lv},{trimLeft:lv})});var pv=g(()=>{"use strict";cv();var wL=Ne(),dv=ud();wL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==dv},{trimStart:dv})});var fv=g((v_,hv)=>{"use strict";pv();var AL=Gi();hv.exports=AL("String","trimLeft")});var bv=g((y_,mv)=>{"use strict";var PL=fv();mv.exports=PL});var Sv=g((T_,gv)=>{"use strict";var kL=bv();gv.exports=kL});var Mv=g(()=>{"use strict"});var $v=g(()=>{"use strict"});var Dv=g((XN,Bv)=>{"use strict";var WL=$t(),YL=ur(),KL=Ze(),XL=KL("match");Bv.exports=function(s){var e;return WL(s)&&((e=s[XL])!==void 0?!!e:YL(s)==="RegExp")}});var Vv=g((JN,Cv)=>{"use strict";var JL=ni();Cv.exports=function(){var s=JL(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var Fv=g((ZN,_v)=>{"use strict";var ZL=Mt(),eM=Xt(),tM=ra(),iM=Vv(),Ov=RegExp.prototype;_v.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in Ov)&&!eM(s,"flags")&&tM(Ov,s)?ZL(iM,s):e}});var Uv=g((eU,Nv)=>{"use strict";var hd=Ye(),rM=$r(),sM=Math.floor,dd=hd("".charAt),aM=hd("".replace),pd=hd("".slice),nM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,oM=/\$([$&'`]|\d{1,2})/g;Nv.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=oM;return r!==void 0&&(r=rM(r),u=nM),aM(a,u,function(l,d){var c;switch(dd(d,0)){case"$":return"$";case"&":return s;case"`":return pd(e,0,t);case"'":return pd(e,n);case"<":c=r[pd(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=sM(p/10);return h===0?l:h<=o?i[h-1]===void 0?dd(d,1):i[h-1]+dd(d,1):l}c=i[p-1]}return c===void 0?"":c})}});var Hv=g(()=>{"use strict";var uM=Ne(),lM=Mt(),md=Ye(),qv=Hi(),cM=Be(),dM=Lr(),pM=Dv(),as=Va(),hM=aa(),fM=Fv(),mM=Uv(),bM=Ze(),gM=Kt(),SM=bM("replace"),vM=TypeError,fd=md("".indexOf),yM=md("".replace),jv=md("".slice),TM=Math.max;uM({target:"String",proto:!0},{replaceAll:function(e,t){var i=qv(this),r,a,n,o,u,l,d,c,p,h,f=0,b="";if(!dM(e)){if(r=pM(e),r&&(a=as(qv(fM(e))),!~fd(a,"g")))throw new vM("`.replaceAll` does not allow non-global regexes");if(n=hM(e,SM),n)return lM(n,e,i,t);if(gM&&r)return yM(as(i),e,t)}for(o=as(i),u=as(e),l=cM(t),l||(t=as(t)),d=u.length,c=TM(1,d),p=fd(o,u);p!==-1;)h=l?as(t(u,p,o)):mM(u,o,p,[],void 0,t),b+=jv(o,f,p)+h,f=p+d,p=p+c>o.length?-1:fd(o,u,p+c);return f<o.length&&(b+=jv(o,f)),b}})});var zv=g((rU,Gv)=>{"use strict";Mv();$v();Hv();var IM=Gi();Gv.exports=IM("String","replaceAll")});var Wv=g((sU,Qv)=>{"use strict";var xM=zv();Qv.exports=xM});var bd=g((aU,Yv)=>{"use strict";var EM=Wv();Yv.exports=EM});var Xv=g((nU,Kv)=>{"use strict";var wM=la(),AM=Va(),PM=Hi(),kM=RangeError;Kv.exports=function(e){var t=AM(PM(this)),i="",r=wM(e);if(r<0||r===1/0)throw new kM("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var iy=g((oU,ty)=>{"use strict";var ey=Ye(),RM=Al(),Jv=Va(),LM=Xv(),MM=Hi(),$M=ey(LM),BM=ey("".slice),DM=Math.ceil,Zv=function(s){return function(e,t,i){var r=Jv(MM(e)),a=RM(t),n=r.length,o=i===void 0?" ":Jv(i),u,l;return a<=n||o===""?r:(u=a-n,l=$M(o,DM(u/o.length)),l.length>u&&(l=BM(l,0,u)),s?r+l:l+r)}};ty.exports={start:Zv(!1),end:Zv(!0)}});var sy=g((uU,ry)=>{"use strict";var CM=cr();ry.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(CM)});var ay=g(()=>{"use strict";var VM=Ne(),OM=iy().start,_M=sy();VM({target:"String",proto:!0,forced:_M},{padStart:function(e){return OM(this,e,arguments.length>1?arguments[1]:void 0)}})});var oy=g((dU,ny)=>{"use strict";ay();var FM=Gi();ny.exports=FM("String","padStart")});var ly=g((pU,uy)=>{"use strict";var NM=oy();uy.exports=NM});var gd=g((hU,cy)=>{"use strict";var UM=ly();cy.exports=UM});var $$={};MT($$,{ChromecastState:()=>Js,HttpConnectionType:()=>no,Observable:()=>hi.Observable,PlaybackState:()=>pt,Player:()=>so,PredefinedQualityLimits:()=>Zs,SDK_VERSION:()=>M$,Subject:()=>hi.Subject,Subscription:()=>hi.Subscription,Surface:()=>oo,VERSION:()=>Ku,ValueSubject:()=>hi.ValueSubject,VideoFormat:()=>si,VideoQuality:()=>hi.VideoQuality,clientChecker:()=>J,isMobile:()=>Wr});module.exports=$T($$);var Ku="2.0.131-dev.c7ccfbe4.0";var pt=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(pt||{}),si=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(si||{});var Js=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Js||{}),no=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(no||{});var oo=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(oo||{}),Zs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Zs||{});var wT=Y(_t(),1);var oe=require("@vkontakte/videoplayer-shared/es2018");var Gh=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var ho=class{constructor(e){this.connection$=new oe.ValueSubject(void 0);this.castState$=new oe.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new oe.Subject;this.realCastState$=new oe.ValueSubject("NOT_AVAILABLE");this.subscription=new oe.Subscription;this.isDestroyed=!1;var a;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,oe.isNonNullable)((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Gh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:oe.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,oe.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,oe.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,oe.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,oe.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,oe.assertNever)(r.sessionState)}})).add((0,oe.merge)((0,oe.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,oe.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,oe.map)(r=>r.castState)),(0,oe.observableFrom)([i.getCastState()])).pipe((0,oe.filterChanged)(),(0,oe.map)(eE),(0,oe.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=(0,oe.isNonNullable)(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();(0,oe.assertNonNullable)(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,oe.isNullable)(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,oe.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:oe.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},eE=s=>{switch(s){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,oe.assertNever)(s)}};var Yd=Y(_t(),1),pT=Y(pr(),1),hT=Y(ec(),1);var jg=Y(xa(),1);var Nc=require("@vkontakte/videoplayer-shared/es2018");var De=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Nc.assertNever)(t)}return s},Qi=(s,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Nc.assertNever)(e)}};var V=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var oi=require("@vkontakte/videoplayer-shared/es2018"),te=class{constructor(e){this.transitionStarted$=new oi.Subject;this.transitionEnded$=new oi.Subject;this.transitionUpdated$=new oi.Subject;this.forceChanged$=new oi.Subject;this.stateChangeStarted$=(0,oi.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,oi.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,oi.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 Ng=require("@vkontakte/videoplayer-shared/es2018"),Ug=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Ng.assertNever)(s)}};var Q=require("@vkontakte/videoplayer-shared/es2018");var uR=5,lR=5,cR=500,qg=7e3,Ea=class{constructor(e){this.subscription=new Q.Subscription;this.loadMediaTimeoutSubscription=new Q.Subscription;this.videoState=new te("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=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(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.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,Q.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,Q.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,Q.assertNever)(e)}break}default:(0,Q.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(Ug(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 Q.Subscription;this.subscription.add(e),this.subscription.add((0,Q.merge)(this.videoState.stateChangeStarted$.pipe((0,Q.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,Q.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new Q.Subject;e.add(r.pipe((0,Q.debounce)(cR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,Q.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-a)>uR)&&r.next(o),a=o})),e.add((0,Q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,Q.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,Q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,Q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=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()&&a.duration-a.currentTime<lR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),V(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,Q.assertNever)(n)}}),t((0,Q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,Q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,Q.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,Q.observableFrom)(["init"])).pipe((0,Q.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"),V(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),V(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),V(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),V(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&V(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let d=t[e];(0,Q.assertNonNullable)(d);let c=(0,Q.getHighestQuality)(Object.keys(d));(0,Q.assertNonNullable)(c);let p=d[c];(0,Q.assertNonNullable)(p),i=p,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];(0,Q.assertNonNullable)(d),i=d.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];(0,Q.assertNonNullable)(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];(0,Q.assertNonNullable)(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];(0,Q.assertNonNullable)(d),i=De(d.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Q.ErrorCategory.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,Q.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,Q.isNonNullable)(o)&&(n.metadata.title=o),(0,Q.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add((0,Q.timeout)(qg).subscribe(()=>a(`timeout(${qg})`)))});(0,jg.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 a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Q.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var id=Y(_t(),1);var Hc=require("@vkontakte/videoplayer-shared/es2018");var Hg=require("@vkontakte/videoplayer-shared/es2018"),Gg=s=>{try{s.pause(),s.playbackRate=0,(0,Hg.clearVideoElement)(s),s.remove()}catch(e){console.error(e)}};var Uo=require("@vkontakte/videoplayer-shared/es2018"),Uc=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)}},qc=window.WeakMap?new WeakMap:new Uc,jc=window.WeakMap?new WeakMap:new Map,dR=(s,e=20)=>{let t=0;return(0,Uo.fromEvent)(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},et=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?(0,Hc.clearVideoElement)(i):(i=document.createElement("video"),s.appendChild(i)),qc.set(i,r);let a=new Uo.Subscription;return a.add(dR(i,e)),jc.set(i,a),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},tt=s=>{let e=jc.get(s);e==null||e.unsubscribe(),jc.delete(s);let t=qc.get(s);qc.delete(s),t?(0,Hc.clearVideoElement)(s):Gg(s)};var Gc=Y(Sr(),1),W=require("@vkontakte/videoplayer-shared/es2018");var Wi=require("@vkontakte/videoplayer-shared/es2018"),qo=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=(0,Wi.isNullable)(r),l=new Wi.Subscription;return r&&l.add(r.subscribe(d=>{let c=s.getState();i(d,c)&&s.setState(d)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(d=>{t(d.to),u&&s.setState(d.to)},a)),l},Ft=(s,e,t)=>qo(e,()=>s.loop,i=>{(0,Wi.isNonNullable)(i)&&(s.loop=i)},{onError:t}),it=(s,e,t,i)=>qo(e,()=>({muted:s.muted,volume:s.volume}),r=>{(0,Wi.isNonNullable)(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),gt=(s,e,t,i)=>qo(e,()=>s.playbackRate,r=>{(0,Wi.isNonNullable)(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Yi=qo;var gR=s=>["__",s.language,s.label].join("|"),SR=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},zc=class s{constructor(e){this.available$=new W.Subject;this.current$=new W.ValueSubject(void 0);this.error$=new W.Subject;this.subscription=new W.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=a=>{this.error$.next({id:"TextTracksManager",category:W.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};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(Yi(t.internalTextTracks,()=>(0,Gc.default)(this.internalTracks),a=>{(0,W.isNonNullable)(a)&&this.setInternal(a)},{equal:(a,n)=>(0,W.isNonNullable)(a)&&(0,W.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,W.map)(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Yi(t.externalTextTracks,()=>(0,Gc.default)(this.externalTracks),a=>{(0,W.isNonNullable)(a)&&this.setExternal(a)},{equal:(a,n)=>(0,W.isNonNullable)(a)&&(0,W.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,W.map)(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Yi(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(Yi(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){(0,W.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,W.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,W.merge)((0,W.fromEvent)(e,"addtrack"),(0,W.fromEvent)(e,"removetrack"),(0,W.observableFrom)(["init"])).pipe((0,W.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,W.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add((0,W.merge)((0,W.fromEvent)(e,"change"),(0,W.observableFrom)(["init"])).pipe((0,W.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,W.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,W.filterChanged)()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add((0,W.fromEvent)(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,d,c,p,h;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(c=o.target)==null?void 0:c.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,W.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,W.isNonNullable)(t.align)&&(r.align=t.align),(0,W.isNonNullable)(t.position)&&(r.position=t.position),(0,W.isNonNullable)(t.size)&&(r.size=t.size),(0,W.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,W.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:gR(e),a=this.externalTracks.has(r),n=(l=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).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,W.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,W.isNullable)(e)||!SR(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,W.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,W.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)}},St=zc;var vr=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 Jg=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Qc=s=>{let e=Jg(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Zg=s=>{let e=Jg(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};var U=require("@vkontakte/videoplayer-shared/es2018");var vR=3,eS=(s,e,t=vR)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var jo=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}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,a=/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,l=/edg/i.test(e)?"Edge":void 0;this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var tS=Y(_t(),1);var Wr=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Ho=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,tS.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||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.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Wr()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}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,a=/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||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Go=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}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(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var Dt=()=>window.ManagedMediaSource||window.MediaSource,Yr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},iS=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},zo=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var yR=document.createElement("video"),TR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',IR='video/mp4; codecs="hev1.1.6.L93.B0"',rS='video/webm; codecs="vp09.00.10.08"',sS='video/webm; codecs="av01.0.00M.08"',xR='audio/mp4; codecs="mp4a.40.2"',ER='audio/webm; codecs="opus"',aS,wR=async()=>{if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:sS}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:rS}})]);aS={DASH_WEBM_AV1:e,DASH_WEBM:t}};wR().catch(s=>{console.log(yR),console.error(s)});var Qo=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 aS}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,a,n,o,u,l,d,c,p,h,f,b,S,v,y,x,A;this._video=document.createElement("video");try{this._protocols={mms:Yr(),mse:iS(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(a=this._video).canPlayType)!=null&&n.call(a,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let w=!!((d=(l=Dt())==null?void 0:l.isTypeSupported)!=null&&d.call(l,TR)),L=!!((p=(c=Dt())==null?void 0:c.isTypeSupported)!=null&&p.call(c,IR)),q=!!((f=(h=Dt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,xR));this._codecs={h264:w,h265:L,vp9:!!((S=(b=Dt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,rS)),av1:!!((y=(v=Dt())==null?void 0:v.isTypeSupported)!=null&&y.call(v,sS)),aac:q,opus:!!((A=(x=Dt())==null?void 0:x.isTypeSupported)!=null&&A.call(x,ER)),mpeg:(w||L)&&q},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(w){console.error(w)}this.destroyVideoElement()}destroyVideoElement(){var t;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);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var nS="audio/mpeg",Wo=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,nS))},this._codecs={mp3:!!((r=(i=Dt())==null?void 0:i.isTypeSupported)!=null&&r.call(i,nS))}}catch(a){console.error(a)}this.destroyAudioElement()}destroyAudioElement(){var t;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);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};var oS=require("@vkontakte/videoplayer-shared/es2018"),Wc=class{constructor(){this.isInited$=new oS.ValueSubject(!1);this._displayChecker=new Go,this._deviceChecker=new Ho(this._displayChecker),this._browserChecker=new jo,this._videoChecker=new Qo(this._deviceChecker,this._browserChecker),this._audioChecker=new Wo,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(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},J=new Wc;var rt=s=>{let e=B=>(0,U.fromEvent)(s,B).pipe((0,U.mapTo)(void 0)),t=new U.Subscription,i=()=>t.unsubscribe(),a=(0,U.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(B=>(0,U.fromEvent)(s,B))).pipe((0,U.map)(B=>B.type==="ended"?s.readyState<2:s.readyState<3),(0,U.filterChanged)()),n=(0,U.merge)((0,U.fromEvent)(s,"progress"),(0,U.fromEvent)(s,"timeupdate")).pipe((0,U.map)(()=>eS(s.buffered,s.currentTime))),o=J.browser.isSafari?(0,U.combine)({play:e("play").pipe((0,U.once)()),playing:e("playing")}).pipe((0,U.mapTo)(void 0)):e("playing"),u=(0,U.fromEvent)(s,"volumechange").pipe((0,U.map)(()=>({muted:s.muted,volume:s.volume}))),l=(0,U.fromEvent)(s,"ratechange").pipe((0,U.map)(()=>s.playbackRate)),d=(0,U.fromEvent)(s,"error").pipe((0,U.filter)(()=>!!(s.error||s.played.length)),(0,U.map)(()=>{var H;let B=s.error;return{id:B?`MediaError#${B.code}`:"HtmlVideoError",category:U.ErrorCategory.VIDEO_PIPELINE,message:B?B.message:"Error event from HTML video element",thrown:(H=s.error)!=null?H:void 0}})),c=(0,U.fromEvent)(s,"timeupdate").pipe((0,U.map)(()=>s.currentTime)),p=new U.Subject,h=.3,f;t.add(c.subscribe(B=>{s.loop&&(0,U.isNonNullable)(f)&&(0,U.isNonNullable)(B)&&f>=s.duration-h&&B<=h&&p.next(f),f=B}));let b=e("pause").pipe((0,U.filter)(()=>!s.error&&f!==s.duration)),S=(0,U.fromEvent)(s,"enterpictureinpicture"),v=(0,U.fromEvent)(s,"leavepictureinpicture"),y=new U.ValueSubject(Zg(s));t.add(S.subscribe(()=>y.next(!0))),t.add(v.subscribe(()=>y.next(!1)));let x=new U.ValueSubject(Qc(s)),A=(0,U.fromEvent)(s,"fullscreenchange");t.add(A.pipe((0,U.map)(()=>Qc(s))).subscribe(x));let w=.1,L=1e3,q=(0,U.fromEvent)(s,"timeupdate").pipe((0,U.filter)(B=>s.duration-s.currentTime<w)),F=(0,U.merge)(q.pipe((0,U.filter)(B=>!s.loop)),(0,U.fromEvent)(s,"ended")).pipe((0,U.throttle)(L),(0,U.mapTo)(void 0)),O=q.pipe((0,U.filter)(B=>s.loop));return{playing$:o,pause$:b,canplay$:e("canplay"),ended$:F,looped$:p,loopExpected$:O,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,U.fromEvent)(s,"durationchange").pipe((0,U.map)(()=>s.duration)),isBuffering$:a,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:y,inFullscreen$:x,enterPip$:S,leavePip$:v,destroy:i}};var Li=require("@vkontakte/videoplayer-shared/es2018"),li=s=>{switch(s){case"mobile":return Li.VideoQuality.Q_144P;case"lowest":return Li.VideoQuality.Q_240P;case"low":return Li.VideoQuality.Q_360P;case"sd":case"medium":return Li.VideoQuality.Q_480P;case"hd":case"high":return Li.VideoQuality.Q_720P;case"fullhd":case"full":return Li.VideoQuality.Q_1080P;case"quadhd":case"quad":return Li.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Li.VideoQuality.Q_2160P}};var ft=Y(Zt(),1),Xc=Y(_t(),1),yr=Y(pr(),1),$=require("@vkontakte/videoplayer-shared/es2018");var Yc=!1,Mi={},fS=s=>{Yc=s},mS=()=>{Mi={}},bS=s=>{s(Mi)},wa=(s,e)=>{var t;Yc&&(Mi.meta=(t=Mi.meta)!=null?t:{},Mi.meta[s]=e)},ht=class{constructor(e){this.name=e}next(e){var i,r;if(!Yc)return;Mi.series=(i=Mi.series)!=null?i:{};let t=(r=Mi.series[this.name])!=null?r:[];t.push([Date.now(),e]),Mi.series[this.name]=t}};var Ue=require("@vkontakte/videoplayer-shared/es2018");function Kc(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Yo(s,e,t){return!!s&&Kc(s,e,t)==="high_quality"}function Kr(s,e,t){return(0,Ue.isNullable)(s)||(0,Ue.isNonNullable)(s.min)&&(0,Ue.isNonNullable)(s.max)&&(0,Ue.isLower)(s.max,s.min)||(0,Ue.isNonNullable)(s.min)&&e&&(0,Ue.isHigher)(s.min,e)||(0,Ue.isNonNullable)(s.max)&&t&&(0,Ue.isLower)(s.max,t)}function gS({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Kr({max:s!=null&&s.max?(0,Ue.videoHeightToQuality)(s.max):void 0,min:s!=null&&s.min?(0,Ue.videoHeightToQuality)(s.min):void 0},e?(0,Ue.videoHeightToQuality)(e):void 0,t?(0,Ue.videoHeightToQuality)(t):void 0)}var DR=new ht("best_bitrate"),Xo=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Xr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),Ki=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,$.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Jo='Assertion "ABR Tracks is empty array" failed',Ko=new WeakMap,SS=new WeakMap,vS=new WeakMap,Aa=(s,e,t,i)=>{var u;let r=[...e].sort(Xr(1)),a=[...t].sort(Xr(1)),n=a.filter(l=>(0,$.isNonNullable)(l.bitrate)&&(0,$.isNonNullable)(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,ft.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,ft.default)(a,-1);return o&&(0,Xc.default)(n,o)?o:n.length?(0,ft.default)(n,-1):(0,ft.default)(a,0)},Pa=(s,e,t,i)=>{var u;let r=Ko.get(e);r||(r=[...e].sort(Xr(1)),Ko.set(e,r));let a=Ko.get(t);a||(a=[...t].sort(Xr(1)),Ko.set(t,a));let n=vS.get(s);n||(n=a.filter(l=>(0,$.isNonNullable)(l.bitrate)&&(0,$.isNonNullable)(s.bitrate)?s.bitrate/l.bitrate>i:!0),vS.set(s,n));let o=(u=(0,ft.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,ft.default)(a,-1);return o&&(0,Xc.default)(n,o)?o:n.length?(0,ft.default)(n,-1):(0,ft.default)(a,0)},yS=s=>"quality"in s,Zo=(s,e,t,i)=>{var n;let r=(0,$.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,$.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&(0,$.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!a&&i.recordSelection(t),a&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=yS(o)?"video":"audio",l=yS(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return i==null||i.recordSwitch(t),t},OA=(a,e)=>Math.log(e)/Math.log(a),BA=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&K.display.pixelRatio){let s=K.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,l=0]=a.pixelRatioLogCoefficients,c=OA(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return Ru({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},zt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:m,stallsPredictedThroughput:h,abrLogger:f,panelSize:g})=>{var re,ge,L,Y,ae;(0,N.assertNotEmptyArray)(a,Lb);let{containerSizeFactor:S,containerSizeLimit:y}=BA({container:e,tuning:i,limits:r,panelSize:g}),E=i.considerPlaybackRate&&(0,N.isNonNullable)(o)?o:1,x=a.filter(k=>!(0,N.isInvariantQuality)(k.quality)).sort((k,B)=>(0,N.isHigher)(k.quality,B.quality)?-1:1),w=(re=(0,Yt.default)(x,-1))==null?void 0:re.quality,P=(ge=(0,Yt.default)(x,0))==null?void 0:ge.quality,V=Hr({limits:r,lowestAvailableQuality:w,highestAvailableQuality:P}),J=E*$b(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),W={},$=x.filter(k=>{let B=!0;if(y)if(k.size)B=k.size.width<=y.width&&k.size.height<=y.height;else{let Tt=y&&(0,N.videoSizeToQuality)(y);B=Tt?(0,N.isLowerOrEqual)(k.quality,Tt):!0}if(!B)return W[k.quality]="FitsContainer",!1;let Ee=h||t,Ei=(0,N.isNonNullable)(Ee)&&isFinite(Ee)&&(0,N.isNonNullable)(k.bitrate)?Ee-s>=k.bitrate*J:!0,yt=Ru({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:r})&&(r==null?void 0:r.min)===k.quality;if(!Ei&&!yt)return W[k.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,N.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,N.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,N.isHigher)(k.quality,u.quality))return W[k.quality]="Buffer",!1;if(!!d&&(0,N.isHigherOrEqual)(k.quality,d)&&!yt)return W[k.quality]="DroppedFramesLimit",!1;if(!!m&&(0,N.isHigherOrEqual)(k.quality,m)&&!yt)return W[k.quality]="StallsLimit",!1;let De=V||((0,N.isNullable)(r==null?void 0:r.max)||(0,N.isLowerOrEqual)(k.quality,r.max))&&((0,N.isNullable)(r==null?void 0:r.min)||(0,N.isHigherOrEqual)(k.quality,r.min)),lt=(0,N.isNonNullable)(c)&&!c?(0,N.isLowerOrEqual)(k.quality,i.backgroundVideoQualityLimit):!0;return!De||!lt?(W[k.quality]="FitsQualityLimits",!1):!0})[0];$&&$.bitrate&&VA.next($.bitrate);let Z=(L=$!=null?$:(0,Yt.default)(x,-1))!=null?L:a[0],_=l==null?void 0:l.last,C=Mb(i,f,Z,l);return(0,N.isNonNullable)(l)&&C.quality!==(_==null?void 0:_.quality)&&f({message:`
9
+ `}),o}return i==null||i.recordSwitch(t),t},CR=(s,e)=>Math.log(e)/Math.log(s),IS=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&J.display.pixelRatio){let a=J.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,d=CR(n,o*a+u)+l;Number.isFinite(d)&&(r*=d)}}return Yo(t,s.highQualityLimit,s.trafficSavingLimit)&&(r*=2),{containerSizeLimit:s.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},TS=new WeakMap,ci=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f,panelSize:b})=>{var _,ne,K,M,z;(0,$.assertNotEmptyArray)(s,Jo);let{containerSizeFactor:S,containerSizeLimit:v}=IS({container:e,tuning:i,limits:r,panelSize:b}),y=i.considerPlaybackRate&&(0,$.isNonNullable)(o)?o:1,x=TS.get(s);x||(x=s.filter(D=>!(0,$.isInvariantQuality)(D.quality)).sort((D,R)=>(0,$.isHigher)(D.quality,R.quality)?-1:1),TS.set(s,x));let A=(_=(0,ft.default)(x,-1))==null?void 0:_.quality,w=(ne=(0,ft.default)(x,0))==null?void 0:ne.quality,L=Kr(r,w,A),q=y*Xo(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),F={},O=null;for(let D of x){let R=!0;if(v)if(D.size)R=D.size.width<=v.width&&D.size.height<=v.height;else{let Xe=v&&(0,$.videoSizeToQuality)(v);R=Xe?(0,$.isLowerOrEqual)(D.quality,Xe):!0}if(!R){F[D.quality]="FitsContainer";continue}let C=h||t,Le=(0,$.isNonNullable)(C)&&isFinite(C)&&(0,$.isNonNullable)(D.bitrate)?C-a>=D.bitrate*q:!0,It=Yo(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===D.quality;if(!Le&&!It){F[D.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&(0,$.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,$.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,$.isHigher)(D.quality,u.quality)){F[D.quality]="Buffer";continue}if(!!c&&(0,$.isHigherOrEqual)(D.quality,c)&&!It){F[D.quality]="DroppedFramesLimit";continue}if(!!p&&(0,$.isHigherOrEqual)(D.quality,p)&&!It){F[D.quality]="StallsLimit";continue}let Oe=L||((0,$.isNullable)(r==null?void 0:r.max)||(0,$.isLowerOrEqual)(D.quality,r.max))&&((0,$.isNullable)(r==null?void 0:r.min)||(0,$.isHigherOrEqual)(D.quality,r.min)),_e=(0,$.isNonNullable)(d)&&!d?(0,$.isLowerOrEqual)(D.quality,i.backgroundVideoQualityLimit):!0;if(!Oe||!_e){F[D.quality]="FitsQualityLimits";continue}O||(O=D)}let B=(K=O!=null?O:(0,ft.default)(x,-1))!=null?K:s[0],H=l==null?void 0:l.last,N=Zo(i,f,B,l);return(0,$.isNonNullable)(l)&&N.quality!==(H==null?void 0:H.quality)&&f({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${a.map(k=>{var B,Ee;return`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate}, size: ${(B=k.size)==null?void 0:B.width}:${(Ee=k.size)==null?void 0:Ee.height} }`}).join(`
12
+ ${s.map(D=>{var R,C;return`{ id: ${D.id}, quality: ${D.quality}, bitrate: ${D.bitrate}, size: ${(R=D.size)==null?void 0:R.width}:${(C=D.size)==null?void 0:C.height} }`}).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,Ws.default)(i!=null?i:{}).map(([k,B])=>`${k}: ${B}`).join(`
16
+ ${(0,yr.default)(i!=null?i:{}).map(([D,R])=>`${D}: ${R}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
20
20
  containerSizeFactor: ${S},
21
- containerSizeLimit: ${(Y=y==null?void 0:y.width)!=null?Y:0} x ${(ae=y==null?void 0:y.height)!=null?ae:0},
21
+ containerSizeLimit: ${(M=v==null?void 0:v.width)!=null?M:0} x ${(z=v==null?void 0:v.height)!=null?z:0},
22
22
  estimatedThroughput: ${t},
23
23
  stallsPredictedThroughput: ${h},
24
- reserve: ${s},
24
+ reserve: ${a},
25
25
  playbackRate: ${o},
26
- playbackRateFactor: ${E},
26
+ playbackRateFactor: ${y},
27
27
  forwardBufferHealth: ${n},
28
- bitrateFactor: ${J},
28
+ bitrateFactor: ${q},
29
29
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
30
- droppedVideoMaxQualityLimit: ${d},
31
- stallsVideoMaxQualityLimit: ${m},
32
- limitsAreInvalid: ${V},
30
+ droppedVideoMaxQualityLimit: ${c},
31
+ stallsVideoMaxQualityLimit: ${p},
32
+ limitsAreInvalid: ${L},
33
33
  maxQualityLimit: ${r==null?void 0:r.max},
34
34
  minQualityLimit: ${r==null?void 0:r.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,Ws.default)(W).map(([k,B])=>`${k}: ${B}`).join(`
37
+ ${(0,yr.default)(F).map(([D,R])=>`${D}: ${R}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
- [best video track] ${$==null?void 0:$.quality}
41
- [selected video track] ${C==null?void 0:C.quality}
42
- `}),C},Db=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{(0,N.assertNotEmptyArray)(t,Lb);let c=r.considerPlaybackRate&&(0,N.isNonNullable)(s)?s:1,d=[...t].sort($u(-1)),m=a.bitrate;(0,N.assertNonNullable)(m);let h=c*$b(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,g=Ys(a,e,t,r.minVideoAudioRatio),S=l||i;(0,N.isNonNullable)(S)&&isFinite(S)&&(f=d.find(x=>(0,N.isNonNullable)(x.bitrate)&&(0,N.isNonNullable)(g==null?void 0:g.bitrate)?S-m>=x.bitrate*h&&x.bitrate>=g.bitrate:!1)),f||(f=g);let y=o==null?void 0:o.last,E=f&&Mb(r,u,f,o);return(0,N.isNonNullable)(o)&&(E==null?void 0:E.bitrate)!==(y==null?void 0:y.bitrate)&&u({message:`
40
+ [best video track] ${O==null?void 0:O.quality}
41
+ [selected video track] ${N==null?void 0:N.quality}
42
+ `}),N},eu=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f,panelSize:b})=>{var ne,K,M,z,D;(0,$.assertNotEmptyArray)(s,Jo);let{containerSizeFactor:S,containerSizeLimit:v}=IS({container:e,tuning:i,limits:r,panelSize:b}),y=i.considerPlaybackRate&&(0,$.isNonNullable)(o)?o:1,x=s.filter(R=>!(0,$.isInvariantQuality)(R.quality)).sort((R,C)=>(0,$.isHigher)(R.quality,C.quality)?-1:1),A=(ne=(0,ft.default)(x,-1))==null?void 0:ne.quality,w=(K=(0,ft.default)(x,0))==null?void 0:K.quality,L=Kr(r,w,A),q=y*Xo(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),F={},B=x.filter(R=>{let C=!0;if(v)if(R.size)C=R.size.width<=v.width&&R.size.height<=v.height;else{let Ot=v&&(0,$.videoSizeToQuality)(v);C=Ot?(0,$.isLowerOrEqual)(R.quality,Ot):!0}if(!C)return F[R.quality]="FitsContainer",!1;let Le=h||t,It=(0,$.isNonNullable)(Le)&&isFinite(Le)&&(0,$.isNonNullable)(R.bitrate)?Le-a>=R.bitrate*q:!0,xt=Yo(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===R.quality;if(!It&&!xt)return F[R.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,$.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,$.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,$.isHigher)(R.quality,u.quality))return F[R.quality]="Buffer",!1;if(!!c&&(0,$.isHigherOrEqual)(R.quality,c)&&!xt)return F[R.quality]="DroppedFramesLimit",!1;if(!!p&&(0,$.isHigherOrEqual)(R.quality,p)&&!xt)return F[R.quality]="StallsLimit",!1;let _e=L||((0,$.isNullable)(r==null?void 0:r.max)||(0,$.isLowerOrEqual)(R.quality,r.max))&&((0,$.isNullable)(r==null?void 0:r.min)||(0,$.isHigherOrEqual)(R.quality,r.min)),Xe=(0,$.isNonNullable)(d)&&!d?(0,$.isLowerOrEqual)(R.quality,i.backgroundVideoQualityLimit):!0;return!_e||!Xe?(F[R.quality]="FitsQualityLimits",!1):!0})[0];B&&B.bitrate&&DR.next(B.bitrate);let H=(M=B!=null?B:(0,ft.default)(x,-1))!=null?M:s[0],N=l==null?void 0:l.last,_=Zo(i,f,H,l);return(0,$.isNonNullable)(l)&&_.quality!==(N==null?void 0:N.quality)&&f({message:`
43
+ [VIDEO TRACKS ABR]
44
+ [available video tracks]
45
+ ${s.map(R=>{var C,Le;return`{ id: ${R.id}, quality: ${R.quality}, bitrate: ${R.bitrate}, size: ${(C=R.size)==null?void 0:C.width}:${(Le=R.size)==null?void 0:Le.height} }`}).join(`
46
+ `)}
47
+
48
+ [tuning]
49
+ ${(0,yr.default)(i!=null?i:{}).map(([R,C])=>`${R}: ${C}`).join(`
50
+ `)}
51
+
52
+ [limit params]
53
+ containerSizeFactor: ${S},
54
+ containerSizeLimit: ${(z=v==null?void 0:v.width)!=null?z:0} x ${(D=v==null?void 0:v.height)!=null?D:0},
55
+ estimatedThroughput: ${t},
56
+ stallsPredictedThroughput: ${h},
57
+ reserve: ${a},
58
+ playbackRate: ${o},
59
+ playbackRateFactor: ${y},
60
+ forwardBufferHealth: ${n},
61
+ bitrateFactor: ${q},
62
+ minBufferToSwitchUp: ${i.minBufferToSwitchUp},
63
+ droppedVideoMaxQualityLimit: ${c},
64
+ stallsVideoMaxQualityLimit: ${p},
65
+ limitsAreInvalid: ${L},
66
+ maxQualityLimit: ${r==null?void 0:r.max},
67
+ minQualityLimit: ${r==null?void 0:r.min},
68
+
69
+ [limited video tracks]
70
+ ${(0,yr.default)(F).map(([R,C])=>`${R}: ${C}`).join(`
71
+ `)||"All tracks are available"}
72
+
73
+ [best video track] ${B==null?void 0:B.quality}
74
+ [selected video track] ${_==null?void 0:_.quality}
75
+ `}),_},tu=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{(0,$.assertNotEmptyArray)(t,Jo);let d=r.considerPlaybackRate&&(0,$.isNonNullable)(a)?a:1,c=[...t].sort(Xr(-1)),p=s.bitrate;(0,$.assertNonNullable)(p);let h=d*Xo(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,b=Aa(s,e,t,r.minVideoAudioRatio),S=l||i;(0,$.isNonNullable)(S)&&isFinite(S)&&(f=c.find(x=>(0,$.isNonNullable)(x.bitrate)&&(0,$.isNonNullable)(b==null?void 0:b.bitrate)?S-p>=x.bitrate*h&&x.bitrate>=b.bitrate:!1)),f||(f=b);let v=o==null?void 0:o.last,y=f&&Zo(r,u,f,o);return(0,$.isNonNullable)(o)&&(y==null?void 0:y.bitrate)!==(v==null?void 0:v.bitrate)&&u({message:`
43
76
  [AUDIO TRACKS ABR]
44
77
  [available audio tracks]
45
78
  ${t.map(x=>`{ id: ${x.id}, bitrate: ${x.bitrate} }`).join(`
46
79
  `)}
47
80
 
48
81
  [tuning]
49
- ${(0,Ws.default)(r!=null?r:{}).map(([x,w])=>`${x}: ${w}`).join(`
82
+ ${(0,yr.default)(r!=null?r:{}).map(([x,A])=>`${x}: ${A}`).join(`
50
83
  `)}
51
84
 
52
85
  [limit params]
53
86
  estimatedThroughput: ${i},
54
87
  stallsPredictedThroughput: ${l},
55
- reserve: ${m},
56
- playbackRate: ${s},
57
- playbackRateFactor: ${c},
88
+ reserve: ${p},
89
+ playbackRate: ${a},
90
+ playbackRateFactor: ${d},
58
91
  forwardBufferHealth: ${n},
59
92
  bitrateFactor: ${h},
60
93
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
61
94
 
62
- [selected audio track] ${E==null?void 0:E.id}
63
- `}),E};var Te=a=>new URL(a).hostname;var O=require("@vkontakte/videoplayer-shared/es2018");var Nb=j(Wt(),1);var Vb=j(Ye(),1),Cb=a=>{if(a instanceof DOMException&&(0,Vb.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Ne=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!Cb(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return Cb(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};var Qe=require("@vkontakte/videoplayer-shared/es2018");var Ob=j(Ki(),1),gt=require("@vkontakte/videoplayer-shared/es2018");function Ie(){return(0,gt.now)()}function Lu(a){return Ie()-a}function Mu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Bb(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Ji(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,m=!1,h="arraybuffer",f=7e3,g=2e3,S=()=>{if(u)return;(0,gt.assertNonNullable)(c);let _=Lu(c),C;if(_<g){C=g-_,setTimeout(S,C);return}g*=2,g>f&&(g=f),n&&n.abort(),n=new r,V()},y=_=>(s=_,Z),E=_=>(d=_,Z),x=()=>(h="json",Z),w=()=>{if(!u){if(--l>=0){S(),i&&i();return}u=!0,d&&d(),t&&t()}},P=_=>(m=_,Z),V=()=>{c=Ie(),n=new r,n.open("get",a);let _=0,C,re=0,ge=()=>((0,gt.assertNonNullable)(c),Math.max(c,Math.max(C||0,re||0)));if(s&&n.addEventListener("progress",L=>{let Y=Ie();s.updateChunk&&L.loaded>_&&(s.updateChunk(ge(),L.loaded-_),_=L.loaded,C=Y)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;(0,gt.assertNonNullable)(n);let L=n.status;if(L>=200&&L<300){let{response:Y,responseType:ae}=n,k=Y==null?void 0:Y.byteLength;if(typeof k=="number"&&s){let B=k-_;B&&s.updateChunk&&s.updateChunk(ge(),B)}ae==="json"&&(!Y||!(0,Ob.default)(Y).length)?w():(d&&d(),e(Y))}else w()}),n.addEventListener("error",()=>{w()}),m){let L=()=>{(0,gt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(re=Ie(),n.removeEventListener("readystatechange",L))};n.addEventListener("readystatechange",L)}return n.responseType=h,n.send(),Z},Z={withBitrateReporting:y,withParallel:P,withJSONResponse:x,withRetryCount:_=>(l=_,Z),withRetryInterval:(_,C)=>((0,gt.isNonNullable)(_)&&(g=_),(0,gt.isNonNullable)(C)&&(f=C),Z),withTimeout:_=>(o=_,Z),withFinally:E,send:V,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return Z}var Qr=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var _b=j(Ki(),1);var Gr=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Ie(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=Ie()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ji(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Ie()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=Ie();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,_b.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Fb=require("@vkontakte/videoplayer-shared/es2018");var zs=1e4,Du=3;var NA=6e4,FA=10,qA=1,UA=500,Wr=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new Fb.Subject,this.chunkRateEstimator=new Qr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Mu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Mu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(K.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Ab({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Nb.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Qe.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Bb(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Gr(Du,zs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let w=s&&(!c||c===this.rep);return w||t("Not running!"),w},m=(w,P,V)=>{u&&u.abort(),u=Ji(this.urlResolver.resolve(w,!1),P,V,()=>this._retryCallback()).withTimeout(zs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Du).withFinally(()=>{u=null}).send()},h=(w,P,V)=>{(0,Qe.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),P,V,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=w=>{let P=i.playbackRate;i.playbackRate!==w&&(t(`Playback rate switch: ${P}=>${w}`),i.playbackRate=w)},g=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let V=Ie()-1e4,J=0;for(let X=0;X<this.bufferStates.length;X++){let $=this.bufferStates[X];w=Math.min(w,$.buf),$.ts<V&&J++}this.bufferStates.splice(0,J),t(`update playback rate; minBuffer=${w} drop=${J} jitter=${this.sourceJitter}`);let W=w-qA;this.sourceJitter>=0?W-=this.sourceJitter/2:this.sourceJitter-=1,W>3?f(1.15):W>1?f(1.1):W>.3?f(1.05):f(1)}},y=w=>{let P,V=()=>P&&P.start?P.start.length:0,J=L=>P.start[L]/1e3,W=L=>P.dur[L]/1e3,X=L=>P.fragIndex+L,$=(L,Y)=>({chunkIdx:X(L),startTS:J(L),dur:W(L),discontinuity:Y}),Z=()=>{let L=0;if(P&&P.dur){let Y=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ae=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,k=Y;this.sourceJitter>1&&(k+=this.sourceJitter-1);let B=P.dur.length-1;for(;B>=0&&(k-=P.dur[B],!(k<=0));--B);L=Math.min(B,P.dur.length-1-ae),L=Math.max(L,0)}return $(L,!0)},_=L=>{let Y=V();if(!(Y<=0)){if((0,Qe.isNonNullable)(L)){for(let ae=0;ae<Y;ae++)if(J(ae)>L)return $(ae)}return Z()}},C=L=>{let Y=V(),ae=L?L.chunkIdx+1:0,k=ae-P.fragIndex;if(!(Y<=0)){if(!L||k<0||k-Y>FA)return t(`Resync: offset=${k} bChunks=${Y} chunk=`+JSON.stringify(L)),Z();if(!(k>=Y))return $(ae-P.fragIndex,!1)}},re=(L,Y,ae)=>{l&&l.abort(),l=Ji(this.urlResolver.resolve(L,!0,this.lowLatency),Y,ae,()=>this._retryCallback()).withTimeout(zs).withRetryCount(Du).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(L,Y)=>{re(w,ae=>{if(!d())return;P=ae;let k=!!P.lowLatency;k!==this.lowLatency&&g(k);let B=0;for(let Ee=0;Ee<P.dur.length;++Ee)B+=P.dur[Ee];B>0&&((0,Qe.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(B/P.dur.length)),r({name:"index",zeroTime:P.zeroTime,shiftDuration:P.shiftDuration}),this.sourceJitter=P.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,P.jitter/1e3)):1,L(_(Y))},()=>this._handleNetworkError())},nextChunk:C}},E=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Qe.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:w=>{let{videoElement:P,logger:V}=this.params,J=y(e.jidxUrl),W,X,$,Z,_=0,C,re,ge,L=()=>{C&&(clearTimeout(C),C=void 0);let ie=Math.max(UA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ke=_+ie,Me=Ie(),De=Math.min(1e4,ke-Me);_=Me;let lt=()=>{l||d()&&J.seek(()=>{d()&&(_=Ie(),Y(),L())})};De>0?C=window.setTimeout(()=>{this.paused?L():lt()},De):lt()},Y=()=>{let ie;for(;ie=J.nextChunk(Z);)Z=ie,Ei(ie);let ke=J.nextChunk($);if(ke){if($&&ke.discontinuity){V("Detected discontinuity; restarting playback"),this.paused?L():(E(),this._initPlayerWith(e));return}Ee(ke)}else L()},ae=(ie,ke)=>{if(!d()||!this.sourceBuffer)return;let Me,De,lt,Tt=Ct=>{window.setTimeout(()=>{d()&&ae(ie,ke)},Ct)};if(this.sourceBuffer.updating)V("Source buffer is updating; delaying appendBuffer"),Tt(100);else{let Ct=Ie(),ei=P.currentTime;!this.paused&&P.buffered.length>1&&re===ei&&Ct-ge>500&&(V("Stall suspected; trying to fix"),this._fixupStall()),re!==ei&&(re=ei,ge=Ct);let xi=this._getBufferSizeSec();if(xi>30)V(`Buffered ${xi} seconds; delaying appendBuffer`),Tt(2e3);else try{this.sourceBuffer.appendBuffer(ie),this.videoPlayStarted?(this.bufferStates.push({ts:Ct,buf:xi}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ke&&ke()}catch(ur){if(ur.name==="QuotaExceededError")V("QuotaExceededError; delaying appendBuffer"),lt=this.sourceBuffer.buffered.length,lt!==0&&(Me=this.sourceBuffer.buffered.start(0),De=ei,De-Me>4&&this.sourceBuffer.remove(Me,De-3)),Tt(1e3);else throw ur}}},k=()=>{X&&W&&(V([`Appending chunk, sz=${X.byteLength}:`,JSON.stringify($)]),ae(X,function(){X=null,Y()}))},B=ie=>e.fragUrlTemplate.replace("%%id%%",ie.chunkIdx),Ee=ie=>{d()&&h(B(ie),(ke,Me)=>{if(d()){if(Me/=1e3,X=ke,$=ie,n=ie.startTS,Me){let De=Math.min(10,ie.dur/Me);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*De:De}k()}},()=>this._handleNetworkError())},Ei=ie=>{d()&&((0,Qe.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(B(ie),!1)))},yt=ie=>{d()&&(e.cachedHeader=ie,ae(ie,()=>{W=!0,k()}))};s=!0,J.seek(ie=>{if(d()){if(_=Ie(),!ie){L();return}Z=ie,!(0,Qe.isNullable)(w)||ie.startTS>w?Ee(ie):($=ie,Y())}},w),e.cachedHeader?yt(e.cachedHeader):m(e.headerUrl,yt,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,Qe.isNonNullable)(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Qe.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Qe.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let m,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}m=this._selectQuality(d),m?this._switchToQuality(m):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(m,h)=>{let f=Ie();if(this.chunkRateEstimator.addInterval(m,f,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-m,speed:S}),!0}},get:()=>{let m=this.chunkRateEstimator.getBitRate();return m?m*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Lu(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,m)=>{let h=s.updateChunk(d,m);return h&&l(),h},notifySwitch:d=>{let m=Ie();d<o&&(n=m),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Ji(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(zs).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Ne(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},NA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var qb=j(Fi(),1),de=require("@vkontakte/videoplayer-shared/es2018"),Cu=class{constructor(){this.onDroopedVideoFramesLimit$=new de.Subject;this.subscription=new de.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new de.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,de.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,de.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,de.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,de.interval)(this.droppedFramesChecker.checkTime).pipe((0,de.filter)(()=>this.playing),(0,de.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,de.debounce)(this.droppedFramesChecker.checkTime)),i=(0,de.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,qb.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,de.isLower)(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Ks=Cu;var Xs=require("@vkontakte/videoplayer-shared/es2018"),Ub=require("@vkontakte/videoplayer-shared/es2018");var Yr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var HA=(a,e)=>new Xs.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Yr()))},{...i,...e});r.observe(a);let s=(0,Ub.fromEvent)(document,"visibilitychange").pipe((0,Xs.map)(n=>!document.hidden||Yr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Xe=HA;var jA=["paused","playing","ready"],QA=["paused","playing","ready"],zr=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new Q("stopped");this.representations$=new O.ValueSubject([]);this.droppedFramesManager=new Ks;this.maxSeekBackTime$=new O.ValueSubject(1/0);this.zeroTime$=new O.ValueSubject(void 0);this.liveOffset=new bi;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:O.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(i=Gt(u.name))!=null?i:(0,O.videoSizeToQuality)(u.video),d=u.bitrate/1e3,m={...u.video};if(!c)continue;let h={id:l,quality:c,bitrate:d,size:m};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,O.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Vu.default)(QA,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,Vu.default)(jA,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(we(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(we(this.params.source.url,u))}return;default:return(0,O.assertNever)(e)}};this.textTracksManager=new Ke(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:O.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,O.merge)(this.videoState.stateChangeStarted$.pipe((0,O.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,O.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ve(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=_e(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,O.map)(r=>r.map(({track:s})=>s)),(0,O.filter)(r=>!!r.length),(0,O.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,O.filterChanged)(),(0,O.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,O.combine)({zeroTime:this.zeroTime$.pipe((0,O.filter)(O.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(bt(this.video,this.params.desiredState.isLooped,t)).add(Be(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ze(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Xe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&(0,O.videoQualityToHeight)(r),min:s&&(0,O.videoQualityToHeight)(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,O.assertNever)(r.to)}},t)).add((0,O.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.observableFrom)(["init"])).pipe((0,O.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Oe(this.video)}createLiveDashPlayer(){let e=new Wr({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,m,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(m=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?m:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,O.isNonNullable)(t)?t:zt(e.map(({track:g})=>g),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let g=(f=e.find(({track:S})=>S.id===s))==null?void 0:f.representation;(0,O.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;(0,O.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(we(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Hb=zr;var Xv=j(Ye(),1);var Zi=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var U=require("@vkontakte/videoplayer-shared/es2018");var Js=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},er=class extends Js{constructor(){super(),this.listeners||Js.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Kr=class{constructor(){Object.defineProperty(this,"signal",{value:new er,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Kr.prototype[Symbol.toStringTag]="AbortController",er.prototype[Symbol.toStringTag]="AbortSignal");function Zs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Ou(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Zs({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let m=new t(l,c);return d&&Object.defineProperty(m,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),m},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let m=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([m,n(u,l)])}return n(u,l)},Request:s}}var Xr=Zs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),jb=Xr?Ou({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,vt=Xr?jb.fetch:window.fetch,PV=Xr?jb.Request:window.Request,Ae=Xr?Kr:window.AbortController,wV=Xr?er:window.AbortSignal;var pl=j(_u(),1);var $g=j(Rg(),1),tr=require("@vkontakte/videoplayer-shared/es2018"),Lg=a=>{if(!a)return{id:"EmptyResponse",category:tr.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:tr.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,$g.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:tr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:tr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:tr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Kt=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared/es2018");var en=j(Ye(),1),ar=j(Wt(),1),tn=j(_u(),1);var $k=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Lk=a=>window.clearTimeout(a),Mg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Dg=!Mg(window.requestIdleCallback)||!Mg(window.cancelIdleCallback),Hu=Dg?$k:window.requestIdleCallback,Zr=Dg?Lk:window.cancelIdleCallback;var Nv=j(Bs(),1);var Xt=require("@vkontakte/videoplayer-shared/es2018");var Mk=18,Cg=!1;try{Cg=K.browser.isSafari&&!!K.browser.safariVersion&&K.browser.safariVersion<=Mk}catch(a){console.error(a)}var ju=class{constructor(e){this.bufferFull$=new Xt.Subject;this.error$=new Xt.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Xt.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Cg&&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(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Xt.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Xt.assertNever)(t)}}},Vg=ju;var Qu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var I=require("@vkontakte/videoplayer-shared/es2018");var ee=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r)}get id(){return this.type}get size(){return this.size32}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 ir=class extends ee{};var ea=class extends ee{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ta=class extends ee{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var ia=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ue=class extends ee{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ra=class extends ue{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var aa=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var sa=class extends ee{constructor(e,t){super(e,t),this.data=this.content}};var gi=class extends ue{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var na=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var oa=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ua=class extends ue{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var la=class extends ue{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ca=class extends ue{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var da=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends ue{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ha=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ma=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends ue{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ba=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=class extends ue{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var va=class extends ue{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Sa=class extends ue{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var ya=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends ue{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Ia=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var Ck={ftyp:ta,moov:ia,mvhd:ra,moof:aa,mdat:sa,sidx:gi,trak:na,mdia:da,mfhd:fa,tkhd:pa,traf:ba,tfhd:ga,tfdt:va,trun:Sa,minf:ha,sv3d:oa,st3d:ua,prhd:la,proj:ma,equi:ca,uuid:ea,stbl:ya,stsd:Ta,avc1:Ia,unknown:ir},kt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=Ck[e];return i?new i(t,new a):new ir(t,new a)}};var Jt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Ok=new TextDecoder("ascii"),Bk=a=>Ok.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",_k=a=>{let e=new gi(a,new kt),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})},Nk=(a,e)=>{let i=new kt().parse(a),r=new Jt(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},Fk=a=>{let t=new kt().parse(a),i=new Jt(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},qk=a=>{var r;let t=new kt().parse(a);return(r=new Jt(t).find("sidx"))==null?void 0:r.timescale},Uk=(a,e)=>{let i=new kt().parse(a),s=new Jt(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,m)=>d+m,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Hk=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 kt().parse(a),r=new Jt(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},Og={validateData:Bk,parseInit:Hk,getIndexRange:()=>{},parseSegments:_k,parseFeedableSegmentChunk:Nk,getChunkEndTime:Uk,getServerLatencyTimestamps:Fk,getTimescaleFromIndex:qk};var xa=j(Ye(),1),Rt=require("@vkontakte/videoplayer-shared/es2018");var _g=require("@vkontakte/videoplayer-shared/es2018");var Bg={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"}},Ng=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=Ea(a,t),r=i in Bg,s=r?Bg[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=Ea(u),d=l*2**((o-1)*8)+c,m=t+o,h;return m+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+m):h=new DataView(a.buffer,a.byteOffset+m,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:m,tagSize:m+d,value:h,valueSize:d}},Ea=(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},ot=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ea(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,_g.assertNever)(e)}},vi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Ng(i);if(!e(r))return;r.type==="master"&&vi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Fg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Ng(a);return vi(r.value,({tag:s,type:n,value:o})=>(s===17143?e=ot(o,n):s===17026?t=ot(o,n):s===17029&&(i=ot(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var qg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],jk=[231,22612,22743,167,171,163,160,175],Qk=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return vi(a,({tag:m,type:h,value:f,valueSize:g})=>{if(m===21419){let S=ot(f,h);l=Ea(S)}else m!==21420&&(l=void 0);return m===408125543?(e=f.byteOffset,t=f.byteOffset+g):m===357149030?s=!0:m===290298740?n=!0:m===2807729?i=ot(f,h):m===17545?r=ot(f,h):m===21420&&l===475249515?u=ot(f,h):m===374648427?vi(f,({tag:S,type:y,value:E})=>S===30321?(c=ot(E,y)===1,!1):!0):s&&n&&(0,xa.default)(qg,m)&&(o=!0),!o}),(0,Rt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Rt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Rt.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Gk=a=>{if((0,Rt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Wk=(a,e)=>{let t=!1,i=!1,r=o=>(0,Rt.isNonNullable)(o.time)&&(0,Rt.isNonNullable)(o.position),s=[],n;return vi(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=ot(l,u));break;case 183:break;case 241:n&&(n.position=ot(l,u));break;default:t&&(0,xa.default)(qg,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Yk=a=>{let e=0,t=!1;try{vi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,xa.default)(jk,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,xa.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Ug={validateData:Fg,parseInit:Qk,getIndexRange:Gk,parseSegments:Wk,parseFeedableSegmentChunk:Yk};var Pa=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Ug;case"mp4":return Og}}throw new ReferenceError(`Unsupported mime type ${a}`)};var al=j(uv(),1),Cv=j(Fi(),1),Vv=j(xv(),1),Ov=j(Wt(),1),sl=j(Ki(),1);var Pv=j(Ye(),1),Ju=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,Pv.default)(["6E","7A","F4"],o)}}return!1};var Aa=require("@vkontakte/videoplayer-shared/es2018");var wv=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Av=a=>{var e;try{let t=HR(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function HR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
64
- (?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
95
+ [selected audio track] ${y==null?void 0:y.id}
96
+ `}),y},iu=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{(0,$.assertNotEmptyArray)(t,Jo);let d=r.considerPlaybackRate&&(0,$.isNonNullable)(a)?a:1,c=SS.get(t);c||(c=[...t].sort(Xr(-1)),SS.set(t,c));let p=s.bitrate;(0,$.assertNonNullable)(p);let h=d*Xo(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,b=Pa(s,e,t,r.minVideoAudioRatio),S=l||i;(0,$.isNonNullable)(S)&&isFinite(S)&&(f=c.find(x=>(0,$.isNonNullable)(x.bitrate)&&(0,$.isNonNullable)(b==null?void 0:b.bitrate)?S-p>=x.bitrate*h&&x.bitrate>=b.bitrate:!1)),f||(f=b);let v=o==null?void 0:o.last,y=f&&Zo(r,u,f,o);return(0,$.isNonNullable)(o)&&(y==null?void 0:y.bitrate)!==(v==null?void 0:v.bitrate)&&u({message:`
97
+ [AUDIO TRACKS ABR]
98
+ [available audio tracks]
99
+ ${t.map(x=>`{ id: ${x.id}, bitrate: ${x.bitrate} }`).join(`
100
+ `)}
101
+
102
+ [tuning]
103
+ ${(0,yr.default)(r!=null?r:{}).map(([x,A])=>`${x}: ${A}`).join(`
104
+ `)}
105
+
106
+ [limit params]
107
+ estimatedThroughput: ${i},
108
+ stallsPredictedThroughput: ${l},
109
+ reserve: ${p},
110
+ playbackRate: ${a},
111
+ playbackRateFactor: ${d},
112
+ forwardBufferHealth: ${n},
113
+ bitrateFactor: ${h},
114
+ minBufferToSwitchUp: ${r.minBufferToSwitchUp},
115
+
116
+ [selected audio track] ${y==null?void 0:y.id}
117
+ `}),y};var qe=s=>new URL(s).hostname;var X=require("@vkontakte/videoplayer-shared/es2018");var kS=Y(Zt(),1);var ES=Y(_t(),1),xS=s=>{if(s instanceof DOMException&&(0,ES.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},st=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!xS(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return xS(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};var Ct=require("@vkontakte/videoplayer-shared/es2018");var wS=Y(Sr(),1),di=require("@vkontakte/videoplayer-shared/es2018");function Ke(){return(0,di.now)()}function Jc(s){return Ke()-s}function Zc(s){let e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function AS(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Jr(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,d,c,p=!1,h="arraybuffer",f=7e3,b=2e3,S=()=>{if(u)return;(0,di.assertNonNullable)(d);let N=Jc(d),_;if(N<b){_=b-N,setTimeout(S,_);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new r,L()},v=N=>(a=N,H),y=N=>(c=N,H),x=()=>(h="json",H),A=()=>{if(!u){if(--l>=0){S(),i&&i();return}u=!0,c&&c(),t&&t()}},w=N=>(p=N,H),L=()=>{d=Ke(),n=new r,n.open("get",s);let N=0,_,ne=0,K=()=>((0,di.assertNonNullable)(d),Math.max(d,Math.max(_||0,ne||0)));if(a&&n.addEventListener("progress",M=>{let z=Ke();a.updateChunk&&M.loaded>N&&(a.updateChunk(K(),M.loaded-N),N=M.loaded,_=z)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>A())),n.addEventListener("load",()=>{if(u)return;(0,di.assertNonNullable)(n);let M=n.status;if(M>=200&&M<300){let{response:z,responseType:D}=n,R=z==null?void 0:z.byteLength;if(typeof R=="number"&&a){let C=R-N;C&&a.updateChunk&&a.updateChunk(K(),C)}D==="json"&&(!z||!(0,wS.default)(z).length)?A():(c&&c(),e(z))}else A()}),n.addEventListener("error",()=>{A()}),p){let M=()=>{(0,di.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ne=Ke(),n.removeEventListener("readystatechange",M))};n.addEventListener("readystatechange",M)}return n.responseType=h,n.send(),H},H={withBitrateReporting:v,withParallel:w,withJSONResponse:x,withRetryCount:N=>(l=N,H),withRetryInterval:(N,_)=>((0,di.isNonNullable)(N)&&(b=N),(0,di.isNonNullable)(_)&&(f=_),H),withTimeout:N=>(o=N,H),withFinally:y,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return H}var ka=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var PS=Y(Sr(),1);var Ra=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Ke(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Ke()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Jr(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Ke()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=Ke();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,PS.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var RS=require("@vkontakte/videoplayer-shared/es2018");var ru=1e4,ed=3;var OR=6e4,_R=10,FR=1,NR=500,La=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new RS.Subject,this.chunkRateEstimator=new ka(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Zc(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Zc(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(J.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!gS({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,kS.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Ct.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{AS(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ra(ed,ru,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let A=a&&(!d||d===this.rep);return A||t("Not running!"),A},p=(A,w,L)=>{u&&u.abort(),u=Jr(this.urlResolver.resolve(A,!1),w,L,()=>this._retryCallback()).withTimeout(ru).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ed).withFinally(()=>{u=null}).send()},h=(A,w,L)=>{(0,Ct.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(A,!1),w,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=A=>{let w=i.playbackRate;i.playbackRate!==A&&(t(`Playback rate switch: ${w}=>${A}`),i.playbackRate=A)},b=A=>{this.lowLatency=A,t(`lowLatency changed to ${A}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let A=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let L=Ke()-1e4,q=0;for(let O=0;O<this.bufferStates.length;O++){let B=this.bufferStates[O];A=Math.min(A,B.buf),B.ts<L&&q++}this.bufferStates.splice(0,q),t(`update playback rate; minBuffer=${A} drop=${q} jitter=${this.sourceJitter}`);let F=A-FR;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?f(1.15):F>1?f(1.1):F>.3?f(1.05):f(1)}},v=A=>{let w,L=()=>w&&w.start?w.start.length:0,q=M=>w.start[M]/1e3,F=M=>w.dur[M]/1e3,O=M=>w.fragIndex+M,B=(M,z)=>({chunkIdx:O(M),startTS:q(M),dur:F(M),discontinuity:z}),H=()=>{let M=0;if(w&&w.dur){let z=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,D=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,R=z;this.sourceJitter>1&&(R+=this.sourceJitter-1);let C=w.dur.length-1;for(;C>=0&&(R-=w.dur[C],!(R<=0));--C);M=Math.min(C,w.dur.length-1-D),M=Math.max(M,0)}return B(M,!0)},N=M=>{let z=L();if(!(z<=0)){if((0,Ct.isNonNullable)(M)){for(let D=0;D<z;D++)if(q(D)>M)return B(D)}return H()}},_=M=>{let z=L(),D=M?M.chunkIdx+1:0,R=D-w.fragIndex;if(!(z<=0)){if(!M||R<0||R-z>_R)return t(`Resync: offset=${R} bChunks=${z} chunk=`+JSON.stringify(M)),H();if(!(R>=z))return B(D-w.fragIndex,!1)}},ne=(M,z,D)=>{l&&l.abort(),l=Jr(this.urlResolver.resolve(M,!0,this.lowLatency),z,D,()=>this._retryCallback()).withTimeout(ru).withRetryCount(ed).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(M,z)=>{ne(A,D=>{if(!c())return;w=D;let R=!!w.lowLatency;R!==this.lowLatency&&b(R);let C=0;for(let Le=0;Le<w.dur.length;++Le)C+=w.dur[Le];C>0&&((0,Ct.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(C/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,M(N(z))},()=>this._handleNetworkError())},nextChunk:_}},y=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ct.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:A=>{let{videoElement:w,logger:L}=this.params,q=v(e.jidxUrl),F,O,B,H,N=0,_,ne,K,M=()=>{_&&(clearTimeout(_),_=void 0);let de=Math.max(NR,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ve=N+de,Oe=Ke(),_e=Math.min(1e4,Ve-Oe);N=Oe;let Xe=()=>{l||c()&&q.seek(()=>{c()&&(N=Ke(),z(),M())})};_e>0?_=window.setTimeout(()=>{this.paused?M():Xe()},_e):Xe()},z=()=>{let de;for(;de=q.nextChunk(H);)H=de,It(de);let Ve=q.nextChunk(B);if(Ve){if(B&&Ve.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?M():(y(),this._initPlayerWith(e));return}Le(Ve)}else M()},D=(de,Ve)=>{if(!c()||!this.sourceBuffer)return;let Oe,_e,Xe,Ot=qt=>{window.setTimeout(()=>{c()&&D(de,Ve)},qt)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),Ot(100);else{let qt=Ke(),ri=w.currentTime;!this.paused&&w.buffered.length>1&&ne===ri&&qt-K>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),ne!==ri&&(ne=ri,K=qt);let fi=this._getBufferSizeSec();if(fi>30)L(`Buffered ${fi} seconds; delaying appendBuffer`),Ot(2e3);else try{this.sourceBuffer.appendBuffer(de),this.videoPlayStarted?(this.bufferStates.push({ts:qt,buf:fi}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ve&&Ve()}catch(ji){if(ji.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),Xe=this.sourceBuffer.buffered.length,Xe!==0&&(Oe=this.sourceBuffer.buffered.start(0),_e=ri,_e-Oe>4&&this.sourceBuffer.remove(Oe,_e-3)),Ot(1e3);else throw ji}}},R=()=>{O&&F&&(L([`Appending chunk, sz=${O.byteLength}:`,JSON.stringify(B)]),D(O,function(){O=null,z()}))},C=de=>e.fragUrlTemplate.replace("%%id%%",de.chunkIdx),Le=de=>{c()&&h(C(de),(Ve,Oe)=>{if(c()){if(Oe/=1e3,O=Ve,B=de,n=de.startTS,Oe){let _e=Math.min(10,de.dur/Oe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*_e:_e}R()}},()=>this._handleNetworkError())},It=de=>{c()&&((0,Ct.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(C(de),!1)))},xt=de=>{c()&&(e.cachedHeader=de,D(de,()=>{F=!0,R()}))};a=!0,q.seek(de=>{if(c()){if(N=Ke(),!de){M();return}H=de,!(0,Ct.isNullable)(A)||de.startTS>A?Le(de):(B=de,z())}},A),e.cachedHeader?xt(e.cachedHeader):p(e.headerUrl,xt,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,Ct.isNonNullable)(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Ct.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ct.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),f=c/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(p,h)=>{let f=Ke();if(this.chunkRateEstimator.addInterval(p,f,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Jc(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=a.updateChunk(c,p);return h&&l(),h},notifySwitch:c=>{let p=Ke();c<o&&(n=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Jr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ru).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;st(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var d,c;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((c=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&c.call(d,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},OR))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var LS=Y(pr(),1),ke=require("@vkontakte/videoplayer-shared/es2018"),td=class{constructor(){this.onDroopedVideoFramesLimit$=new ke.Subject;this.subscription=new ke.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ke.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,ke.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&(0,ke.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,ke.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ke.interval)(this.droppedFramesChecker.checkTime).pipe((0,ke.filter)(()=>this.playing),(0,ke.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,ke.debounce)(this.droppedFramesChecker.checkTime)),i=(0,ke.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,LS.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>(0,ke.isLower)(a,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Zr=td;var su=require("@vkontakte/videoplayer-shared/es2018"),MS=require("@vkontakte/videoplayer-shared/es2018");var Ma=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var UR=(s,e)=>new su.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ma()))},{...i,...e});r.observe(s);let a=(0,MS.fromEvent)(document,"visibilitychange").pipe((0,su.map)(n=>!document.hidden||Ma())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),vt=UR;var qR=["paused","playing","ready"],jR=["paused","playing","ready"],$a=class{constructor(e){this.subscription=new X.Subscription;this.videoState=new te("stopped");this.representations$=new X.ValueSubject([]);this.droppedFramesManager=new Zr;this.maxSeekBackTime$=new X.ValueSubject(1/0);this.zeroTime$=new X.ValueSubject(void 0);this.liveOffset=new vr;this._dashCb=e=>{var t,i,r,a;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:X.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),d=(i=li(u.name))!=null?i:(0,X.videoSizeToQuality)(u.video),c=u.bitrate/1e3,p={...u.video};if(!d)continue;let h={id:l,quality:d,bitrate:c,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(a=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:a.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,X.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,id.default)(jR,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,id.default)(qR,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(De(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(De(this.params.source.url,u))}return;default:return(0,X.assertNever)(e)}};this.textTracksManager=new St(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:X.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,X.merge)(this.videoState.stateChangeStarted$.pipe((0,X.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,X.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=et(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=rt(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,X.map)(r=>r.map(({track:a})=>a)),(0,X.filter)(r=>!!r.length),(0,X.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,X.filterChanged)(),(0,X.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,X.combine)({zeroTime:this.zeroTime$.pipe((0,X.filter)(X.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ft(this.video,this.params.desiredState.isLooped,t)).add(it(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(gt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(vt(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&(0,X.videoQualityToHeight)(r),min:a&&(0,X.videoQualityToHeight)(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,X.assertNever)(r.to)}},t)).add((0,X.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,X.observableFrom)(["init"])).pipe((0,X.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),tt(this.video)}createLiveDashPlayer(){let e=new La({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,p,h,f;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(p=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,X.isNonNullable)(t)?t:ci(e.map(({track:b})=>b),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let b=(f=e.find(({track:S})=>S.id===a))==null?void 0:f.representation;(0,X.assertNonNullable)(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;(0,X.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(De(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var $S=$a;var Re=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var ae=require("@vkontakte/videoplayer-shared/es2018");var au=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},es=class extends au{constructor(){super(),this.listeners||au.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Ba=class{constructor(){Object.defineProperty(this,"signal",{value:new es,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ba.prototype[Symbol.toStringTag]="AbortController",es.prototype[Symbol.toStringTag]="AbortSignal");function nu(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function rd(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!nu({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(h){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:a}}var HR=()=>"fetch"in window,Da=HR()&&nu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),BS=Da?rd({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Nt=Da?BS.fetch:window.fetch,YO=Da?BS.Request:window.Request,be=Da?Ba:window.AbortController,KO=Da?es:window.AbortSignal;var Ld=Y(Ca(),1);var vv=Y(Sv(),1),ts=require("@vkontakte/videoplayer-shared/es2018"),ou=s=>{if(!s)return{id:"EmptyResponse",category:ts.ErrorCategory.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:ts.ErrorCategory.NETWORK,message:`UV Error ${s}`};let e=(0,vv.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ts.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ts.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ts.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var at=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};var T=require("@vkontakte/videoplayer-shared/es2018");var pu=Y(_t(),1),os=Y(Zt(),1),hu=Y(Ca(),1);var RL=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},LL=s=>window.clearTimeout(s),yv=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),Tv=!yv(window.requestIdleCallback)||!yv(window.cancelIdleCallback),is=Tv?RL:window.requestIdleCallback,pi=Tv?LL:window.cancelIdleCallback;var wy=Y(xa(),1);var Xi=require("@vkontakte/videoplayer-shared/es2018");var ML=18,Iv=!1;try{Iv=J.browser.isSafari&&!!J.browser.safariVersion&&J.browser.safariVersion<=ML}catch(s){console.error(s)}var ld=class{constructor(e){this.bufferFull$=new Xi.Subject;this.error$=new Xi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Xi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};Iv&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!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(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Xi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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,Xi.assertNever)(t)}}},xv=ld;var rs=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};var k=require("@vkontakte/videoplayer-shared/es2018");var pe=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}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 ss=class extends pe{};var Oa=class extends pe{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var _a=class extends pe{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Fa=class extends pe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ye=class extends pe{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Na=class extends ye{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Ua=class extends pe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qa=class extends pe{constructor(e,t){super(e,t),this.data=this.content}};var Tr=class extends ye{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var ja=class extends pe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ha=class extends pe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ga=class extends ye{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var za=class extends ye{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Qa=class extends ye{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Wa=class extends pe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends ye{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 Ka=class extends pe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xa=class extends pe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ja=class extends ye{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Za=class extends pe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var en=class extends ye{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 tn=class extends ye{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 rn=class extends ye{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 sn=class extends pe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var an=class extends ye{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var nn=class extends pe{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var BL={ftyp:_a,moov:Fa,mvhd:Na,moof:Ua,mdat:qa,sidx:Tr,trak:ja,mdia:Wa,mfhd:Ja,tkhd:Ya,traf:Za,tfhd:en,tfdt:tn,trun:rn,minf:Ka,sv3d:Ha,st3d:Ga,prhd:za,proj:Xa,equi:Qa,uuid:Oa,stbl:sn,stsd:an,avc1:nn,unknown:ss},$i=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=BL[e];return i?new i(t,new s):new ss(t,new s)}};var Ji=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var CL=new TextDecoder("ascii"),VL=s=>CL.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",OL=s=>{let e=new Tr(s,new $i),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},_L=(s,e)=>{let i=new $i().parse(s),r=new Ji(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},FL=s=>{let t=new $i().parse(s),i=new Ji(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},NL=s=>{var r;let t=new $i().parse(s);return(r=new Ji(t).find("sidx"))==null?void 0:r.timescale},UL=(s,e)=>{let i=new $i().parse(s),a=new Ji(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},qL=s=>{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 $i().parse(s),r=new Ji(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},Ev={validateData:VL,parseInit:qL,getIndexRange:()=>{},parseSegments:OL,parseFeedableSegmentChunk:_L,getChunkEndTime:UL,getServerLatencyTimestamps:FL,getTimescaleFromIndex:NL};var un=Y(_t(),1),Bi=require("@vkontakte/videoplayer-shared/es2018");var Av=require("@vkontakte/videoplayer-shared/es2018");var wv={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"}},Pv=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=on(s,t),r=i in wv,a=r?wv[i].type:"binary",n=s.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(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=on(u),c=l*2**((o-1)*8)+d,p=t+o,h;return p+c>s.byteLength?h=new DataView(s.buffer,s.byteOffset+p):h=new DataView(s.buffer,s.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},on=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ei=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return on(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:(0,Av.assertNever)(e)}},Ir=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Pv(i);if(!e(r))return;r.type==="master"&&Ir(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},kv=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Pv(s);return Ir(r.value,({tag:a,type:n,value:o})=>(a===17143?e=ei(o,n):a===17026?t=ei(o,n):a===17029&&(i=ei(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Rv=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],jL=[231,22612,22743,167,171,163,160,175],HL=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return Ir(s,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let S=ei(f,h);l=on(S)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?a=!0:p===290298740?n=!0:p===2807729?i=ei(f,h):p===17545?r=ei(f,h):p===21420&&l===475249515?u=ei(f,h):p===374648427?Ir(f,({tag:S,type:v,value:y})=>S===30321?(d=ei(y,v)===1,!1):!0):a&&n&&(0,un.default)(Rv,p)&&(o=!0),!o}),(0,Bi.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Bi.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Bi.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},GL=s=>{if((0,Bi.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},zL=(s,e)=>{let t=!1,i=!1,r=o=>(0,Bi.isNonNullable)(o.time)&&(0,Bi.isNonNullable)(o.position),a=[],n;return Ir(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=ei(l,u));break;case 183:break;case 241:n&&(n.position=ei(l,u));break;default:t&&(0,un.default)(Rv,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},QL=s=>{let e=0,t=!1;try{Ir(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,un.default)(jL,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,un.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Lv={validateData:kv,parseInit:HL,getIndexRange:GL,parseSegments:zL,parseFeedableSegmentChunk:QL};var ln=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Lv;case"mp4":return Ev}}throw new ReferenceError(`Unsupported mime type ${s}`)};var xd=Y(bd(),1),Ty=Y(pr(),1),Iy=Y(gd(),1),xy=Y(Zt(),1),Ed=Y(Sr(),1);var dy=Y(_t(),1),ns=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,n]=r.toUpperCase(),o=a+n;return(0,dy.default)(["6E","7A","F4"],o)}}return!1};var dn=require("@vkontakte/videoplayer-shared/es2018");var uu=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var py=s=>{var e;try{let t=qM(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function qM(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
118
+ (?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
65
119
  (-(?<script>[a-z]{4}))?
66
120
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
67
121
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
68
122
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
69
123
  (?:-(?<privateuse>(?:${e})))?
70
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var el=j(Wt(),1);var kv=require("@vkontakte/videoplayer-shared/es2018"),Rv=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Gt(s):void 0)!=null?u:(0,kv.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},$v=({id:a,bitrate:e})=>({id:a,bitrate:e}),Lv=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Mv=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),tl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,el.default)(i.split("."),0),isDefault:r}),il=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,el.default)(r.split("."),0)}),rl=a=>"url"in a,Le=a=>a.type==="template",wa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Dv=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},$t=(a,e)=>{let t=a;t=(0,al.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,Cv.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,al.default)(t,n,(o,u)=>(0,Aa.isNullable)(s)?o:(0,Aa.isNullable)(u)?s:(0,Vv.default)(s,parseInt(u,10),"0"))}return t},Bv=(a,e)=>{var X,$,Z,_,C,re,ge,L,Y,ae,k,B,Ee,Ei,yt,ie,ke,Me,De,lt,Tt,Ct,ei,xi,ur,Il,El,xl,Pl,wl,Al,kl,Rl,$l,Ll,Ml,Dl,Cl,Vl,Ol,Bl,_l,Nl,Fl,ql,Ul,Hl,jl,Ql,Gl,Wl,Yl,zl,Kl,Xl,Jl,Zl,ec,tc,ic,rc;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(Ze=>{var ne,ti;return(ti=(ne=Ze.textContent)==null?void 0:ne.trim())!=null?ti:""}),o=(X=(0,Ov.default)(n,0))!=null?X:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],m=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,g=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:m?new Date(m).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let y,E=s.getAttribute("mediaPresentationDuration"),x=[...s.getElementsByTagName("Period")],w=x.reduce((Ze,ne)=>({...Ze,[ne.id]:ne.children}),{}),P=x.reduce((Ze,ne)=>({...Ze,[ne.id]:ne.getAttribute("duration")}),{});E?y=Dv(E):(0,sl.default)(P).filter(Ze=>Ze).length&&!u?y=(0,sl.default)(P).reduce((Ze,ne)=>{var ti;return Ze+((ti=Dv(ne))!=null?ti:0)},0):g&&(y=parseInt(g,10));let V=0,J=(Z=($=s.getAttribute("profiles"))==null?void 0:$.split(","))!=null?Z:[];for(let Ze of x.map(ne=>ne.id))for(let ne of w[Ze]){let ti=(_=ne.getAttribute("id"))!=null?_:"id"+(V++).toString(10),lr=(C=ne.getAttribute("mimeType"))!=null?C:"",Tn=(re=ne.getAttribute("codecs"))!=null?re:"",In=(ge=ne.getAttribute("contentType"))!=null?ge:lr==null?void 0:lr.split("/")[0],TS=(Y=(L=ne.getAttribute("profiles"))==null?void 0:L.split(","))!=null?Y:[],ac=(k=Av((ae=ne.getAttribute("lang"))!=null?ae:""))!=null?k:{},ja=(Ei=(Ee=(B=ne.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:Ee.trim())!=null?Ei:void 0,IS=ne.querySelectorAll("Representation"),ES=ne.querySelector("SegmentTemplate"),xS=(ie=(yt=ne.querySelector("Role"))==null?void 0:yt.getAttribute("value"))!=null?ie:void 0,Pi=In,he={id:ti,language:ac.language,isDefault:xS==="main",label:ja,codecs:Tn,hdr:Pi==="video"&&Ju(Tn),mime:lr,representations:[]};for(let se of IS){let Vt=(ke=se.getAttribute("lang"))!=null?ke:void 0,cr=(De=(Me=ja!=null?ja:ne.getAttribute("label"))!=null?Me:se.getAttribute("label"))!=null?De:void 0,Qa=(Ct=(Tt=(lt=se.querySelector("BaseURL"))==null?void 0:lt.textContent)==null?void 0:Tt.trim())!=null?Ct:"",ii=new URL(Qa||o,e).toString(),Ot=(ei=se.getAttribute("mimeType"))!=null?ei:lr,Ga=(ur=(xi=se.getAttribute("codecs"))!=null?xi:Tn)!=null?ur:"",Wa;if(In==="text"){let Bt=se.getAttribute("id")||"",Ya=((Il=ac.privateuse)==null?void 0:Il.includes("x-auto"))||Bt.includes("_auto"),ri=se.querySelector("SegmentTemplate");if(ri){let dr={representationId:(El=se.getAttribute("id"))!=null?El:void 0,bandwidth:(xl=se.getAttribute("bandwidth"))!=null?xl:void 0},za=parseInt((Pl=se.getAttribute("bandwidth"))!=null?Pl:"",10)/1e3,Ka=(Al=parseInt((wl=ri.getAttribute("startNumber"))!=null?wl:"",10))!=null?Al:1,wi=parseInt((kl=ri.getAttribute("timescale"))!=null?kl:"",10),En=(Rl=ri.querySelectorAll("SegmentTimeline S"))!=null?Rl:[],Ai=ri.getAttribute("media");if(!Ai)continue;let Xa=[],Ja=0,Za="",ki=0,pr=Ka,Re=0;for(let et of En){let ai=parseInt(($l=et.getAttribute("d"))!=null?$l:"",10),We=parseInt((Ll=et.getAttribute("r"))!=null?Ll:"",10)||0,_t=parseInt((Ml=et.getAttribute("t"))!=null?Ml:"",10);Re=Number.isFinite(_t)?_t:Re;let si=ai/wi*1e3,Nt=Re/wi*1e3;for(let ct=0;ct<We+1;ct++){let Ft=$t(Ai,{...dr,segmentNumber:pr.toString(10),segmentTime:(Re+ct*ai).toString(10)}),Ri=(Nt!=null?Nt:0)+ct*si,mr=Ri+si;pr++,Xa.push({time:{from:Ri,to:mr},url:Ft})}Re+=(We+1)*ai,Ja+=(We+1)*si}ki=Re/wi*1e3,Za=$t(Ai,{...dr,segmentNumber:pr.toString(10),segmentTime:Re.toString(10)});let hr={time:{from:ki,to:1/0},url:Za},It={type:"template",baseUrl:ii,segmentTemplateUrl:Ai,initUrl:"",totalSegmentsDurationMs:Ja,segments:Xa,nextSegmentBeyondManifest:hr,timescale:wi};Wa={id:Bt,kind:"text",segmentReference:It,profiles:[],duration:y,bitrate:za,mime:"",codecs:"",width:0,height:0,isAuto:Ya}}else Wa={id:Bt,isAuto:Ya,kind:"text",url:ii}}else{let Bt=(Cl=(Dl=se.getAttribute("contentType"))!=null?Dl:Ot==null?void 0:Ot.split("/")[0])!=null?Cl:In,Ya=(Ol=(Vl=ne.getAttribute("profiles"))==null?void 0:Vl.split(","))!=null?Ol:[],ri=parseInt((Bl=se.getAttribute("width"))!=null?Bl:"",10),dr=parseInt((_l=se.getAttribute("height"))!=null?_l:"",10),za=parseInt((Nl=se.getAttribute("bandwidth"))!=null?Nl:"",10)/1e3,Ka=(Fl=se.getAttribute("frameRate"))!=null?Fl:"",wi=(ql=se.getAttribute("quality"))!=null?ql:void 0,En=Ka?wv(Ka):void 0,Ai=(Ul=se.getAttribute("id"))!=null?Ul:"id"+(V++).toString(10),Xa=Bt==="video"?`${dr}p`:Bt==="audio"?`${za}Kbps`:Ga,Ja=`${Ai}@${Xa}`,Za=[...J,...TS,...Ya],ki,pr=se.querySelector("SegmentBase"),Re=(Hl=se.querySelector("SegmentTemplate"))!=null?Hl:ES;if(pr){let It=(Ql=(jl=se.querySelector("SegmentBase Initialization"))==null?void 0:jl.getAttribute("range"))!=null?Ql:"",[et,ai]=It.split("-").map(Ft=>parseInt(Ft,10)),We={from:et,to:ai},_t=(Gl=se.querySelector("SegmentBase"))==null?void 0:Gl.getAttribute("indexRange"),[si,Nt]=_t?_t.split("-").map(Ft=>parseInt(Ft,10)):[],ct=_t?{from:si,to:Nt}:void 0;ki={type:"byteRange",url:ii,initRange:We,indexRange:ct}}else if(Re){let It={representationId:(Wl=se.getAttribute("id"))!=null?Wl:void 0,bandwidth:(Yl=se.getAttribute("bandwidth"))!=null?Yl:void 0},et=parseInt((zl=Re.getAttribute("timescale"))!=null?zl:"",10),ai=(Kl=Re.getAttribute("initialization"))!=null?Kl:"",We=Re.getAttribute("media"),_t=(Jl=parseInt((Xl=Re.getAttribute("startNumber"))!=null?Xl:"",10))!=null?Jl:1,si=$t(ai,It);if(!We)throw new ReferenceError("No media attribute in SegmentTemplate");let Nt=(Zl=Re.querySelectorAll("SegmentTimeline S"))!=null?Zl:[],ct=[],Ft=0,Ri="",mr=0;if(Nt.length){let es=_t,tt=0;for(let $i of Nt){let dt=parseInt((ec=$i.getAttribute("d"))!=null?ec:"",10),ni=parseInt((tc=$i.getAttribute("r"))!=null?tc:"",10)||0,ts=parseInt((ic=$i.getAttribute("t"))!=null?ic:"",10);tt=Number.isFinite(ts)?ts:tt;let xn=dt/et*1e3,Pn=tt/et*1e3;for(let is=0;is<ni+1;is++){let wS=$t(We,{...It,segmentNumber:es.toString(10),segmentTime:(tt+is*dt).toString(10)}),sc=(Pn!=null?Pn:0)+is*xn,AS=sc+xn;es++,ct.push({time:{from:sc,to:AS},url:wS})}tt+=(ni+1)*dt,Ft+=(ni+1)*xn}mr=tt/et*1e3,Ri=$t(We,{...It,segmentNumber:es.toString(10),segmentTime:tt.toString(10)})}else if((0,Aa.isNonNullable)(y)){let tt=parseInt((rc=Re.getAttribute("duration"))!=null?rc:"",10)/et*1e3,$i=Math.ceil(y/tt),dt=0;for(let ni=1;ni<$i;ni++){let ts=$t(We,{...It,segmentNumber:ni.toString(10),segmentTime:dt.toString(10)});ct.push({time:{from:dt,to:dt+tt},url:ts}),dt+=tt}mr=dt,Ri=$t(We,{...It,segmentNumber:$i.toString(10),segmentTime:dt.toString(10)})}let PS={time:{from:mr,to:1/0},url:Ri};ki={type:"template",baseUrl:ii,segmentTemplateUrl:We,initUrl:si,totalSegmentsDurationMs:Ft,segments:ct,nextSegmentBeyondManifest:PS,timescale:et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Bt||!Ot)continue;let hr={video:"video",audio:"audio",text:"text"}[Bt];if(!hr)continue;Pi||(Pi=hr),Wa={id:Ja,kind:hr,segmentReference:ki,profiles:Za,duration:y,bitrate:za,mime:Ot,codecs:Ga,width:ri,height:dr,fps:En,quality:wi}}he.language||(he.language=Vt),he.label||(he.label=cr),he.mime||(he.mime=Ot),he.codecs||(he.codecs=Ga),he.hdr||(he.hdr=Pi==="video"&&Ju(Ga)),he.representations.push(Wa)}if(Pi){let se=r[Pi].find(Vt=>Vt.id===he.id);if(se&&he.representations.every(Vt=>Le(Vt.segmentReference)))for(let Vt of se.representations){let cr=he.representations.find(Ot=>Ot.id===Vt.id),Qa=cr==null?void 0:cr.segmentReference,ii=Vt.segmentReference;ii.segments.push(...Qa.segments),ii.nextSegmentBeyondManifest=Qa.nextSegmentBeyondManifest}else r[Pi].push(he)}}return{duration:y,streams:r,baseUrls:n,live:S}};var _v=j(Ye(),1),ol=require("@vkontakte/videoplayer-shared/es2018"),fe=(a,e)=>(0,ol.isNonNullable)(a)&&(0,ol.isNonNullable)(e)&&a.readyState==="open"&&(0,_v.default)([...a.activeSourceBuffers],e);var ka=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new I.ValueSubject(0);this.currentLowLatencySegmentLength$=new I.ValueSubject(0);this.currentSegmentLength$=new I.ValueSubject(0);this.onLastSegment$=new I.ValueSubject(!1);this.fullyBuffered$=new I.ValueSubject(!1);this.playingRepresentation$=new I.ValueSubject(void 0);this.playingRepresentationInit$=new I.ValueSubject(void 0);this.error$=new I.Subject;this.gaps=[];this.subscription=new I.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ae;this.switchAbortController=new Ae;this.destroyAbortController=new Ae;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,I.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Vg(this.sourceBuffer),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!fe(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Qu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"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,I.assertNonNullable)(i,"No init buffer for starting representation"),(0,I.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,I.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!fe(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,I.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,I.isNullable)(s)||(0,I.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,I.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!fe(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,I.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,I.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!fe(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,I.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,I.isNullable)(s)||(0,I.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,I.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!fe(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,I.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,I.abortable)(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,tn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let m=this.representations.get(c);if(!m||!Le(m.segmentReference))return;let h=this.getActualLiveStartingSegments(m.segmentReference);this.segments.set(m.id,h)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,I.assertNonNullable)(r);let s=this.segments.get(i);(0,I.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,I.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,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));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],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){!fe(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Ae,(0,I.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,I.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,I.isNullable)(o)||(0,I.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,I.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!fe(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,I.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,I.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 Ae,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,I.isNullable)(e)||(0,I.isNullable)(this.downloadingRepresentationId)||(0,I.isNullable)(this.playingRepresentationId)||(0,I.isNullable)(this.sourceBuffer)||!fe(this.mediaSource,this.sourceBuffer)||(0,I.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,I.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);(0,I.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&Qu(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,en.default)(u,r))c="high";else{let d=(0,ar.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,ar.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),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}),i=s.time.to;(0,I.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,tn.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,tn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Le(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,ar.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,m=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(m===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(m+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,I.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!Le(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=$t(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Zr&&Zr(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Zr&&Zr(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:d,time:{from:m,to:h}},f)=>{let g=m<=i&&h>=i,S=m>i||g||f===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&m<=i+y||h<=i+y;return(d==="none"||d==="partially_ejected"&&S&&E&&this.sourceBuffer&&fe(this.mediaSource,this.sourceBuffer)&&!(Kt(this.sourceBuffer.buffered,m)&&Kt(this.sourceBuffer.buffered,h)))&&S&&E});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=r;d<s.length&&(n<=l||o<=c);d++){let m=s[d];if(n+=m.byte.to+1-m.byte.from,o+=m.time.to+1-m.time.from,m.status==="none"||m.status==="partially_ejected")u.push(m);else break}return u}async loadSegments(e,t,i="auto"){Le(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,I.abortable)(o,async function*(){let c=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,I.now)(),!c)return;let d=new DataView(c),m=Pa(t.mime);if(!isFinite(r.segment.time.to)){let g=t.segmentReference.timescale;r.segment.time.to=m.getChunkEndTime(d,g)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=m.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),wa(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Le(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,I.abortable)(n,async function*(){let u=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,I.fromEvent)(window,"online").pipe((0,I.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,I.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),wa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Le(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,ar.default)(e,0).byte.from,to:(0,ar.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,I.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Le(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,I.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,en.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!fe(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 l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Pa(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!fe(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-i,d=l.byte.to-i,m=d-c+1,h=c<r,f=d<=r;if(!h)continue;let g=Pa(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,m);await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(m,r-c),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),y=u.loadedBytes===m?S:g.parseFeedableSegmentChunk(S);y!=null&&y.byteLength&&(l.status="partially_fed",u.feedingBytes+=y.byteLength,await this.sourceBufferTaskQueue.append(y,s)&&!s.aborted?(u.fedBytes+=y.byteLength,u.fedBytes===m&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!((0,I.isNullable)(this.sourceBuffer)||!fe(this.mediaSource,this.sourceBuffer))){!this.isLive&&K.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Kt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Kt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",rl(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Hu(()=>(0,Nv.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,I.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Pa(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let m=c;this.isLive&&Le(e.segmentReference)&&(m=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,m),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:I.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!fe(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,I.isNullable)(e))return!1;let r=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:m}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,m):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=rl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let m of this.segments.values())for(let h of m)(0,en.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let m={time:{from:l,to:c},url:"",status:"none"};o(m)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!fe(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||!fe(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||!fe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,I.isNullable)(e)?0:Zi(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!fe(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!fe(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Hu(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:I.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,I.isNullable)(this.sourceBuffer)||!fe(this.mediaSource,this.sourceBuffer)||(0,I.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:I.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ra=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Fv=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};var q=require("@vkontakte/videoplayer-shared/es2018");var qv=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var an=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new q.ValueSubject(void 0);this.lastConnectionReused$=new q.ValueSubject(void 0);this.lastRequestFirstBytes$=new q.ValueSubject(void 0);this.recoverableError$=new q.Subject;this.error$=new q.Subject;this.abortAllController=new Ae;this.subscription=new q.Subscription;this.fetchManifest=(0,q.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ra(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=qv(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(rn);return r?(t.log("success",(0,q.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,q.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,q.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var Z,_;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let C=new URL(l,location.href);C.searchParams.append("bytes",`${i.from}-${i.to}`),l=C.toString();break}default:(0,q.assertNever)(t)}this.requestQuic&&(l=Ra(l));let m=this.abortAllController.signal,h;if(n){let C=new Ae;if(h=(0,q.merge)((0,q.fromEvent)(this.abortAllController.signal,"abort"),(0,q.fromEvent)(n,"abort")).subscribe(()=>{try{C.abort()}catch(re){rn(re)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{C.abort()}catch(re){rn(re)}m=C.signal}let f=(0,q.now)();d.log("startRequest",(0,q.flattenObject)({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let g=yield this.doFetch(l,{priority:s,headers:c,signal:m}),S=(0,q.now)();if(!g)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((Z=this.throughputEstimator)==null||Z.addRawRtt(S-f),!g.ok||!g.body){h==null||h.unsubscribe();let C=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:C}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){h==null||h.unsubscribe();let C=(0,q.now)(),re={requestStartedAt:f,requestEndedAt:C,duration:C-f};return d.log("endRequest",(0,q.flattenObject)(re)),d.end(),g.arrayBuffer()}let[y,E]=g.body.tee(),x=y.getReader();o&&((_=this.throughputEstimator)==null||_.trackStream(E,u));let w=0,P=new Uint8Array(0),V=!1,J=C=>{h==null||h.unsubscribe(),V=!0,rn(C)},W=(0,q.abortable)(m,async function*({done:C,value:re}){if(w===0&&this.lastRequestFirstBytes$.next((0,q.now)()-f),m.aborted){h==null||h.unsubscribe();return}if(!C&&re){let ge=new Uint8Array(P.length+re.length);ge.set(P),ge.set(re,P.length),P=ge,w+=re.byteLength,r==null||r(new DataView(P.buffer),w),yield x==null?void 0:x.read().then(W,J)}}.bind(this));yield x==null?void 0:x.read().then(W,J),h==null||h.unsubscribe();let X=(0,q.now)(),$={failed:V,requestStartedAt:f,requestEndedAt:X,duration:X-f};return V?(d.error("endRequest",(0,q.flattenObject)($)),d.end(),null):(d.log("endRequest",(0,q.flattenObject)($)),d.end(),P.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,q.abortable)(this.abortAllController.signal,async function*(e,t,i){var y;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let m=new DataView(d,r-n,s-n+1);if(!t.validateData(m))throw new Error("Invalid media file");let h=t.parseInit(m),f=(y=e.indexRange)!=null?y:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,f.from-n,f.to-f.from+1);else{let E=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!E)return null;g=new DataView(E)}let S=t.parseSegments(g,h,f);return{init:h,dataView:new DataView(d),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,q.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Fv(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,q.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await vt(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:q.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:q.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:q.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:q.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:q.ErrorCategory.FATAL})}}},rn=a=>{if(!wa(a))throw a};var Si=(a,e,t)=>t*e+(1-t)*a,ul=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Uv=(a,e,t,i)=>{let r=0,s=t,n=ul(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};var $a=require("@vkontakte/videoplayer-shared/es2018"),Zt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new $a.ValueSubject(e.initial),this.debounced$=new $a.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new $e(`raw_${t}`),this.smoothedSeries$=new $e(`smoothed_${t}`),this.reportedSeries$=new $e(`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,$a.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 sn=class extends Zt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Si(this.slow,e,this.params.emaAlphaSlow),this.fast=Si(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var nn=class extends Zt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ul(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Si(this.emaSmoothed,e,this.params.emaAlpha);let i=Uv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var on=class extends Zt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Si(this.smoothed,t,this.params.emaAlpha):t}};var yi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new sn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new nn({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 on({initial:e,label:"liveEdgeDelay",...t})}};var ll=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var un=require("@vkontakte/videoplayer-shared/es2018");var La=class a{constructor(e,t){this.currentRepresentation$=new un.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,un.isNullable)(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Le(t.segmentReference))}};var cn=j(Wt(),1);var Ma=require("@vkontakte/videoplayer-shared/es2018");var Hv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:s,codecs:n,nativeHlsSupported:o}=K.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!i||!!window.MediaStreamTrack)||s.mms&&t;return a.filter(c=>{switch(c){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(r.mp4||r.webm);default:return(0,Ma.assertNever)(c)}})},ln=a=>{let{webmDecodingInfo:e}=K.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,Ma.assertNever)(a)}return[t,i]},jv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...ln(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(K.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...ln(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ln(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ln(a),...r,"HLS","HLS_ONDEMAND"];default:(0,Ma.assertNever)(e)}return K.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Qv=({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=K.device.isMac&&K.browser.isSafari;if(K.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,Ma.assertNever)(a)}else K.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},cl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Gv=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,cn.default)(t.value.split("."),0)}for(let t of a){let i=(0,cn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,cn.default)(e.value.split("."),0)};var zR=["timeupdate","progress","play","seeked","stalled","waiting"],KR=["timeupdate","progress","loadeddata","playing","seeked"];var dn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new v.Subscription;this.representationSubscription=new v.Subscription;this.state$=new Q("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentAudioRepresentation$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.currentLiveTextRepresentation$=new v.ValueSubject(null);this.isLive$=new v.ValueSubject(!1);this.isActiveLive$=new v.ValueSubject(!1);this.isLowLatency$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveSeekableDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(0);this.liveStreamStatus$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLatency$=new v.ValueSubject(void 0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.currentStallDuration$=new v.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new v.ValueSubject(0);this.fetcherRecoverableError$=new v.Subject;this.fetcherError$=new v.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new Ae;this.initManifest=(0,v.abortable)(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=we(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Bv(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Lg(e))!=null?n:{id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,m,h,f;return!!((m=(d=this.element)==null?void 0:d.canPlayType)!=null&&m.call(d,l)&&((f=(h=nt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,m=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*m),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";d||(h=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:f})=>i(u,h,f)),d=new Set(c.map(({codecs:h})=>h)),m=Gv(d);if(m&&(r[u]=c.filter(({codecs:h})=>h.startsWith(m))),u==="video"){let h=this.tuning.preferHDR,f=r.video.some(S=>S.hdr),g=r.video.some(S=>!S.hdr);K.display.isHDR&&h&&f?r.video=r.video.filter(S=>S.hdr):g&&(r.video=r.video.filter(S=>!S.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",(0,v.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,async function*(e,t,i){var m;this.tracer.log("initRepresentationsStart",(0,v.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=h=>{this.representationSubscription.add((0,v.fromEvent)(h,"error").pipe((0,v.filter)(f=>{var g;return!!((g=this.element)!=null&&g.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?pb():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&js())if(i){let h=document.createElement("source");r(h),h.type="application/x-mpegurl",h.src=i.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.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((h,f)=>[...h,...f.representations],[]);if(this.videoBufferManager=new ka("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let h=this.manifest.streams.audio.reduce((f,g)=>[...f,...g.representations],[]);this.audioBufferManager=new ka("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}La.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new La(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,v.merge)(...KR.map(h=>(0,v.fromEvent)(this.element,h))).pipe((0,v.map)(h=>this.element?Zi(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.tap)(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,v.merge)((0,v.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,v.filterChanged)()).subscribe(f=>this.liveStreamEndTimestamp=(0,v.now)())),this.subscription.add((0,v.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,v.interval)(1e3).subscribe(f=>{let g=_s(this.manifestUrlString,2);this.manifestUrlString=we(this.manifestUrlString,g+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,v.fromEvent)(this.element,"play").subscribe(f=>{var g;return(g=this.livePauseWatchdogSubscription)==null?void 0:g.unsubscribe()})),this.representationSubscription.add((0,v.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,v.map)(({isActiveLive:f,isLowLatency:g})=>f&&g),(0,v.filterChanged)()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||ll(this.element,1)})),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,v.filter)(({bufferLength:f,isActiveLive:g,isLowLatency:S})=>g&&S&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let g=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(g,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add((0,v.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,v.filter)(({isLive:f})=>f),(0,v.filterChanged)((f,g)=>g.bufferLength<f.bufferLength),(0,v.map)(({rtt:f,bufferLength:g,segmentServerLatency:S})=>{let y=_s(this.manifestUrlString,2);return(f/2+g+S+y)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,v.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:g,isLowLatency:S})=>{if(!S||!g)return;let y=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,w=f-y;if(this.isManualDecreasePlaybackInLive())return;let P=1;Math.abs(w)>E&&(P=1+Math.sign(w)*x),ll(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var S,y;let g=0;if(f){let E=((y=(S=this.element)==null?void 0:S.currentTime)!=null?y:0)*1e3;g=Math.min(...this.bufferManagers.map(w=>{var P,V;return(V=(P=w.getLiveSegmentsToLoadState(this.manifest))==null?void 0:P.to)!=null?V:E}))-E}this.liveLoadBufferLength$.getValue()!==g&&this.liveLoadBufferLength$.next(g)}));let h=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:g})=>{if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,y=_s(this.manifestUrlString,2),E=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(E,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,P=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,V=isFinite(f)?f:g,J=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),W=E<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(W);let X="none";if(J?X="active_low_latency":this.isLowLatency$.getValue()&&W?(this.bufferManagers.forEach($=>$.proceedLowLatencyLive()),X="active_low_latency"):y!==0&&V<x?X="live_forward_buffering":V<x+P&&(X="live_with_target_offset"),isFinite(f)&&(h=f>h?f:h),X==="live_forward_buffering"||X==="live_with_target_offset"){let $=h-(x+w),Z=this.normolizeLiveOffset(Math.trunc(y+$/S)),_=Math.abs(Z-y),C=0;!f||_<=this.tuning.dashCmafLive.offsetCalculationError?C=y:Z>0&&_>this.tuning.dashCmafLive.offsetCalculationError&&(C=Z),this.manifestUrlString=we(this.manifestUrlString,C,2)}(X==="live_with_target_offset"||X==="live_forward_buffering")&&(h=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:v.ErrorCategory.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=(0,v.merge)(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),c=(0,v.merge)(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue()))),d=(0,v.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,v.filterChanged)(),(0,v.map)(({allBuffersFull:h,someBufferEnded:f})=>h&&f),(0,v.filter)(h=>h));if(this.representationSubscription.add((0,v.merge)(this.forceEnded$,d).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(h=this.source)==null||h.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add((0,v.merge)(...this.bufferManagers.map(h=>h.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let h=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise((f,g)=>{var S;h&&(this.timeoutSourceOpenId=setTimeout(()=>{var y;if(((y=this.source)==null?void 0:y.readyState)==="open"){f();return}this.tuning.dash.rejectOnSourceOpenTimeout?g(new Error("Timeout reject when wait sourceopen event")):f()},this.tuning.dash.sourceOpenTimeout)),(S=this.source)==null||S.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let h=[(m=this.manifest.duration)!=null?m:0,...(0,pl.default)((0,pl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let g=[];return f.duration&&g.push(f.duration),Le(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&g.push(f.segmentReference.totalSegmentsDurationMs),g})];this.source.duration=Math.max(...h)/1e3}this.audioBufferManager&&(0,v.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new an({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.liveBuffer=yi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;(0,v.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,v.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=we(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...zR.map(e=>(0,v.fromEvent)(this.element,e)),(0,v.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,v.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Kt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,g,S,y,E,x,w,P,V,J;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=(0,v.now)(),n=100,o=(g=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?g:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(y=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?y:0,l=(x=(E=this.videoBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?x:0,c=(P=(w=this.audioBufferManager)==null?void 0:w.getForwardBufferDuration())!=null?P:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,m=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||m)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let W=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(W).catch(X=>{this.error$.next({id:"stallIntervalCallback",category:v.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:X})}),r.liveLastOffset=W}else{let W=this.element.currentTime*1e3;(V=this.videoBufferManager)==null||V.maintain(W),(J=this.audioBufferManager)==null||J.maintain(W),r.position=W}this.tracer.log("stallIntervalCallback",(0,v.flattenObject)(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Kt(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!((0,v.isNullable)(this.element)||(0,v.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,v.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,v.isNonNullable)(this.element)&&(0,v.isNonNullable)(this.source)&&(0,v.isNonNullable)(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,v.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,v.flattenObject)(i)))}}};var pn=class{constructor(e,t){this.fov=e,this.orientation=t}};var hn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Yv=`attribute vec2 a_vertex;
124
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var vd=Y(Zt(),1);var hy=require("@vkontakte/videoplayer-shared/es2018"),fy=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?li(a):void 0)!=null?u:(0,hy.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},my=({id:s,bitrate:e})=>({id:s,bitrate:e}),by=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),gy=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),yd=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,vd.default)(i.split("."),0),isDefault:r}),Td=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,vd.default)(r.split("."),0)}),Id=s=>"url"in s,mt=s=>s.type==="template",cn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Sy=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},xr=(s,e)=>{for(let t of s)if(e(t))return t;return null},jM=(s,e)=>{let t=0;return()=>{let i=Date.now();i-t>=e&&(s(),t=i)}},vy=s=>{let e=!1,t=jM(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}},lu=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var yy=s=>{if(!(s!=null&&s.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(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Di=(s,e)=>{let t=s;t=(0,xd.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Ty.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,xd.default)(t,n,(o,u)=>(0,dn.isNullable)(a)?o:(0,dn.isNullable)(u)?a:(0,Iy.default)(a,parseInt(u,10),"0"))}return t},Ey=(s,e)=>{var O,B,H,N,_,ne,K,M,z,D,R,C,Le,It,xt,de,Ve,Oe,_e,Xe,Ot,qt,ri,fi,ji,fs,ms,bs,gs,Ss,vs,ys,Ts,Is,xs,Es,ws,As,Ps,ks,Rs,Ls,Ms,$s,Bs,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,Gs,zs,Qs,Ws,Ys;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(xe=>{var G,nt;return(nt=(G=xe.textContent)==null?void 0:G.trim())!=null?nt:""}),o=(O=(0,xy.default)(n,0))!=null?O:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],p=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let v,y=a.getAttribute("mediaPresentationDuration"),x=[...a.getElementsByTagName("Period")],A=x.reduce((xe,G)=>({...xe,[G.id]:G.children}),{}),w=x.reduce((xe,G)=>({...xe,[G.id]:G.getAttribute("duration")}),{});y?v=yy(y):(0,Ed.default)(w).filter(xe=>xe).length&&!u?v=(0,Ed.default)(w).reduce((xe,G)=>{var nt;return xe+((nt=yy(G))!=null?nt:0)},0):b&&(v=parseInt(b,10));let L=0,q=(H=(B=a.getAttribute("profiles"))==null?void 0:B.split(","))!=null?H:[];for(let xe of x.map(G=>G.id))for(let G of A[xe]){let nt=(N=G.getAttribute("id"))!=null?N:"id"+(L++).toString(10),jt=(_=G.getAttribute("mimeType"))!=null?_:"",rr=(ne=G.getAttribute("codecs"))!=null?ne:"",sr=(K=G.getAttribute("contentType"))!=null?K:jt==null?void 0:jt.split("/")[0],ju=(z=(M=G.getAttribute("profiles"))==null?void 0:M.split(","))!=null?z:[],Ks=(R=py((D=G.getAttribute("lang"))!=null?D:""))!=null?R:{},mi=(It=(Le=(C=G.querySelector("Label"))==null?void 0:C.textContent)==null?void 0:Le.trim())!=null?It:void 0,Hu=G.querySelectorAll("Representation"),Gu=G.querySelector("SegmentTemplate"),zu=(de=(xt=G.querySelector("Role"))==null?void 0:xt.getAttribute("value"))!=null?de:void 0,Et=sr,se={id:nt,language:Ks.language,isDefault:zu==="main",label:mi,codecs:rr,hdr:Et==="video"&&ns(rr),mime:jt,representations:[]};for(let j of Hu){let je=(Ve=j.getAttribute("lang"))!=null?Ve:void 0,Ht=(_e=(Oe=mi!=null?mi:G.getAttribute("label"))!=null?Oe:j.getAttribute("label"))!=null?_e:void 0,bi=(qt=(Ot=(Xe=j.querySelector("BaseURL"))==null?void 0:Xe.textContent)==null?void 0:Ot.trim())!=null?qt:"",ot=new URL(bi||o,e).toString(),He=(ri=j.getAttribute("mimeType"))!=null?ri:jt,gi=(ji=(fi=j.getAttribute("codecs"))!=null?fi:rr)!=null?ji:"",Si;if(sr==="text"){let Ge=j.getAttribute("id")||"",vi=((fs=Ks.privateuse)==null?void 0:fs.includes("x-auto"))||Ge.includes("_auto"),ut=j.querySelector("SegmentTemplate");if(ut){let Gt={representationId:(ms=j.getAttribute("id"))!=null?ms:void 0,bandwidth:(bs=j.getAttribute("bandwidth"))!=null?bs:void 0},yi=parseInt((gs=j.getAttribute("bandwidth"))!=null?gs:"",10)/1e3,Ti=(vs=parseInt((Ss=ut.getAttribute("startNumber"))!=null?Ss:"",10))!=null?vs:1,wt=parseInt((ys=ut.getAttribute("timescale"))!=null?ys:"",10),ar=(Ts=ut.querySelectorAll("SegmentTimeline S"))!=null?Ts:[],At=ut.getAttribute("media");if(!At)continue;let Ii=[],xi=0,Ei="",Pt=0,zt=Ti,fe=0;for(let Ee of ar){let lt=parseInt((Is=Ee.getAttribute("d"))!=null?Is:"",10),ge=parseInt((xs=Ee.getAttribute("r"))!=null?xs:"",10)||0,ze=parseInt((Es=Ee.getAttribute("t"))!=null?Es:"",10);fe=Number.isFinite(ze)?ze:fe;let ct=lt/wt*1e3,Qe=fe/wt*1e3;for(let Me=0;Me<ge+1;Me++){let We=Di(At,{...Gt,segmentNumber:zt.toString(10),segmentTime:(fe+Me*lt).toString(10)}),kt=(Qe!=null?Qe:0)+Me*ct,Wt=kt+ct;zt++,Ii.push({time:{from:kt,to:Wt},url:We})}fe+=(ge+1)*lt,xi+=(ge+1)*ct}Pt=fe/wt*1e3,Ei=Di(At,{...Gt,segmentNumber:zt.toString(10),segmentTime:fe.toString(10)});let Qt={time:{from:Pt,to:1/0},url:Ei},Fe={type:"template",baseUrl:ot,segmentTemplateUrl:At,initUrl:"",totalSegmentsDurationMs:xi,segments:Ii,nextSegmentBeyondManifest:Qt,timescale:wt};Si={id:Ge,kind:"text",segmentReference:Fe,profiles:[],duration:v,bitrate:yi,mime:"",codecs:"",width:0,height:0,isAuto:vi}}else Si={id:Ge,isAuto:vi,kind:"text",url:ot}}else{let Ge=(As=(ws=j.getAttribute("contentType"))!=null?ws:He==null?void 0:He.split("/")[0])!=null?As:sr,vi=(ks=(Ps=G.getAttribute("profiles"))==null?void 0:Ps.split(","))!=null?ks:[],ut=parseInt((Rs=j.getAttribute("width"))!=null?Rs:"",10),Gt=parseInt((Ls=j.getAttribute("height"))!=null?Ls:"",10),yi=parseInt((Ms=j.getAttribute("bandwidth"))!=null?Ms:"",10)/1e3,Ti=($s=j.getAttribute("frameRate"))!=null?$s:"",wt=(Bs=j.getAttribute("quality"))!=null?Bs:void 0,ar=Ti?uu(Ti):void 0,At=(Ds=j.getAttribute("id"))!=null?Ds:"id"+(L++).toString(10),Ii=Ge==="video"?`${Gt}p`:Ge==="audio"?`${yi}Kbps`:gi,xi=`${At}@${Ii}`,Ei=[...q,...ju,...vi],Pt,zt=j.querySelector("SegmentBase"),fe=(Cs=j.querySelector("SegmentTemplate"))!=null?Cs:Gu;if(zt){let Fe=(Os=(Vs=j.querySelector("SegmentBase Initialization"))==null?void 0:Vs.getAttribute("range"))!=null?Os:"",[Ee,lt]=Fe.split("-").map(We=>parseInt(We,10)),ge={from:Ee,to:lt},ze=(_s=j.querySelector("SegmentBase"))==null?void 0:_s.getAttribute("indexRange"),[ct,Qe]=ze?ze.split("-").map(We=>parseInt(We,10)):[],Me=ze?{from:ct,to:Qe}:void 0;Pt={type:"byteRange",url:ot,initRange:ge,indexRange:Me}}else if(fe){let Fe={representationId:(Fs=j.getAttribute("id"))!=null?Fs:void 0,bandwidth:(Ns=j.getAttribute("bandwidth"))!=null?Ns:void 0},Ee=parseInt((Us=fe.getAttribute("timescale"))!=null?Us:"",10),lt=(qs=fe.getAttribute("initialization"))!=null?qs:"",ge=fe.getAttribute("media"),ze=(Hs=parseInt((js=fe.getAttribute("startNumber"))!=null?js:"",10))!=null?Hs:1,ct=Di(lt,Fe);if(!ge)throw new ReferenceError("No media attribute in SegmentTemplate");let Qe=(Gs=fe.querySelectorAll("SegmentTimeline S"))!=null?Gs:[],Me=[],We=0,kt="",Wt=0;if(Qe.length){let wi=ze,we=0;for(let Rt of Qe){let $e=parseInt((zs=Rt.getAttribute("d"))!=null?zs:"",10),dt=parseInt((Qs=Rt.getAttribute("r"))!=null?Qs:"",10)||0,Ai=parseInt((Ws=Rt.getAttribute("t"))!=null?Ws:"",10);we=Number.isFinite(Ai)?Ai:we;let nr=$e/Ee*1e3,or=we/Ee*1e3;for(let Pi=0;Pi<dt+1;Pi++){let Wu=Di(ge,{...Fe,segmentNumber:wi.toString(10),segmentTime:(we+Pi*$e).toString(10)}),Xs=(or!=null?or:0)+Pi*nr,Yu=Xs+nr;wi++,Me.push({time:{from:Xs,to:Yu},url:Wu})}we+=(dt+1)*$e,We+=(dt+1)*nr}Wt=we/Ee*1e3,kt=Di(ge,{...Fe,segmentNumber:wi.toString(10),segmentTime:we.toString(10)})}else if((0,dn.isNonNullable)(v)){let we=parseInt((Ys=fe.getAttribute("duration"))!=null?Ys:"",10)/Ee*1e3,Rt=Math.ceil(v/we),$e=0;for(let dt=1;dt<Rt;dt++){let Ai=Di(ge,{...Fe,segmentNumber:dt.toString(10),segmentTime:$e.toString(10)});Me.push({time:{from:$e,to:$e+we},url:Ai}),$e+=we}Wt=$e,kt=Di(ge,{...Fe,segmentNumber:Rt.toString(10),segmentTime:$e.toString(10)})}let Qu={time:{from:Wt,to:1/0},url:kt};Pt={type:"template",baseUrl:ot,segmentTemplateUrl:ge,initUrl:ct,totalSegmentsDurationMs:We,segments:Me,nextSegmentBeyondManifest:Qu,timescale:Ee}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ge||!He)continue;let Qt={video:"video",audio:"audio",text:"text"}[Ge];if(!Qt)continue;Et||(Et=Qt),Si={id:xi,kind:Qt,segmentReference:Pt,profiles:Ei,duration:v,bitrate:yi,mime:He,codecs:gi,width:ut,height:Gt,fps:ar,quality:wt}}se.language||(se.language=je),se.label||(se.label=Ht),se.mime||(se.mime=He),se.codecs||(se.codecs=gi),se.hdr||(se.hdr=Et==="video"&&ns(gi)),se.representations.push(Si)}if(Et){let j=r[Et].find(je=>je.id===se.id);if(j&&se.representations.every(je=>mt(je.segmentReference)))for(let je of j.representations){let Ht=se.representations.find(He=>He.id===je.id),bi=Ht==null?void 0:Ht.segmentReference,ot=je.segmentReference;ot.segments.push(...bi.segments),ot.nextSegmentBeyondManifest=bi.nextSegmentBeyondManifest}else r[Et].push(se)}}return{duration:v,streams:r,baseUrls:n,live:S}};var Ad=require("@vkontakte/videoplayer-shared/es2018"),Z=(s,e)=>(0,Ad.isNonNullable)(s)&&(0,Ad.isNonNullable)(e)&&s.readyState==="open"&&HM(s,e);function HM(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var du=require("@vkontakte/videoplayer-shared/es2018");var cu=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new du.Subscription;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add((0,du.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!Z(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=lu(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var pn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new k.ValueSubject(0);this.currentLowLatencySegmentLength$=new k.ValueSubject(0);this.currentSegmentLength$=new k.ValueSubject(0);this.onLastSegment$=new k.ValueSubject(!1);this.fullyBuffered$=new k.ValueSubject(!1);this.playingRepresentation$=new k.ValueSubject(void 0);this.playingRepresentationInit$=new k.ValueSubject(void 0);this.error$=new k.Subject;this.gaps=[];this.subscription=new k.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new be;this.switchAbortController=new be;this.destroyAbortController=new be;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.sourceBufferBufferedDiff=null;this.startWith=(0,k.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,k.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 xv(this.sourceBuffer),this.sourceBufferBufferedDiff=new cu(this.mediaSource,this.sourceBuffer),this.subscription.add((0,k.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:k.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Z(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,rs(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Re(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"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),a=this.parsedInitData.get(t.id);(0,k.assertNonNullable)(i,"No init buffer for starting representation"),(0,k.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(a))}.bind(this));this.switchTo=(0,k.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,k.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,k.isNullable)(a)||(0,k.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,k.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,k.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,k.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,k.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,k.isNullable)(a)||(0,k.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,k.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,k.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,k.abortable)(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,hu.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let p=this.representations.get(d);if(!p||!mt(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,k.assertNonNullable)(r);let a=this.segments.get(i);(0,k.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,k.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))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(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new be,(0,k.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,k.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,k.isNullable)(o)||(0,k.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,k.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Z(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,k.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,k.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 be,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,k.isNullable)(e)||(0,k.isNullable)(this.downloadingRepresentationId)||(0,k.isNullable)(this.playingRepresentationId)||(0,k.isNullable)(this.sourceBuffer)||!Z(this.mediaSource,this.sourceBuffer)||(0,k.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,k.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);(0,k.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=Re(this.sourceBuffer.buffered,e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&rs(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Re(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(p=>{this.handleAsyncError(p,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u!=null&&u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,pu.default)(u,r))d="high";else{let c=(0,os.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&Re(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,os.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Re(this.sourceBuffer.buffered,e)<n),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 a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;(0,k.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=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,hu.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,hu.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!mt(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,os.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>c>=h.time.from+l&&c<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...d,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,k.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!mt(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.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),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=Di(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&pi&&pi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&pi&&pi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:p,to:h}},f)=>{let b=p<=i&&h>=i,S=p>i||b||f===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+v||h<=i+v;return(c==="none"||c==="partially_ejected"&&S&&y&&this.sourceBuffer&&Z(this.mediaSource,this.sourceBuffer)&&!(at(this.sourceBuffer.buffered,p)&&at(this.sourceBuffer.buffered,h)))&&S&&y});if(r===-1)return null;if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){let p=a[c];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){mt(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:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,k.abortable)(o,async function*(){let d=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,k.now)(),!d)return;let c=new DataView(d),p=ln(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(c,b)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),cn(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())mt(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:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,k.abortable)(n,async function*(){let u=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,k.fromEvent)(window,"online").pipe((0,k.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,k.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),cn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(mt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,os.default)(e,0).byte.from,to:(0,os.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,k.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!mt(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:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,k.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,pu.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!Z(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(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=ln(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&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:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Z(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,d=l.byte.from-i,c=l.byte.to-i,p=c-d+1,h=d<r,f=c<=r;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(b,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-d),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?b:ln(o.mime).parseFeedableSegmentChunk(b);S!=null&&S.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!((0,k.isNullable)(this.sourceBuffer)||!Z(this.mediaSource,this.sourceBuffer))){!this.isLive&&J.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(at(this.sourceBuffer.buffered,e.segment.time.from,100)&&at(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Id(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&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,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=is(()=>(0,wy.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,k.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ln(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&mt(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:k.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,k.isNullable)(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push({...o.time});let u=Id(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let p of c)(0,pu.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(u)&&Math.round(p.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=Sy(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!Z(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||!Z(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)}}getBufferedTo(){return!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,k.isNullable)(e)?0:Re(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(a=>{if(a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.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}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=is(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:k.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,k.isNullable)(this.sourceBuffer)||!Z(this.mediaSource,this.sourceBuffer)||(0,k.isNullable)(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=lu(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],p=e[d+1];u||(u=c-t<=n&&p+t>=o),(n>=c&&n<p-t||o>c+t&&o<=p)&&(l+=1)}u||(l===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:k.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Zi=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var fu=s=>{var a;let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};var ie=require("@vkontakte/videoplayer-shared/es2018");var mu=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var gu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new ie.ValueSubject(void 0);this.lastConnectionReused$=new ie.ValueSubject(void 0);this.lastRequestFirstBytes$=new ie.ValueSubject(void 0);this.recoverableError$=new ie.Subject;this.error$=new ie.Subject;this.abortAllController=new be;this.subscription=new ie.SubscriptionRemovable;this.fetchManifest=(0,ie.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Zi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=mu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(bu);return r?(t.log("success",(0,ie.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,ie.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,ie.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var H,N;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let _=new URL(l,location.href);_.searchParams.append("bytes",`${i.from}-${i.to}`),l=_.toString();break}default:(0,ie.assertNever)(t)}this.requestQuic&&(l=Zi(l));let p=this.abortAllController.signal,h;if(n){let _=new be;if(h=(0,ie.merge)((0,ie.fromEvent)(this.abortAllController.signal,"abort"),(0,ie.fromEvent)(n,"abort")).subscribe(()=>{try{_.abort()}catch(ne){bu(ne)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(ne){bu(ne)}p=_.signal}let f=(0,ie.now)();c.log("startRequest",(0,ie.flattenObject)({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let b=yield this.doFetch(l,{priority:a,headers:d,signal:p}),S=(0,ie.now)();if(!b)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(h),null;if((H=this.throughputEstimator)==null||H.addRawRtt(S-f),!b.ok||!b.body){this.unsubscribeAbortSubscription(h);let _=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:_}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let _=(0,ie.now)(),ne={requestStartedAt:f,requestEndedAt:_,duration:_-f};return c.log("endRequest",(0,ie.flattenObject)(ne)),c.end(),b.arrayBuffer()}let[v,y]=b.body.tee(),x=v.getReader();o&&((N=this.throughputEstimator)==null||N.trackStream(y,u));let A=0,w=new Uint8Array(0),L=!1,q=_=>{this.unsubscribeAbortSubscription(h),L=!0,bu(_)},F=(0,ie.abortable)(p,async function*({done:_,value:ne}){if(A===0&&this.lastRequestFirstBytes$.next((0,ie.now)()-f),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!_&&ne){let K=new Uint8Array(w.length+ne.length);K.set(w),K.set(ne,w.length),w=K,A+=ne.byteLength,r==null||r(new DataView(w.buffer),A),yield x==null?void 0:x.read().then(F,q)}}.bind(this));yield x==null?void 0:x.read().then(F,q),this.unsubscribeAbortSubscription(h);let O=(0,ie.now)(),B={failed:L,requestStartedAt:f,requestEndedAt:O,duration:O-f};return L?(c.error("endRequest",(0,ie.flattenObject)(B)),c.end(),null):(c.log("endRequest",(0,ie.flattenObject)(B)),c.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,ie.abortable)(this.abortAllController.signal,async function*(e,t,i){var v;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,r-n,a-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,f.from-n,f.to-f.from+1);else{let y=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,ie.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=fu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,ie.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Nt(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:ie.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ie.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ie.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ie.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:ie.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},bu=s=>{if(!cn(s))throw s};var Ci=(s,e,t)=>t*e+(1-t)*s,Pd=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Ay=(s,e,t,i)=>{let r=0,a=t,n=Pd(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};var hn=require("@vkontakte/videoplayer-shared/es2018"),er=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new hn.ValueSubject(e.initial),this.debounced$=new hn.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ht(`raw_${t}`),this.smoothedSeries$=new ht(`smoothed_${t}`),this.reportedSeries$=new ht(`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),a=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>a||this.smoothed<n)&&((0,hn.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 Su=class extends er{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ci(this.slow,e,this.params.emaAlphaSlow),this.fast=Ci(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var vu=class extends er{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Pd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ci(this.emaSmoothed,e,this.params.emaAlpha);let i=Ay(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var yu=class extends er{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?Ci(this.smoothed,t,this.params.emaAlpha):t}};var Vi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Su({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new vu({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 yu({initial:e,label:"liveEdgeDelay",...t})}};var us=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};var Tu=require("@vkontakte/videoplayer-shared/es2018");var fn=class s{constructor(e,t){this.currentRepresentation$=new Tu.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,Tu.isNullable)(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&mt(t.segmentReference))}};var xu=Y(Zt(),1);var mn=require("@vkontakte/videoplayer-shared/es2018");var Py=(s,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:a,codecs:n,nativeHlsSupported:o}=J.video,u=(n.h264||n.h265)&&n.aac,l=a.mse&&(!i||!!window.MediaStreamTrack)||a.mms&&t;return s.filter(d=>{switch(d){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return a.webrtc&&a.ws&&n.h264&&(r.mp4||r.webm);default:return(0,mn.assertNever)(d)}})},Iu=s=>{let{webmDecodingInfo:e}=J.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){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,mn.assertNever)(s)}return[t,i]},ky=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Iu(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(J.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Iu(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Iu(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Iu(s),...r,"HLS","HLS_ONDEMAND"];default:(0,mn.assertNever)(e)}return J.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Ry=({androidPreferredFormat:s,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"],a=[...i,...r],n=[...r,...i],o,u=J.device.isMac&&J.browser.isSafari;if(J.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:(0,mn.assertNever)(s)}else J.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},kd=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Eu=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,xu.default)(t.value.split("."),0)}for(let t of s){let i=(0,xu.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,xu.default)(e.value.split("."),0)};var YM=["timeupdate","progress","play","seeked","stalled","waiting"],KM=["timeupdate","progress","loadeddata","playing","seeked"];var wu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new T.Subscription;this.representationSubscription=new T.Subscription;this.state$=new te("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.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=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.bufferLength$=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.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.destroyController=new be;this.initedPruneBufferCallback=!1;this.initManifest=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=De(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:T.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,T.abortable)(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Ey(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=ou(e))!=null?n:{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,p,h,f;return!!((p=(c=this.element)==null?void 0:c.canPlayType)!=null&&p.call(c,l)&&((f=(h=Dt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,p=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";c||(h=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:h,codecs:f})=>i(u,h,f)),c=new Set(d.map(({codecs:h})=>h)),p=Eu(c);if(p&&(r[u]=d.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=r.video.some(S=>S.hdr),b=r.video.some(S=>!S.hdr);J.display.isHDR&&h&&f?r.video=r.video.filter(S=>S.hdr):b&&(r.video=r.video.filter(S=>!S.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",(0,T.flattenObject)(a)),a}.bind(this));this.initRepresentations=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){var p;this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new T.Subscription,this.state$.startTransitionTo("representations_ready");let r=h=>{this.representationSubscription.add((0,T.fromEvent)(h,"error").pipe((0,T.filter)(f=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?zo():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Yr())if(i){let h=document.createElement("source");r(h),h.type="application/x-mpegurl",h.src=i.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.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((h,f)=>[...h,...f.representations],[]);if(this.videoBufferManager=new pn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let h=this.manifest.streams.audio.reduce((f,b)=>[...f,...b.representations],[]);this.audioBufferManager=new pn("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}fn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new fn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,T.merge)(...KM.map(h=>(0,T.fromEvent)(this.element,h))).pipe((0,T.map)(h=>this.element?Re(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,T.filterChanged)()).subscribe(f=>this.liveStreamEndTimestamp=(0,T.now)())),this.subscription.add((0,T.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,T.interval)(1e3).subscribe(f=>{let b=Qi(this.manifestUrlString,2);this.manifestUrlString=De(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,T.fromEvent)(this.element,"play").subscribe(f=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add((0,T.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.map)(({isActiveLive:f,isLowLatency:b})=>f&&b),(0,T.filterChanged)()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||us(this.element,1)})),this.representationSubscription.add((0,T.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.filter)(({bufferLength:f,isActiveLive:b,isLowLatency:S})=>b&&S&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let b=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add((0,T.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,T.filter)(({isLive:f})=>f),(0,T.filterChanged)((f,b)=>b.bufferLength<f.bufferLength),(0,T.map)(({rtt:f,bufferLength:b,segmentServerLatency:S})=>{let v=Qi(this.manifestUrlString,2);return(f/2+b+S+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,T.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:b,isLowLatency:S})=>{if(!S||!b)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,A=f-v;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(A)>y&&(w=1+Math.sign(A)*x),us(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var S,v;let b=0;if(f){let y=((v=(S=this.element)==null?void 0:S.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(A=>{var w,L;return(L=(w=A.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?L:y}))-y}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let h=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:b})=>{if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,v=Qi(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),A=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,w=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,L=isFinite(f)?f:b,q=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),F=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(F);let O="none";if(q?O="active_low_latency":this.isLowLatency$.getValue()&&F?(this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),O="active_low_latency"):v!==0&&L<x?O="live_forward_buffering":L<x+w&&(O="live_with_target_offset"),isFinite(f)&&(h=f>h?f:h),O==="live_forward_buffering"||O==="live_with_target_offset"){let B=h-(x+A),H=this.normolizeLiveOffset(Math.trunc(v+B/S)),N=Math.abs(H-v),_=0;!f||N<=this.tuning.dashCmafLive.offsetCalculationError?_=v:H>0&&N>this.tuning.dashCmafLive.offsetCalculationError&&(_=H),this.manifestUrlString=De(this.manifestUrlString,_,2)}(O==="live_with_target_offset"||O==="live_forward_buffering")&&(h=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:T.ErrorCategory.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=(0,T.merge)(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=(0,T.merge)(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue()))),c=(0,T.combine)({allBuffersFull:l,someBufferEnded:d}).pipe((0,T.filterChanged)(),(0,T.map)(({allBuffersFull:h,someBufferEnded:f})=>h&&f),(0,T.filter)(h=>h));if(this.representationSubscription.add((0,T.merge)(this.forceEnded$,c).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(h=this.source)==null||h.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(h=>h.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let h=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise((f,b)=>{var S;h&&(this.timeoutSourceOpenId=setTimeout(()=>{var v;if(((v=this.source)==null?void 0:v.readyState)==="open"){f();return}this.tuning.dash.rejectOnSourceOpenTimeout?b(new Error("Timeout reject when wait sourceopen event")):f()},this.tuning.dash.sourceOpenTimeout)),(S=this.source)==null||S.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let h=[(p=this.manifest.duration)!=null?p:0,...(0,Ld.default)((0,Ld.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let b=[];return f.duration&&b.push(f.duration),mt(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&b.push(f.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...h)/1e3}this.audioBufferManager&&(0,T.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,T.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:T.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new gu({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.liveBuffer=Vi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;(0,T.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,T.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=De(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,T.merge)(...YM.filter(e=>e!=="timeupdate").map(e=>(0,T.fromEvent)(this.element,e)),(0,T.fromEvent)(window,"online"),(0,T.fromEvent)(this.element,"timeupdate").pipe((0,T.throttle)(300))).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&at(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,b,S,v,y,x,A,w,L,q;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=(0,T.now)(),n=100,o=(b=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?v:0,l=(x=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?x:0,d=(w=(A=this.audioBufferManager)==null?void 0:A.getForwardBufferDuration())!=null?w:0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||p)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let F=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(F).catch(O=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:O})}),r.liveLastOffset=F}else{let F=this.element.currentTime*1e3;(L=this.videoBufferManager)==null||L.maintain(F),(q=this.audioBufferManager)==null||q.maintain(F),r.position=F}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,T.interval)(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;(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((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),at(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!((0,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.isNonNullable)(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,T.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",(0,T.flattenObject)({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};var Au=class{constructor(e,t){this.fov=e,this.orientation=t}};var Pu=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var $y=`attribute vec2 a_vertex;
71
125
  attribute vec2 a_texel;
72
126
 
73
127
  varying vec2 v_texel;
@@ -78,7 +132,7 @@ void main(void) {
78
132
  // save texel vector to pass to fragment shader
79
133
  v_texel = a_texel;
80
134
  }
81
- `;var zv=`#ifdef GL_ES
135
+ `;var By=`#ifdef GL_ES
82
136
  precision highp float;
83
137
  precision highp int;
84
138
  #else
@@ -121,6 +175,13 @@ void main(void) {
121
175
  // sample using new coordinates
122
176
  gl_FragColor = texture2D(u_texture, tc);
123
177
  }
124
- `;var mn=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new pn(this.params.fov,this.params.orientation),this.cameraRotationManager=new hn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Yv,this.gl.VERTEX_SHADER),i=this.createShader(zv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,m=t+r;return[s,n,o,u,l,c,d,m]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var be=require("@vkontakte/videoplayer-shared/es2018"),hl=class{constructor(){this.isSeeked$=new be.ValueSubject(!1);this.isBuffering$=new be.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new be.Subscription;this.severeStallOccurred$=new be.ValueSubject(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add((0,be.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,be.debounce)(this.qualityLimitsOnStall.stallDurationToBeCount),(0,be.filter)(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add((0,be.combine)({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if((0,be.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=(0,be.now)(),d=r&&this.currentStallsCount>=r,m=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||m)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,be.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,be.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Kv=hl;var Fe=require("@vkontakte/videoplayer-shared/es2018"),fn=class{constructor(){this.subscription=new Fe.Subscription;this.pipSize$=new Fe.ValueSubject(void 0);this.videoSize$=new Fe.ValueSubject(void 0);this.elementSize$=new Fe.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Fe.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,Fe.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,Fe.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Fe.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 Ti=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new Q("stopped");this.droppedFramesManager=new Ks;this.stallsManager=new Kv;this.elementSizeManager=new fn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new jr;this.audioTrackSwitchHistory=new jr;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==null?void 0: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.hostname$.next(void 0),this.videoState.setState("stopped"),R(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"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&R(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==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return(0,U.assertNever)(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new mn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ke(e.source.url),this.params=e,this.video=Ve(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(Te(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 dn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=_e(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,s=o=>{e.error$.next({id:r,category:U.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,U.filter)(l=>!!l.length),(0,U.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,U.map)(l=>l.to.state!=="none"),(0,U.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,U.filterChanged)()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$,looped$:i.looped$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,U.filter)(U.isNonNullable),(0,U.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,U.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(Be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Xe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if((0,U.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let h of c.audio){m.push(tl(h));let f=[];for(let g of h.representations){let S=$v(g);f.push(S),this.audioTracksMap.set(S,{stream:h,representation:g})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(m)}let d=[];for(let m of c.video){d.push(il(m));let h=[];for(let f of m.representations){let g=Rv({...f,streamId:m.id});g&&(h.push(g),this.videoTracksMap.set(g,{stream:m,representation:f}))}this.videoStreamsMap.set(m,h)}this.params.output.availableVideoStreams$.next(d);for(let m of c.text)for(let h of m.representations){let f=Lv(m,h);this.textTracksMap.set(f,{stream:m,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&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)),this.subscription.add((0,U.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,U.fromEvent)(this.video,"progress")).pipe((0,U.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,Xv.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[m,h]=d,f=[...this.videoTracksMap.keys()].find(S=>{var y;return((y=this.videoTracksMap.get(S))==null?void 0:y.representation.id)===m.id});(0,U.isNonNullable)(f)&&(this.stallsManager.lastVideoTrackSelected=f);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),l==="manifest_ready")await this.player.initRepresentations(m.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),h){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,S)}},r)),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,U.filterChanged)()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:m}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===m.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(il(m))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,U.filterChanged)()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:m}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===m.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(tl(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.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 o=t.playbackState.stateChangeStarted$.pipe((0,U.map)(({to:l})=>l==="ready"),(0,U.filterChanged)());this.subscription.add((0,U.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,U.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,U.merge)(o,this.player.state$.stateChangeEnded$,(0,U.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,U.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var J,W,X,$,Z,_,C,re,ge,L,Y,ae,k;if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(J=e.videoTrack.getState())==null?void 0:J.id,n=[...this.videoTracksMap.keys()].find(({id:B})=>B===r),o=t.currentVideoTrack$.getValue(),u=(($=(X=e.videoStream.getState())!=null?X:n&&((W=this.videoTracksMap.get(n))==null?void 0:W.stream))!=null?$:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:B})=>B===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Zi(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(d/Math.min(m,h||1/0),1),g=(Z=e.audioStream.getState())!=null?Z:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,S=(_=[...this.audioStreamsMap.keys()].find(({id:B})=>B===(g==null?void 0:g.id)))!=null?_:this.audioStreamsMap.keys().next().value,y=0;if(S){if(n&&!i){let B=Ys(n,c,(C=this.audioStreamsMap.get(S))!=null?C:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(re=B==null?void 0:B.bitrate)!=null?re:-1/0)}if(o){let B=Ys(o,c,(ge=this.audioStreamsMap.get(S))!=null?ge:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(L=B==null?void 0:B.bitrate)!=null?L:-1/0)}}let E=zt(c,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:f,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),x=i?E!=null?E:n:n!=null?n:E,w=S&&Db(x,c,(Y=this.audioStreamsMap.get(S))!=null?Y:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=(ae=this.videoTracksMap.get(x))==null?void 0:ae.representation,V=w&&((k=this.audioTracksMap.get(w))==null?void 0:k.representation);if(P&&V)return[P,V];if(P&&!V&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:U.ErrorCategory.DOM,thrown:e}))}destroy(){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),Oe(this.video),this.tracer.end()}};var Da=class extends Ti{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 oe=require("@vkontakte/videoplayer-shared/es2018");var Ca=class extends Ti{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new oe.ValueSubject(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe((0,oe.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,oe.combine)({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,oe.map)(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,oe.filter)(o=>(0,oe.isNonNullable)(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add((0,oe.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,oe.merge)(i.playbackRateState$,new oe.ValueSubject(1))}).pipe((0,oe.filter)(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||(0,oe.isNullable)(l)||(e=o-l)})).add((0,oe.combine)({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,oe.merge)(i.playbackRateState$,new oe.ValueSubject(1))}).pipe((0,oe.filterChanged)((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||(0,oe.isNullable)(o)||(0,oe.isNullable)(u))return;let m=-1*(u-o-e);t.position$.next(Math.min(m,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Mv(o);this.params.output.availableTextTracks$.next([u])}}))}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 Jv=j(Bs(),1);var z=require("@vkontakte/videoplayer-shared/es2018"),ut={};var sr=(a,e)=>new z.Observable(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),Va=class{constructor(e){this.subscription=new z.Subscription;this.videoState=new Q("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,z.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,z.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,z.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,z.assertNever)(e)}break;default:(0,z.assertNever)(t)}};this.textTracksManager=new Ke(e.source.url),this.video=Ve(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),Oe(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:z.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Jv.default)(import("hls.js").then(r=>{e||(ut.Hls=r.default,ut.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){(0,z.assertNonNullable)(ut.Hls,"hls.js not loaded"),this.hls=new ut.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,z.assertNonNullable)(ut.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:z.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=_e(this.video);this.subscription.add(()=>r.destroy());let s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(bt(this.video,e.isLooped,i)),this.subscription.add(Be(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ze(this.video,e.playbackRate,r.playbackRateState$,i)),s(Xe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,z.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(sr(this.hls,ut.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:z.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(sr(this.hls,ut.Events.MANIFEST_PARSED).pipe((0,z.map)(({levels:l})=>l.reduce((c,d)=>{var E,x;let m=d.name||d.height.toString(10),{width:h,height:f}=d,g=(x=Gt((E=d.attrs.QUALITY)!=null?E:""))!=null?x:(0,z.videoSizeToQuality)({width:h,height:f});if(!g)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,y={id:m.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:S};return this.trackLevels.set(m,{track:y,level:d}),c.push(y),c},[]))),t.availableVideoTracks$),s(sr(this.hls,ut.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let m=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:m,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(sr(this.hls,ut.Events.LEVEL_LOADING).pipe((0,z.map)(({url:l})=>Te(l))),t.hostname$),s(sr(this.hls,ut.Events.FRAG_CHANGED),l=>{var m,h,f,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((m=c==null?void 0:c.endPTS)!=null?m:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(Qt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=sr(this.hls,ut.Events.LEVEL_SWITCHED).pipe((0,z.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,z.filter)(z.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Qt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if((0,z.isNullable)(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),m=this.hls.currentLevel,h=this.hls.levels[m];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,z.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,z.observableFrom)(["init"])).pipe((0,z.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:z.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0)}};var Zv="X-Playback-Duration",ml=async a=>{var r;let e=await vt(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Zv)?parseInt(e.headers.get(Zv),10):void 0};var G=require("@vkontakte/videoplayer-shared/es2018");var bl=j(Mo(),1);var bn=require("@vkontakte/videoplayer-shared/es2018");var e$=a=>{let e=null;if(a.QUALITY&&(e=Gt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,bn.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},t$=(a,e)=>{var s,n;let t=a.split(`
125
- `),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,bl.default)(l[1].split(",").map(E=>E.split("="))),m=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=e$(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[E,x]=d.RESOLUTION.split("x").map(w=>parseInt(w,10));E&&x&&(S={width:E,height:x})}let y=new URL(t[++o],e).toString();h&&i.push({id:m,quality:h,url:y,bandwidth:f,size:S,fps:g})}if(c){let d=(0,bl.default)(c[1].split(",").map(g=>{let S=g.indexOf("=");return[g.substring(0,S),g.substring(S+1)]}).map(([g,S])=>[g,S.replace(/^"|"$/g,"")])),m=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;m&&h&&r.push({type:"internal",id:h,label:f,language:h,url:m,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},i$=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),fl=0,eS=async(a,e=a,t,i)=>{let s=await(await vt(a,i)).text();fl+=1;try{let{qualityManifests:n,textTracks:o}=t$(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(fl<=t.manifestRetryMaxCount)return await i$((0,bn.getExponentialDelay)(fl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),eS(a,e,t)}return{qualityManifests:[],textTracks:[]}},gn=eS;var Ge=require("@vkontakte/videoplayer-shared/es2018");var vn=class{constructor(e,t,i,r,s){this.subscription=new Ge.Subscription;this.abortControllers={destroy:new Ae,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Ge.ValueSubject(null);this.getCurrentTime$=new Ge.ValueSubject(null);this.error$=new Ge.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe((0,Ge.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 vt(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(`
126
- `),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),m=new Date(i.programDateTime).valueOf();i.segmentStartTime=m-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,Ge.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 Ae;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(){var t;let e=(t=this.prepareUrl)!=null?t: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:Ge.ErrorCategory.WTF,thrown:t,message:e})}};var Oa=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new Q("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new G.ValueSubject([]);this.liveOffset=new bi;this.manifestStartTime$=new G.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(R(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,G.assertNever)(t)}};var i;this.params=e,this.video=Ve(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:G.VideoQuality.INVARIANT,url:this.params.source.url};let t=(r,s)=>gn(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new vn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ke(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:G.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:G.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new G.ValueSubject((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(m=>m.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:G.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=_e(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.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(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Xe(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,G.filterChanged)(),(0,G.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,G.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(h=>h.id===d);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Te(m.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,G.combine)({startTime:this.manifestStartTime$.pipe((0,G.filter)(G.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,G.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:m})=>({id:u,quality:l,size:c,fps:m,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,G.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),Oe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if((0,G.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[m,h]of[[c,"mq"],[d,"lq"]]){let f=String(parseFloat(m||""));h&&m&&r.searchParams.set(h,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=we(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),ml(n).then(c=>{var d;if(!(0,G.isNullable)(c))this.maxSeekBackTime$.next(c);else{let m=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();((0,G.isNullable)(m)||!isFinite(m))&&vt(n).then(h=>h.text()).then(h=>{var g;let f=(g=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:g[1];if(f){let S=new URL(f,n).toString();ml(S).then(y=>{(0,G.isNullable)(y)||this.maxSeekBackTime$.next(y)})}}).catch(()=>{})}})}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=we(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 te=require("@vkontakte/videoplayer-shared/es2018");var Ba=class{constructor(e){this.subscription=new te.Subscription;this.videoState=new Q("stopped");this.manifests$=new te.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,te.assertNever)(t)}};this.textTracksManager=new Ke(e.source.url),this.params=e,this.video=Ve(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:te.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(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),gn(we(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:te.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(m=>m.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:te.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=_e(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.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,te.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,te.isNonNullable)(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let g=this.manifests$.getValue().find(S=>S.id===f);g&&(this.params.output.currentVideoTrack$.next(g),this.params.output.hostname$.next(Te(g.url)))}let d=this.params.desiredState.playbackRate.getState(),m=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==m){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe((0,te.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:m})=>({id:u,quality:l,size:c,fps:m,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!K.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,te.merge)((0,te.fromEvent)(o,"addtrack"),(0,te.fromEvent)(o,"removetrack"),(0,te.fromEvent)(o,"change"),(0,te.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,te.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,te.observableFrom)(["init"])).pipe((0,te.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Oe(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,te.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:te.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var tS=j(Fi(),1),gl=j(Ki(),1),iS=j(Wt(),1);var le=require("@vkontakte/videoplayer-shared/es2018");var _a=class{constructor(e){this.subscription=new le.Subscription;this.videoState=new Q("stopped");this.trackUrls={};this.textTracksManager=new Ke;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.hostname$.next(void 0),this.videoState.setState("stopped"),R(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==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?R(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return(0,le.assertNever)(e)}};this.params=e,this.video=Ve(e.container,e.tuning),this.params.output.element$.next(this.video),(0,tS.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,gl.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:le.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=_e(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.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,le.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Xe(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,le.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(c),m.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=(0,le.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,le.observableFrom)(["init"])).pipe((0,le.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),Oe(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,le.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,le.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ra(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Te(t))}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:le.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let m=zt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(m)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,gl.default)(this.trackUrls).map(d=>d.track);if(!r||!s||Hr({limits:e,lowestAvailableQuality:(c=(0,iS.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){i();return}let o=e.max?(0,le.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,le.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var ce=require("@vkontakte/videoplayer-shared/es2018");var aS=require("@vkontakte/videoplayer-shared/es2018"),rS=["stun:videostun.mycdn.me:80"],r$=1e3,a$=3,vl=()=>null,Sn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=vl;this.externalStopCallback=vl;this.externalErrorCallback=vl;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:rS}]};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:aS.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),r$)}normalizeOptions(e={}){let t={stunServerList:rS,maxRetryNumber:a$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Na=class{constructor(e){this.videoState=new Q("stopped");this.maxSeekBackTime$=new ce.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(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"),R(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return(0,ce.assertNever)(e)}};this.subscription=new ce.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ve(e.container,e.tuning),this.liveStreamClient=new Sn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Oe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ce.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,ce.merge)(this.videoState.stateChangeStarted$.pipe((0,ce.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ce.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=_e(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(Xe(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Be(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,ce.assertNever)(n.to)}},i)).add((0,ce.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ce.observableFrom)(["init"])).pipe((0,ce.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(Te(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:ce.VideoQuality.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:ce.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ce.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Fa=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var T=require("@vkontakte/videoplayer-shared/es2018");var Lt=require("@vkontakte/videoplayer-shared/es2018"),sS=a=>new Lt.Observable(e=>{let t=new Lt.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Lt.map)(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Lt.map)(({type:l})=>l!==void 0)),n=new Lt.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Je=require("@vkontakte/videoplayer-shared/es2018");function nS(){return new(window.AudioContext||window.webkitAudioContext)}var qa=class qa{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Ae;this.subscriptions=new Je.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Je.filter)(s=>!!s.type),(0,Je.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){K.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Je.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Je.filter)(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,Je.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=nS();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){var t;this.volumeMultiplierError$.next({id:qa.errorId,category:Je.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${qa.errorId} exception`,thrown:e})}};qa.errorId="VolumeMultiplierManager";var nr=qa;var s$={chunkDuration:5e3,maxParallelRequests:5},Ua=class{constructor(e){this.current$=new T.ValueSubject({type:void 0});this.providerError$=new T.Subject;this.noAvailableProvidersError$=new T.Subject;this.volumeMultiplierError$=new T.Subject;this.providerOutput={position$:new T.ValueSubject(0),duration$:new T.ValueSubject(1/0),volume$:new T.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new T.ValueSubject([]),currentVideoStream$:new T.ValueSubject(void 0),availableVideoTracks$:new T.ValueSubject([]),currentVideoTrack$:new T.ValueSubject(void 0),availableAudioStreams$:new T.ValueSubject([]),currentAudioStream$:new T.ValueSubject(void 0),availableAudioTracks$:new T.ValueSubject([]),currentVideoSegmentLength$:new T.ValueSubject(0),currentAudioSegmentLength$:new T.ValueSubject(0),isAudioAvailable$:new T.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new T.ValueSubject(!1),autoVideoTrackLimits$:new T.ValueSubject(void 0),currentBuffer$:new T.ValueSubject(void 0),isBuffering$:new T.ValueSubject(!0),error$:new T.Subject,fetcherError$:new T.Subject,fetcherRecoverableError$:new T.Subject,warning$:new T.Subject,willSeekEvent$:new T.Subject,soundProhibitedEvent$:new T.Subject,seekedEvent$:new T.Subject,loopedEvent$:new T.Subject,endedEvent$:new T.Subject,firstBytesEvent$:new T.Subject,loadedMetadataEvent$:new T.Subject,firstFrameEvent$:new T.Subject,canplay$:new T.Subject,isLive$:new T.ValueSubject(void 0),isLiveEnded$:new T.ValueSubject(null),isLowLatency$:new T.ValueSubject(!1),canChangePlaybackSpeed$:new T.ValueSubject(!0),liveTime$:new T.ValueSubject(void 0),liveBufferTime$:new T.ValueSubject(void 0),liveLatency$:new T.ValueSubject(void 0),severeStallOccurred$:new T.Subject,availableTextTracks$:new T.ValueSubject([]),currentTextTrack$:new T.ValueSubject(void 0),hostname$:new T.ValueSubject(void 0),httpConnectionType$:new T.ValueSubject(void 0),httpConnectionReused$:new T.ValueSubject(void 0),inPiP$:new T.ValueSubject(!1),inFullscreen$:new T.ValueSubject(!1),element$:new T.ValueSubject(void 0),elementVisible$:new T.ValueSubject(!0),availableSources$:new T.ValueSubject(void 0),is3DVideo$:new T.ValueSubject(!1),playbackState$:new T.ValueSubject(""),getCurrentTime$:new T.ValueSubject(null)};this.subscription=new T.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=Hv([...Qv(this.params.tuning),...jv(this.params.tuning)],this.params.tuning).filter(l=>(0,T.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Sl.default)(r,l)),...t.filter(l=>(0,Sl.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,T.flattenObject)(s)),this.screenFormatsIterator=new Fa(s);let n=[...cl(!0),...cl(!1)];this.chromecastFormatsIterator=new Fa(n.filter(l=>(0,T.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&nr.isSupported()&&(this.volumeMultiplierManager=new nr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,T.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:T.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,T.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]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,T.assertNonNullable)(u),new Da({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,T.assertNonNullable)(u),new Ca({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return(0,T.assertNonNullable)(u),K.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Ba({...o,source:u}):new Va({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,T.assertNonNullable)(u),new Oa({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return(0,T.assertNonNullable)(u),new _a({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,T.assertNonNullable)(u),new Hb({...o,source:u,config:{...s$,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,T.assertNonNullable)(u),new Na({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,T.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,T.assertNonNullable)(o),new qr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,T.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,T.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,T.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,uS.default)((0,oS.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new T.Subscription,t=!1,i=0;return e.add((0,T.merge)(this.providerOutput.error$.pipe((0,T.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),sS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,T.map)(r=>({id:`ProviderHangup:${r}`,category:T.ErrorCategory.WTF,message:`A ${r} 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 r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,T.filter)(({to:s})=>s==="playing"),(0,T.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===T.ErrorCategory.NETWORK,u=r.category===T.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s!=null?s:"SCREEN"))}this.tracer.error("providerError",(0,T.flattenObject)(n))})),e}};var F=require("@vkontakte/videoplayer-shared/es2018");var n$=5e3,lS="one_video_throughput",cS="one_video_rtt",Mt=window.navigator.connection,dS=()=>{let a=Mt==null?void 0:Mt.downlink;if((0,F.isNonNullable)(a)&&a!==10)return a*1e3},pS=()=>{let a=Mt==null?void 0:Mt.rtt;if((0,F.isNonNullable)(a)&&a!==3e3)return a},hS=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},yl=class a{constructor(e){this.subscription=new F.Subscription;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(lS)||(e.useBrowserEstimation?dS():void 0)||n$,i=(s=(r=a.load(cS))!=null?r:e.useBrowserEstimation?pS():void 0)!=null?s:0;if(this.throughput$=new F.ValueSubject(t),this.rtt$=new F.ValueSubject(i),this.rttAdjustedThroughput$=new F.ValueSubject(hS(t,i,e.rttPenaltyRequestSize)),this.throughput=yi.getSmoothedValue(t,-1,e),this.rtt=yi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=dS();u&&this.throughput.next(u);let l=pS();(0,F.isNonNullable)(l)&&this.rtt.next(l)};Mt&&"onchange"in Mt&&this.subscription.add((0,F.fromEvent)(Mt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{F.safeStorage.set(lS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{F.safeStorage.set(cS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,F.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,F.map)(({throughput:n,rtt:o})=>hS(n,o,e.rttPenaltyRequestSize)),(0,F.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,F.now)(),r=new F.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,F.fromEvent)(e,"progress").pipe((0,F.once)()).subscribe(s=>{t=s.loaded,i=(0,F.now)()}));break;case 1:case 0:r.add((0,F.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,F.now)()}));break}r.add((0,F.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,F.now)(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=(0,F.now)(),n=0,o=(0,F.now)(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,(0,F.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let m=(0,F.now)();if(m-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||m-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=(0,F.now)()}else n+=d.byteLength;o=(0,F.now)()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,F.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,F.now)()-o,this.concurrentDownloads.size),n=0,o=(0,F.now)());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=F.safeStorage.get(e);if((0,F.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},mS=yl;var Ii=require("@vkontakte/videoplayer-shared/es2018"),fS={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Ii.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Ii.VideoQuality.Q_720P,trafficSavingLimit:Ii.VideoQuality.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ii.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},bS=a=>{var e;return{...(0,Ii.fillWithDefault)(a,fS),configName:[...(e=a.configName)!=null?e:[],...fS.configName]}};var p=require("@vkontakte/videoplayer-shared/es2018");var Dt=require("@vkontakte/videoplayer-shared/es2018"),Tl=({seekState:a,position$:e})=>(0,Dt.merge)(a.stateChangeEnded$.pipe((0,Dt.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,Dt.filter)(Dt.isNonNullable)),e.pipe((0,Dt.filter)(()=>a.getState().state==="none")));var gS=require("@vkontakte/videoplayer-shared/es2018"),vS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,gS.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var yn=require("@vkontakte/videoplayer-shared/es2018"),SS=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,yn.filter)(r=>r.length>0),(0,yn.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var or=class or{constructor(e={configName:[]},t=p.Tracer.createRootTracer(!1)){this.subscription=new p.Subscription;this.logger=new p.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new p.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new p.ValueSubject(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new Q("stopped"),seekState:new Q({state:"none"}),volume:new Q({volume:1,muted:!1}),videoTrack:new Q(void 0),videoStream:new Q(void 0),audioStream:new Q(void 0),autoVideoTrackSwitching:new Q(!0),autoVideoTrackLimits:new Q({}),isLooped:new Q(!1),isLowLatency:new Q(!1),playbackRate:new Q(1),externalTextTracks:new Q([]),internalTextTracks:new Q([]),currentTextTrack:new Q(void 0),textTrackCuesSettings:new Q({}),cameraOrientation:new Q({x:0,y:0})};this.info={playbackState$:new p.ValueSubject(void 0),position$:new p.ValueSubject(0),duration$:new p.ValueSubject(1/0),muted$:new p.ValueSubject(!1),volume$:new p.ValueSubject(1),availableVideoStreams$:new p.ValueSubject([]),currentVideoStream$:new p.ValueSubject(void 0),availableQualities$:new p.ValueSubject([]),availableQualitiesFps$:new p.ValueSubject({}),currentQuality$:new p.ValueSubject(void 0),isAutoQualityEnabled$:new p.ValueSubject(!0),autoQualityLimitingAvailable$:new p.ValueSubject(!1),autoQualityLimits$:new p.ValueSubject({}),predefinedQualityLimitType$:new p.ValueSubject("unknown"),availableAudioStreams$:new p.ValueSubject([]),currentAudioStream$:new p.ValueSubject(void 0),availableAudioTracks$:new p.ValueSubject([]),isAudioAvailable$:new p.ValueSubject(!0),currentPlaybackRate$:new p.ValueSubject(1),currentBuffer$:new p.ValueSubject({start:0,end:0}),isBuffering$:new p.ValueSubject(!0),isStalled$:new p.ValueSubject(!1),isEnded$:new p.ValueSubject(!1),isLooped$:new p.ValueSubject(!1),isLive$:new p.ValueSubject(void 0),isLiveEnded$:new p.ValueSubject(null),canChangePlaybackSpeed$:new p.ValueSubject(void 0),atLiveEdge$:new p.ValueSubject(void 0),atLiveDurationEdge$:new p.ValueSubject(void 0),liveTime$:new p.ValueSubject(void 0),liveBufferTime$:new p.ValueSubject(void 0),liveLatency$:new p.ValueSubject(void 0),currentFormat$:new p.ValueSubject(void 0),availableTextTracks$:new p.ValueSubject([]),currentTextTrack$:new p.ValueSubject(void 0),throughputEstimation$:new p.ValueSubject(void 0),rttEstimation$:new p.ValueSubject(void 0),videoBitrate$:new p.ValueSubject(void 0),hostname$:new p.ValueSubject(void 0),httpConnectionType$:new p.ValueSubject(void 0),httpConnectionReused$:new p.ValueSubject(void 0),surface$:new p.ValueSubject("none"),chromecastState$:new p.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new p.ValueSubject(void 0),intrinsicVideoSize$:new p.ValueSubject(void 0),availableSources$:new p.ValueSubject(void 0),is3DVideo$:new p.ValueSubject(!1),currentVideoSegmentLength$:new p.ValueSubject(0),currentAudioSegmentLength$:new p.ValueSubject(0)};this.events={inited$:new p.Subject,ready$:new p.Subject,started$:new p.Subject,playing$:new p.Subject,paused$:new p.Subject,stopped$:new p.Subject,willStart$:new p.Subject,willResume$:new p.Subject,willPause$:new p.Subject,willStop$:new p.Subject,willDestruct$:new p.Subject,watchCoverageRecord$:new p.Subject,watchCoverageLive$:new p.Subject,managedError$:new p.Subject,fatalError$:new p.Subject,fetcherRecoverableError$:new p.Subject,ended$:new p.Subject,looped$:new p.Subject,seeked$:new p.Subject,willSeek$:new p.Subject,autoplaySoundProhibited$:new p.Subject,firstBytes$:new p.Subject,loadedMetadata$:new p.Subject,firstFrame$:new p.Subject,canplay$:new p.Subject,log$:new p.Subject,fetcherError$:new p.Subject,severeStallOccured$:new p.Subject};this.experimental={element$:new p.ValueSubject(void 0),tuningConfigName$:new p.ValueSubject([]),enableDebugTelemetry$:new p.ValueSubject(!1),dumpTelemetry:wb,getCurrentTime$:new p.ValueSubject(null)};if(this.initLogs(),this.tuning=bS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ls({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new mS(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new p.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(m=>JSON.stringify(m,(h,f)=>{let g=typeof f;return(0,yS.default)(["number","string","boolean"],g)?f:f===null?null:`<${g}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:p.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}static withFiniteDuration(e,t,i){let r=i.value;return i.value=function(...s){return this.subscription.add((0,p.combine)({inited:this.playerInited.pipe((0,p.filter)(n=>!!n)),duration:this.info.duration$.pipe((0,p.filter)(n=>Number.isFinite(n)))}).pipe((0,p.once)()).subscribe(()=>{r.apply(this,s)})),this},i}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var u,l,c;let{container:n,...o}=e;this.tracer.log("initVideo",(0,p.flattenObject)(o)),this.domContainer=vS(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Ua({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?K.isInited$.pipe((0,p.filter)(n=>!!n),(0,p.once)()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),(0,p.fromEvent)(document,"visibilitychange").pipe((0,p.once)()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe((0,p.filter)(e=>!!e),(0,p.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe((0,p.filter)(e=>!!e),(0,p.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe((0,p.filter)(e=>!!e),(0,p.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe((0,p.filter)(e=>!!e),(0,p.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){let i=this.info.duration$.getValue();if(!i||!Number.isFinite(e))return this;let r=e;return i<0?(e>0&&(r=-e),r<i&&(r=i)):e>i?r=i-this.tuning.seekNearDurationBias:e<0&&(r=Math.max(0,i+e)),this.tracer.log("seekTime",{duration:i,isLive:this.info.isLive$.getValue(),time:e,calculatedTime:r,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:r}),this.desiredState.seekState.setState({state:"requested",position:r*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),this.seekTime(Math.abs(t)*e,!1),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe((0,p.filter)(i=>!!i),(0,p.once)()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e){return this.subscription.add(this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{var n;let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,r=t.getTransition(),s=(n=r==null?void 0:r.to.volume)!=null?n:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:s,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:s,muted:i})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{(0,p.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,p.filter)(i=>i.length>0),(0,p.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",(0,p.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{var i;(0,p.assertNonNullable)(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",(0,p.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{var t;SS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe((0,p.filter)(i=>!!i),(0,p.once)()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe((0,p.filter)(i=>!!i),(0,p.once)()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe((0,p.filter)(e=>e),(0,p.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe((0,p.filter)(e=>!!e),(0,p.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,p.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,p.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(ku({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.filter)(({from:e})=>e==="stopped"),(0,p.once)()).subscribe(()=>{this.initedAt=(0,p.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,p.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:p.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,p.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,p.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,p.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,p.map)(n=>n.destination),(0,p.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,p.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,p.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,p.isInvariantQuality)(u)?1:(0,p.isInvariantQuality)(l)?-1:(0,p.isHigher)(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,p.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe((0,p.filter)(n=>(0,p.isNonNullable)(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,p.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,p.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,p.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,p.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe((0,p.tap)(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add((0,p.combine)({hasLiveOffsetByPaused:(0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(n=>n.to),(0,p.filterChanged)(),(0,p.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,p.combine)({atLiveEdge:(0,p.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Tl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,p.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,p.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,p.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,p.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.muted),(0,p.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.volume),(0,p.filterChanged)()).subscribe(this.info.volume$)).add(Tl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,p.merge)(e.providerOutput.endedEvent$.pipe((0,p.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,p.mapTo)(!1))).pipe((0,p.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,p.map)(n=>({id:n?`No${n}`:"NoProviders",category:p.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe((0,p.once)(),(0,p.map)(n=>n!=null?n:(0,p.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new p.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new p.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.filter)(({to:n})=>n==="playing"),(0,p.once)()).subscribe(()=>i.next(!1)));let r=0,s=(0,p.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,p.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,p.filterChanged)());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,p.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,p.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,p.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new p.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,p.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,p.filter)(i=>i.length>0),(0,p.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=zt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,p.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,p.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,p.assertNonNullable)(this.providerContainer),(0,p.assertNonNullable)(e),Pb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>xb(i)),this.providerContainer.current$.subscribe(({type:i})=>Ur("provider",i)),e.duration$.subscribe(i=>Ur("duration",i)),e.availableVideoTracks$.pipe((0,p.filter)(i=>!!i.length),(0,p.once)()).subscribe(i=>Ur("tracks",i)),this.events.fatalError$.subscribe(new $e("fatalError")),this.events.managedError$.subscribe(new $e("managedError")),e.position$.subscribe(new $e("position")),e.currentVideoTrack$.pipe((0,p.map)(i=>i==null?void 0:i.quality)).subscribe(new $e("quality")),this.info.currentBuffer$.subscribe(new $e("buffer")),e.isBuffering$.subscribe(new $e("isBuffering"))].forEach(i=>this.subscription.add(i)),Ur("codecs",K.video.supportedCodecs)}initTracerSubscription(){let e=(0,p.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,p.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,p.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,p.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,p.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,p.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,p.filter)(i=>i>0),(0,p.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,p.filter)(i=>i>0),(0,p.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,p.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,p.filter)(i=>i.end>0),(0,p.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,p.filterChanged)())}).pipe((0,p.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,p.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,p.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,p.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,p.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,p.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,p.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,p.filterChanged)(),(0,p.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,p.filterChanged)(),(0,p.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,p.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,p.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,p.filterChanged)(),(0,p.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,p.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,p.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,p.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,p.filterChanged)(),(0,p.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:p.ErrorCategory.DOM,message:String(r)})})};this.subscription.add((0,p.merge)((0,p.fromEvent)(document,"visibilitychange"),(0,p.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,p.flattenObject)({quality:t,availableTracks:(0,p.flattenObject)(e),track:(0,p.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Yr()}};wn([or.withFiniteDuration],or.prototype,"seekTime",1),wn([or.withFiniteDuration],or.prototype,"seekPercent",1);var Ha=or;var St=require("@vkontakte/videoplayer-shared/es2018"),o$=`@vkontakte/videoplayer-core@${An}`;
178
+ `;var ls=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Au(this.params.fov,this.params.orientation),this.cameraRotationManager=new Pu(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader($y,this.gl.VERTEX_SHADER),i=this.createShader(By,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,p=t+r;return[a,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Ae=require("@vkontakte/videoplayer-shared/es2018");var ku="stalls_manager_metrics",ZM="stalls_manager_abr_params",Md=class{constructor(){this.isSeeked$=new Ae.ValueSubject(!1);this.isBuffering$=new Ae.ValueSubject(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Ae.Subscription;this.severeStallOccurred$=new Ae.ValueSubject(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){return this.abrParams}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,Ae.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=((0,Ae.now)()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}updateStoredAbrParams(){let e=[],t=this.getStoredData(ku,"[]");if(t.length<this.tuning.stallsMetricsHistoryLength)return;if(this.tuning.useTotalStallsDurationPerTvt){let r=t.reduce((o,u)=>o+u.tvt,0),n=t.reduce((o,u)=>o+u.stallsDuration,0)/r;e.push(this.calculateOptimalAbrParams(n))}if(this.tuning.useAverageStallsDurationPerTvt){let r=t.reduce((a,n)=>a+n.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(r))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed));let i={bitrateFactorAtEmptyBuffer:Math.max(...e.map(r=>r.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(r=>r.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(r=>r.containerSizeFactor))};this.setStoredData(ku,[]),this.setStoredData(ZM,i)}calculateOptimalAbrParams(e){let{targetStallsDurationPerTvt:t,deviationStallsDurationPerTvt:i,criticalStallsDurationPerTvt:r,abrAdjustingSpeed:a}=this.tuning,n=this.abrTuningParams;return e<t-i?n={bitrateFactorAtEmptyBuffer:Math.max(n.bitrateFactorAtEmptyBuffer-a,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(n.bitrateFactorAtFullBuffer-a,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(n.containerSizeFactor+a,this.abrParams.maxContainerSizeFactor)}:e>t+i&&(n={bitrateFactorAtEmptyBuffer:Math.min(n.bitrateFactorAtEmptyBuffer+a,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(n.bitrateFactorAtFullBuffer+a,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(n.containerSizeFactor-a,this.abrParams.minContainerSizeFactor)}),e>r&&(n={bitrateFactorAtEmptyBuffer:Math.max(n.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(n.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(n.containerSizeFactor,this.abrParams.containerSizeFactor)}),n}getStoredData(e,t="{}"){var i;return JSON.parse((i=Ae.safeStorage.get(e))!=null?i:t)}setStoredData(e,t){Ae.safeStorage.set(e,JSON.stringify(t))}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(ku,"[]"),r=t/e,a=i.length?Ci(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(ku,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe((0,Ae.once)()).subscribe(t=>this.providerStartWatchingTimestamp=(0,Ae.now)())),this.subscription.add(this.currentStallDuration$.pipe((0,Ae.filterChanged)()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if((0,Ae.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=(0,Ae.now)(),c=r&&this.currentStallsCount>=r,p=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Ae.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&(0,Ae.now)()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},Ru=Md;var yt=require("@vkontakte/videoplayer-shared/es2018"),Lu=class{constructor(){this.subscription=new yt.Subscription;this.pipSize$=new yt.ValueSubject(void 0);this.videoSize$=new yt.ValueSubject(void 0);this.elementSize$=new yt.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=yt.noop}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add((0,yt.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,yt.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,yt.map)(({videoSize:r,inPip:a,pipSize:n})=>a?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 Er=class{constructor(e){this.subscription=new ae.Subscription;this.videoState=new te("stopped");this.droppedFramesManager=new Zr;this.stallsManager=new Ru;this.elementSizeManager=new Lu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ki;this.audioTrackSwitchHistory=new Ki;this.selectedRepresentations={audio:null,video:null};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==null?void 0: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.hostname$.next(void 0),this.videoState.setState("stopped"),V(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"),V(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&V(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==null?void 0:i.to)==="playing"&&V(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&V(this.params.desiredState.playbackState,"paused");return;default:return(0,ae.assertNever)(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new ls(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.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 St(e.source.url),this.params=e,this.video=et(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(qe(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 wu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=rt(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:ae.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,ae.filter)(c=>!!c.length),(0,ae.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,ae.map)(c=>c.to.state!=="none"),(0,ae.filterChanged)());this.stallsManager.connect({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$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,ae.filter)(ae.isNonNullable),(0,ae.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,ae.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(c=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ft(this.video,t.isLooped,r)),this.subscription.add(it(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(gt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(vt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),V(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),V(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams();if((0,ae.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of p.audio){f.push(yd(b));let S=[];for(let v of b.representations){let y=my(v);S.push(y),this.audioTracksMap.set(y,{stream:b,representation:v})}this.audioStreamsMap.set(b,S)}this.params.output.availableAudioStreams$.next(f)}let h=[];for(let f of p.video){h.push(Td(f));let b=[];for(let S of f.representations){let v=fy({...S,streamId:f.id});v&&(b.push(v),this.videoTracksMap.set(v,{stream:f,representation:S}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(h);for(let f of p.text)for(let b of f.representations){let S=by(f,b);this.textTracksMap.set(S,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&vy(o)||null;this.subscription.add((0,ae.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,ae.fromEvent)(this.video,"progress")).pipe((0,ae.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||p||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:f}=this.selectedRepresentations;if(!h)return;let b=xr(this.videoTracksMap.keys(),v=>{var y;return((y=this.videoTracksMap.get(v))==null?void 0:y.representation.id)===h.id});(0,ae.isNonNullable)(b)&&(this.stallsManager.lastVideoTrackSelected=b);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),c==="manifest_ready")await this.player.initRepresentations(h.id,f==null?void 0:f.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),f){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,v)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,ae.filterChanged)()).subscribe(c=>{let p=xr(this.videoTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=p,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Td(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,ae.filterChanged)()).subscribe(c=>{let p=xr(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=p,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(yd(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var p,h;if(c!=null&&c.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe((0,ae.map)(({to:c})=>c==="ready"),(0,ae.filterChanged)());this.subscription.add((0,ae.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,ae.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,ae.merge)(l,this.player.state$.stateChangeEnded$,(0,ae.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=(0,ae.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,ae.observableFrom)(["init"])).pipe((0,ae.debounce)(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var F,O,B,H,N,_,ne,K,M,z,D,R;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Pa:Aa,t=this.params.tuning.useNewAutoSelectVideoTrack?iu:tu,i=this.params.tuning.useNewAutoSelectVideoTrack?ci:eu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(F=r.videoTrack.getState())==null?void 0:F.id,u=xr(this.videoTracksMap.keys(),C=>C.id===o),l=a.currentVideoTrack$.getValue(),d=((H=(B=r.videoStream.getState())!=null?B:u&&((O=this.videoTracksMap.get(u))==null?void 0:O.stream))!=null?H:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=xr(this.videoStreamsMap.keys(),C=>C.id===d.id),p=c&&this.videoStreamsMap.get(c);if(!p)return;let h=Re(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 b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,b||1/0),1),v=(N=r.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(v==null?void 0:v.id)&&xr(this.audioStreamsMap.keys(),C=>C.id===v.id)||this.audioStreamsMap.keys().next().value,x=0;if(y){if(u&&!n){let C=e(u,p,(_=this.audioStreamsMap.get(y))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(ne=C==null?void 0:C.bitrate)!=null?ne:-1/0)}if(l){let C=e(l,p,(K=this.audioStreamsMap.get(y))!=null?K:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(M=C==null?void 0:C.bitrate)!=null?M:-1/0)}}let A=u;(n||!A)&&(A=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:x,forwardBufferHealth:S,current:l,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 w=y&&t(A,p,(z=this.audioStreamsMap.get(y))!=null?z:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),L=(D=this.videoTracksMap.get(A))==null?void 0:D.representation,q=w&&((R=this.audioTracksMap.get(w))==null?void 0:R.representation);L&&q?(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=q):L&&!q&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){st(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),V(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ae.ErrorCategory.DOM,thrown:e}))}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),tt(this.video),this.tracer.end()}};var bn=class extends Er{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 Se=require("@vkontakte/videoplayer-shared/es2018");var gn=class extends Er{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new Se.ValueSubject(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe((0,Se.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,Se.combine)({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Se.map)(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,Se.filter)(o=>(0,Se.isNonNullable)(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add((0,Se.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,Se.merge)(i.playbackRateState$,new Se.ValueSubject(1))}).pipe((0,Se.filter)(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||(0,Se.isNullable)(l)||(e=o-l)})).add((0,Se.combine)({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,Se.merge)(i.playbackRateState$,new Se.ValueSubject(1))}).pipe((0,Se.filterChanged)((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||(0,Se.isNullable)(o)||(0,Se.isNullable)(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=gy(o);this.params.output.availableTextTracks$.next([u])}}))}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 ue=require("@vkontakte/videoplayer-shared/es2018");var jd=Y(Ca(),1);var I=require("@vkontakte/videoplayer-shared/es2018");var Mu=Y(_t(),1),ds=Y(Zt(),1),$u=Y(Ca(),1);var tT=Y(xa(),1);var tr=require("@vkontakte/videoplayer-shared/es2018");var t$=18,Dy=!1;try{Dy=J.browser.isSafari&&!!J.browser.safariVersion&&J.browser.safariVersion<=t$}catch(s){console.error(s)}var $d=class{constructor(e){this.bufferFull$=new tr.Subject;this.error$=new tr.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:tr.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};Dy&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!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(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:tr.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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,tr.assertNever)(t)}}},Cy=$d;var P=require("@vkontakte/videoplayer-shared/es2018");var he=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>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}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 cs=class extends he{};var Sn=class extends he{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var vn=class extends he{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var yn=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Te=class extends he{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Tn=class extends Te{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var In=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var xn=class extends he{constructor(e,t){super(e,t),this.data=this.content}};var wr=class extends Te{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var En=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wn=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var An=class extends Te{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Pn=class extends Te{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var kn=class extends Te{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Rn=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ln=class extends Te{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 Mn=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var $n=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Bn=class extends Te{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Dn=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Cn=class extends Te{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 Vn=class extends Te{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 On=class extends Te{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 _n=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fn=class extends Te{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Nn=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var r$={ftyp:vn,moov:yn,mvhd:Tn,moof:In,mdat:xn,sidx:wr,trak:En,mdia:Rn,mfhd:Bn,tkhd:Ln,traf:Dn,tfhd:Cn,tfdt:Vn,trun:On,minf:Mn,sv3d:wn,st3d:An,prhd:Pn,proj:$n,equi:kn,uuid:Sn,stbl:_n,stsd:Fn,avc1:Nn,unknown:cs},Oi=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=r$[e];return i?new i(t,new s):new cs(t,new s)}};var ir=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var a$=new TextDecoder("ascii"),n$=s=>a$.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",o$=s=>{let e=new wr(s,new Oi),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},u$=(s,e)=>{let i=new Oi().parse(s),r=new ir(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},l$=s=>{let t=new Oi().parse(s),i=new ir(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},c$=s=>{var r;let t=new Oi().parse(s);return(r=new ir(t).find("sidx"))==null?void 0:r.timescale},d$=(s,e)=>{let i=new Oi().parse(s),a=new ir(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},p$=s=>{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 Oi().parse(s),r=new ir(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},Vy={validateData:n$,parseInit:p$,getIndexRange:()=>{},parseSegments:o$,parseFeedableSegmentChunk:u$,getChunkEndTime:d$,getServerLatencyTimestamps:l$,getTimescaleFromIndex:c$};var qn=Y(_t(),1),_i=require("@vkontakte/videoplayer-shared/es2018");var _y=require("@vkontakte/videoplayer-shared/es2018");var Oy={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"}},Fy=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Un(s,t),r=i in Oy,a=r?Oy[i].type:"binary",n=s.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(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=Un(u),c=l*2**((o-1)*8)+d,p=t+o,h;return p+c>s.byteLength?h=new DataView(s.buffer,s.byteOffset+p):h=new DataView(s.buffer,s.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},Un=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ti=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Un(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:(0,_y.assertNever)(e)}},Ar=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Fy(i);if(!e(r))return;r.type==="master"&&Ar(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Ny=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Fy(s);return Ar(r.value,({tag:a,type:n,value:o})=>(a===17143?e=ti(o,n):a===17026?t=ti(o,n):a===17029&&(i=ti(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Uy=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],h$=[231,22612,22743,167,171,163,160,175],f$=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return Ar(s,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let S=ti(f,h);l=Un(S)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?a=!0:p===290298740?n=!0:p===2807729?i=ti(f,h):p===17545?r=ti(f,h):p===21420&&l===475249515?u=ti(f,h):p===374648427?Ar(f,({tag:S,type:v,value:y})=>S===30321?(d=ti(y,v)===1,!1):!0):a&&n&&(0,qn.default)(Uy,p)&&(o=!0),!o}),(0,_i.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,_i.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,_i.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},m$=s=>{if((0,_i.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},b$=(s,e)=>{let t=!1,i=!1,r=o=>(0,_i.isNonNullable)(o.time)&&(0,_i.isNonNullable)(o.position),a=[],n;return Ar(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=ti(l,u));break;case 183:break;case 241:n&&(n.position=ti(l,u));break;default:t&&(0,qn.default)(Uy,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},g$=s=>{let e=0,t=!1;try{Ar(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,qn.default)(h$,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,qn.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},qy={validateData:Ny,parseInit:f$,getIndexRange:m$,parseSegments:b$,parseFeedableSegmentChunk:g$};var jn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return qy;case"mp4":return Vy}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Fd=Y(bd(),1),Xy=Y(pr(),1),Jy=Y(gd(),1),Zy=Y(Zt(),1),Nd=Y(Sr(),1);var Gn=require("@vkontakte/videoplayer-shared/es2018");var jy=s=>{var e;try{let t=S$(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function S$(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
179
+ (?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
180
+ (-(?<script>[a-z]{4}))?
181
+ (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
182
+ (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
183
+ (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
184
+ (?:-(?<privateuse>(?:${e})))?
185
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Cd=Y(Zt(),1);var Hy=require("@vkontakte/videoplayer-shared/es2018"),Gy=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?li(a):void 0)!=null?u:(0,Hy.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},zy=({id:s,bitrate:e})=>({id:s,bitrate:e}),Qy=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Wy=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Vd=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Cd.default)(i.split("."),0),isDefault:r}),Od=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Cd.default)(r.split("."),0)}),_d=s=>"url"in s,bt=s=>s.type==="template",Hn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Yy=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},Pr=(s,e)=>{for(let t of s)if(e(t))return t;return null};var Ky=s=>{if(!(s!=null&&s.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(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Fi=(s,e)=>{let t=s;t=(0,Fd.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Xy.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Fd.default)(t,n,(o,u)=>(0,Gn.isNullable)(a)?o:(0,Gn.isNullable)(u)?a:(0,Jy.default)(a,parseInt(u,10),"0"))}return t},eT=(s,e)=>{var O,B,H,N,_,ne,K,M,z,D,R,C,Le,It,xt,de,Ve,Oe,_e,Xe,Ot,qt,ri,fi,ji,fs,ms,bs,gs,Ss,vs,ys,Ts,Is,xs,Es,ws,As,Ps,ks,Rs,Ls,Ms,$s,Bs,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,Gs,zs,Qs,Ws,Ys;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(xe=>{var G,nt;return(nt=(G=xe.textContent)==null?void 0:G.trim())!=null?nt:""}),o=(O=(0,Zy.default)(n,0))!=null?O:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],p=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let v,y=a.getAttribute("mediaPresentationDuration"),x=[...a.getElementsByTagName("Period")],A=x.reduce((xe,G)=>({...xe,[G.id]:G.children}),{}),w=x.reduce((xe,G)=>({...xe,[G.id]:G.getAttribute("duration")}),{});y?v=Ky(y):(0,Nd.default)(w).filter(xe=>xe).length&&!u?v=(0,Nd.default)(w).reduce((xe,G)=>{var nt;return xe+((nt=Ky(G))!=null?nt:0)},0):b&&(v=parseInt(b,10));let L=0,q=(H=(B=a.getAttribute("profiles"))==null?void 0:B.split(","))!=null?H:[];for(let xe of x.map(G=>G.id))for(let G of A[xe]){let nt=(N=G.getAttribute("id"))!=null?N:"id"+(L++).toString(10),jt=(_=G.getAttribute("mimeType"))!=null?_:"",rr=(ne=G.getAttribute("codecs"))!=null?ne:"",sr=(K=G.getAttribute("contentType"))!=null?K:jt==null?void 0:jt.split("/")[0],ju=(z=(M=G.getAttribute("profiles"))==null?void 0:M.split(","))!=null?z:[],Ks=(R=jy((D=G.getAttribute("lang"))!=null?D:""))!=null?R:{},mi=(It=(Le=(C=G.querySelector("Label"))==null?void 0:C.textContent)==null?void 0:Le.trim())!=null?It:void 0,Hu=G.querySelectorAll("Representation"),Gu=G.querySelector("SegmentTemplate"),zu=(de=(xt=G.querySelector("Role"))==null?void 0:xt.getAttribute("value"))!=null?de:void 0,Et=sr,se={id:nt,language:Ks.language,isDefault:zu==="main",label:mi,codecs:rr,hdr:Et==="video"&&ns(rr),mime:jt,representations:[]};for(let j of Hu){let je=(Ve=j.getAttribute("lang"))!=null?Ve:void 0,Ht=(_e=(Oe=mi!=null?mi:G.getAttribute("label"))!=null?Oe:j.getAttribute("label"))!=null?_e:void 0,bi=(qt=(Ot=(Xe=j.querySelector("BaseURL"))==null?void 0:Xe.textContent)==null?void 0:Ot.trim())!=null?qt:"",ot=new URL(bi||o,e).toString(),He=(ri=j.getAttribute("mimeType"))!=null?ri:jt,gi=(ji=(fi=j.getAttribute("codecs"))!=null?fi:rr)!=null?ji:"",Si;if(sr==="text"){let Ge=j.getAttribute("id")||"",vi=((fs=Ks.privateuse)==null?void 0:fs.includes("x-auto"))||Ge.includes("_auto"),ut=j.querySelector("SegmentTemplate");if(ut){let Gt={representationId:(ms=j.getAttribute("id"))!=null?ms:void 0,bandwidth:(bs=j.getAttribute("bandwidth"))!=null?bs:void 0},yi=parseInt((gs=j.getAttribute("bandwidth"))!=null?gs:"",10)/1e3,Ti=(vs=parseInt((Ss=ut.getAttribute("startNumber"))!=null?Ss:"",10))!=null?vs:1,wt=parseInt((ys=ut.getAttribute("timescale"))!=null?ys:"",10),ar=(Ts=ut.querySelectorAll("SegmentTimeline S"))!=null?Ts:[],At=ut.getAttribute("media");if(!At)continue;let Ii=[],xi=0,Ei="",Pt=0,zt=Ti,fe=0;for(let Ee of ar){let lt=parseInt((Is=Ee.getAttribute("d"))!=null?Is:"",10),ge=parseInt((xs=Ee.getAttribute("r"))!=null?xs:"",10)||0,ze=parseInt((Es=Ee.getAttribute("t"))!=null?Es:"",10);fe=Number.isFinite(ze)?ze:fe;let ct=lt/wt*1e3,Qe=fe/wt*1e3;for(let Me=0;Me<ge+1;Me++){let We=Fi(At,{...Gt,segmentNumber:zt.toString(10),segmentTime:(fe+Me*lt).toString(10)}),kt=(Qe!=null?Qe:0)+Me*ct,Wt=kt+ct;zt++,Ii.push({time:{from:kt,to:Wt},url:We})}fe+=(ge+1)*lt,xi+=(ge+1)*ct}Pt=fe/wt*1e3,Ei=Fi(At,{...Gt,segmentNumber:zt.toString(10),segmentTime:fe.toString(10)});let Qt={time:{from:Pt,to:1/0},url:Ei},Fe={type:"template",baseUrl:ot,segmentTemplateUrl:At,initUrl:"",totalSegmentsDurationMs:xi,segments:Ii,nextSegmentBeyondManifest:Qt,timescale:wt};Si={id:Ge,kind:"text",segmentReference:Fe,profiles:[],duration:v,bitrate:yi,mime:"",codecs:"",width:0,height:0,isAuto:vi}}else Si={id:Ge,isAuto:vi,kind:"text",url:ot}}else{let Ge=(As=(ws=j.getAttribute("contentType"))!=null?ws:He==null?void 0:He.split("/")[0])!=null?As:sr,vi=(ks=(Ps=G.getAttribute("profiles"))==null?void 0:Ps.split(","))!=null?ks:[],ut=parseInt((Rs=j.getAttribute("width"))!=null?Rs:"",10),Gt=parseInt((Ls=j.getAttribute("height"))!=null?Ls:"",10),yi=parseInt((Ms=j.getAttribute("bandwidth"))!=null?Ms:"",10)/1e3,Ti=($s=j.getAttribute("frameRate"))!=null?$s:"",wt=(Bs=j.getAttribute("quality"))!=null?Bs:void 0,ar=Ti?uu(Ti):void 0,At=(Ds=j.getAttribute("id"))!=null?Ds:"id"+(L++).toString(10),Ii=Ge==="video"?`${Gt}p`:Ge==="audio"?`${yi}Kbps`:gi,xi=`${At}@${Ii}`,Ei=[...q,...ju,...vi],Pt,zt=j.querySelector("SegmentBase"),fe=(Cs=j.querySelector("SegmentTemplate"))!=null?Cs:Gu;if(zt){let Fe=(Os=(Vs=j.querySelector("SegmentBase Initialization"))==null?void 0:Vs.getAttribute("range"))!=null?Os:"",[Ee,lt]=Fe.split("-").map(We=>parseInt(We,10)),ge={from:Ee,to:lt},ze=(_s=j.querySelector("SegmentBase"))==null?void 0:_s.getAttribute("indexRange"),[ct,Qe]=ze?ze.split("-").map(We=>parseInt(We,10)):[],Me=ze?{from:ct,to:Qe}:void 0;Pt={type:"byteRange",url:ot,initRange:ge,indexRange:Me}}else if(fe){let Fe={representationId:(Fs=j.getAttribute("id"))!=null?Fs:void 0,bandwidth:(Ns=j.getAttribute("bandwidth"))!=null?Ns:void 0},Ee=parseInt((Us=fe.getAttribute("timescale"))!=null?Us:"",10),lt=(qs=fe.getAttribute("initialization"))!=null?qs:"",ge=fe.getAttribute("media"),ze=(Hs=parseInt((js=fe.getAttribute("startNumber"))!=null?js:"",10))!=null?Hs:1,ct=Fi(lt,Fe);if(!ge)throw new ReferenceError("No media attribute in SegmentTemplate");let Qe=(Gs=fe.querySelectorAll("SegmentTimeline S"))!=null?Gs:[],Me=[],We=0,kt="",Wt=0;if(Qe.length){let wi=ze,we=0;for(let Rt of Qe){let $e=parseInt((zs=Rt.getAttribute("d"))!=null?zs:"",10),dt=parseInt((Qs=Rt.getAttribute("r"))!=null?Qs:"",10)||0,Ai=parseInt((Ws=Rt.getAttribute("t"))!=null?Ws:"",10);we=Number.isFinite(Ai)?Ai:we;let nr=$e/Ee*1e3,or=we/Ee*1e3;for(let Pi=0;Pi<dt+1;Pi++){let Wu=Fi(ge,{...Fe,segmentNumber:wi.toString(10),segmentTime:(we+Pi*$e).toString(10)}),Xs=(or!=null?or:0)+Pi*nr,Yu=Xs+nr;wi++,Me.push({time:{from:Xs,to:Yu},url:Wu})}we+=(dt+1)*$e,We+=(dt+1)*nr}Wt=we/Ee*1e3,kt=Fi(ge,{...Fe,segmentNumber:wi.toString(10),segmentTime:we.toString(10)})}else if((0,Gn.isNonNullable)(v)){let we=parseInt((Ys=fe.getAttribute("duration"))!=null?Ys:"",10)/Ee*1e3,Rt=Math.ceil(v/we),$e=0;for(let dt=1;dt<Rt;dt++){let Ai=Fi(ge,{...Fe,segmentNumber:dt.toString(10),segmentTime:$e.toString(10)});Me.push({time:{from:$e,to:$e+we},url:Ai}),$e+=we}Wt=$e,kt=Fi(ge,{...Fe,segmentNumber:Rt.toString(10),segmentTime:$e.toString(10)})}let Qu={time:{from:Wt,to:1/0},url:kt};Pt={type:"template",baseUrl:ot,segmentTemplateUrl:ge,initUrl:ct,totalSegmentsDurationMs:We,segments:Me,nextSegmentBeyondManifest:Qu,timescale:Ee}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ge||!He)continue;let Qt={video:"video",audio:"audio",text:"text"}[Ge];if(!Qt)continue;Et||(Et=Qt),Si={id:xi,kind:Qt,segmentReference:Pt,profiles:Ei,duration:v,bitrate:yi,mime:He,codecs:gi,width:ut,height:Gt,fps:ar,quality:wt}}se.language||(se.language=je),se.label||(se.label=Ht),se.mime||(se.mime=He),se.codecs||(se.codecs=gi),se.hdr||(se.hdr=Et==="video"&&ns(gi)),se.representations.push(Si)}if(Et){let j=r[Et].find(je=>je.id===se.id);if(j&&se.representations.every(je=>bt(je.segmentReference)))for(let je of j.representations){let Ht=se.representations.find(He=>He.id===je.id),bi=Ht==null?void 0:Ht.segmentReference,ot=je.segmentReference;ot.segments.push(...bi.segments),ot.nextSegmentBeyondManifest=bi.nextSegmentBeyondManifest}else r[Et].push(se)}}return{duration:v,streams:r,baseUrls:n,live:S}};var zn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new P.ValueSubject(0);this.currentLowLatencySegmentLength$=new P.ValueSubject(0);this.currentSegmentLength$=new P.ValueSubject(0);this.onLastSegment$=new P.ValueSubject(!1);this.fullyBuffered$=new P.ValueSubject(!1);this.playingRepresentation$=new P.ValueSubject(void 0);this.playingRepresentationInit$=new P.ValueSubject(void 0);this.error$=new P.Subject;this.gaps=[];this.subscription=new P.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new be;this.switchAbortController=new be;this.destroyAbortController=new be;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,P.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,P.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 Cy(this.sourceBuffer),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:P.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Z(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,rs(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Re(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"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),a=this.parsedInitData.get(t.id);(0,P.assertNonNullable)(i,"No init buffer for starting representation"),(0,P.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=(0,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,P.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,P.isNullable)(a)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,P.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,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,P.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,P.isNullable)(a)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,P.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,P.abortable)(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,$u.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let p=this.representations.get(d);if(!p||!bt(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,P.assertNonNullable)(r);let a=this.segments.get(i);(0,P.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,P.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new be,(0,P.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,P.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,P.isNullable)(o)||(0,P.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,P.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Z(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,P.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!(0,P.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 be,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,P.isNullable)(e)||(0,P.isNullable)(this.downloadingRepresentationId)||(0,P.isNullable)(this.playingRepresentationId)||(0,P.isNullable)(this.sourceBuffer)||!Z(this.mediaSource,this.sourceBuffer)||(0,P.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,P.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);(0,P.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=Re(this.sourceBuffer.buffered,e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&rs(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Re(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(p=>{this.handleAsyncError(p,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u!=null&&u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Mu.default)(u,r))d="high";else{let c=(0,ds.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&Re(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,ds.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Re(this.sourceBuffer.buffered,e)<n),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 a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;(0,P.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,$u.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,$u.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!bt(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,ds.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>c>=h.time.from+l&&c<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...d,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,P.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!bt(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.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),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=Fi(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&pi&&pi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&pi&&pi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:p,to:h}},f)=>{let b=p<=i&&h>=i,S=p>i||b||f===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+v||h<=i+v;return(c==="none"||c==="partially_ejected"&&S&&y&&this.sourceBuffer&&Z(this.mediaSource,this.sourceBuffer)&&!(at(this.sourceBuffer.buffered,p)&&at(this.sourceBuffer.buffered,h)))&&S&&y});if(r===-1)return null;if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){let p=a[c];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){bt(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:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,P.abortable)(o,async function*(){let d=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,P.now)(),!d)return;let c=new DataView(d),p=jn(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(c,b)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Hn(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())bt(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:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,P.abortable)(n,async function*(){let u=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,P.fromEvent)(window,"online").pipe((0,P.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,P.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Hn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(bt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,ds.default)(e,0).byte.from,to:(0,ds.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!bt(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:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Mu.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!Z(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(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=jn(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&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:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Z(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,d=l.byte.from-i,c=l.byte.to-i,p=c-d+1,h=d<r,f=c<=r;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(b,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-d),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?b:jn(o.mime).parseFeedableSegmentChunk(b);S!=null&&S.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!((0,P.isNullable)(this.sourceBuffer)||!Z(this.mediaSource,this.sourceBuffer))){!this.isLive&&J.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(at(this.sourceBuffer.buffered,e.segment.time.from,100)&&at(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",_d(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&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,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=is(()=>(0,tT.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,P.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,jn(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&bt(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:P.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}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||!Z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,P.isNullable)(e))return!1;let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push({...o.time});let u=_d(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let p of c)(0,Mu.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(u)&&Math.round(p.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=Yy(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!Z(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||!Z(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)}}getBufferedTo(){return!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,P.isNullable)(e)?0:Re(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer))return;if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));let i={representation:e,from:t.time.from,to:t.time.to};for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=this.sourceBuffer.buffered.start(r)*1e3,n=this.sourceBuffer.buffered.end(r)*1e3;if(!(n<=t.time.from||a>=t.time.to)){if(a<=t.time.from&&n>=t.time.to){i=void 0;break}n>t.time.from&&n<t.time.to&&(i.from=n),a<t.time.to&&a>t.time.from&&(i.to=a)}}i&&i.to-i.from>1&&!this.gaps.some(r=>i&&r.from===i.from&&r.to===i.to)&&this.gaps.push(i)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=is(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:P.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,P.isNullable)(this.sourceBuffer)||!Z(this.mediaSource,this.sourceBuffer)||(0,P.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:P.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var re=require("@vkontakte/videoplayer-shared/es2018");var Du=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new re.ValueSubject(void 0);this.lastConnectionReused$=new re.ValueSubject(void 0);this.lastRequestFirstBytes$=new re.ValueSubject(void 0);this.recoverableError$=new re.Subject;this.error$=new re.Subject;this.abortAllController=new be;this.subscription=new re.SubscriptionRemovable;this.fetchManifest=(0,re.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Zi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=mu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Bu);return r?(t.log("success",(0,re.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,re.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,re.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var N,_,ne;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let K=new URL(l,location.href);K.searchParams.append("bytes",`${i.from}-${i.to}`),l=K.toString();break}default:(0,re.assertNever)(t)}this.requestQuic&&(l=Zi(l));let p=this.abortAllController.signal,h;if(n){let K=new be;if(h=(0,re.merge)((0,re.fromEvent)(this.abortAllController.signal,"abort"),(0,re.fromEvent)(n,"abort")).subscribe(()=>{try{K.abort()}catch(M){Bu(M)}}),this.abortAllController.signal.aborted||n.aborted)try{K.abort()}catch(M){Bu(M)}p=K.signal}let f=(0,re.now)();c.log("startRequest",(0,re.flattenObject)({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let b=yield this.doFetch(l,{priority:a,headers:d,signal:p}),S=(0,re.now)();if(!b)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(h),null;if((N=this.throughputEstimator)==null||N.addRawRtt(S-f),!b.ok||!b.body){this.unsubscribeAbortSubscription(h);let K=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:K}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let K=(0,re.now)(),M={requestStartedAt:f,requestEndedAt:K,duration:K-f};return c.log("endRequest",(0,re.flattenObject)(M)),c.end(),b.arrayBuffer()}let v=b.body;if(o){let K;[v,K]=b.body.tee(),(_=this.throughputEstimator)==null||_.trackStream(K,u)}let y=v.getReader(),x,A=parseInt((ne=b.headers.get("content-length"))!=null?ne:"",10);Number.isFinite(A)&&(x=A),!x&&i&&(x=i.to-i.from+1);let w=0,L=x?new Uint8Array(x):new Uint8Array(0),q=!1,F=K=>{this.unsubscribeAbortSubscription(h),q=!0,Bu(K)},O=(0,re.abortable)(p,async function*({done:K,value:M}){if(w===0&&this.lastRequestFirstBytes$.next((0,re.now)()-f),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!K&&M){if(x)L.set(M,w),w+=M.byteLength;else{let z=new Uint8Array(L.length+M.length);z.set(L),z.set(M,L.length),L=z,w+=M.byteLength}r==null||r(new DataView(L.buffer),w),yield y==null?void 0:y.read().then(O,F)}}.bind(this));yield y==null?void 0:y.read().then(O,F),this.unsubscribeAbortSubscription(h);let B=(0,re.now)(),H={failed:q,requestStartedAt:f,requestEndedAt:B,duration:B-f};return q?(c.error("endRequest",(0,re.flattenObject)(H)),c.end(),null):(c.log("endRequest",(0,re.flattenObject)(H)),c.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,re.abortable)(this.abortAllController.signal,async function*(e,t,i){var v;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,r-n,a-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,f.from-n,f.to-f.from+1);else{let y=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,re.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=fu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,re.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Nt(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:re.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:re.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:re.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:re.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:re.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Bu=s=>{if(!Hn(s))throw s};var Cu=require("@vkontakte/videoplayer-shared/es2018");var Qn=class s{constructor(e,t){this.currentRepresentation$=new Cu.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,Cu.isNullable)(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&bt(t.segmentReference))}};var T$=["timeupdate","progress","play","seeked","stalled","waiting"],I$=["timeupdate","progress","loadeddata","playing","seeked"];var Vu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new I.Subscription;this.representationSubscription=new I.Subscription;this.state$=new te("none");this.currentVideoRepresentation$=new I.ValueSubject(void 0);this.currentVideoRepresentationInit$=new I.ValueSubject(void 0);this.currentAudioRepresentation$=new I.ValueSubject(void 0);this.currentVideoSegmentLength$=new I.ValueSubject(0);this.currentAudioSegmentLength$=new I.ValueSubject(0);this.error$=new I.Subject;this.lastConnectionType$=new I.ValueSubject(void 0);this.lastConnectionReused$=new I.ValueSubject(void 0);this.lastRequestFirstBytes$=new I.ValueSubject(void 0);this.currentLiveTextRepresentation$=new I.ValueSubject(null);this.isLive$=new I.ValueSubject(!1);this.isActiveLive$=new I.ValueSubject(!1);this.isLowLatency$=new I.ValueSubject(!1);this.liveDuration$=new I.ValueSubject(0);this.liveSeekableDuration$=new I.ValueSubject(0);this.liveAvailabilityStartTime$=new I.ValueSubject(0);this.liveStreamStatus$=new I.ValueSubject(void 0);this.bufferLength$=new I.ValueSubject(0);this.liveLatency$=new I.ValueSubject(void 0);this.liveLoadBufferLength$=new I.ValueSubject(0);this.livePositionFromPlayer$=new I.ValueSubject(0);this.currentStallDuration$=new I.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new I.ValueSubject(0);this.fetcherRecoverableError$=new I.Subject;this.fetcherError$=new I.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new I.Subject;this.gapWatchdogActive=!1;this.destroyController=new be;this.initManifest=(0,I.abortable)(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=De(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:I.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,I.abortable)(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=eT(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=ou(e))!=null?n:{id:"ManifestParsing",category:I.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,p,h,f;return!!((p=(c=this.element)==null?void 0:c.canPlayType)!=null&&p.call(c,l)&&((f=(h=Dt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,p=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";c||(h=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:h,codecs:f})=>i(u,h,f)),c=new Set(d.map(({codecs:h})=>h)),p=Eu(c);if(p&&(r[u]=d.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=r.video.some(S=>S.hdr),b=r.video.some(S=>!S.hdr);J.display.isHDR&&h&&f?r.video=r.video.filter(S=>S.hdr):b&&(r.video=r.video.filter(S=>!S.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",(0,I.flattenObject)(a)),a}.bind(this));this.initRepresentations=(0,I.abortable)(this.destroyController.signal,async function*(e,t,i){var p;this.tracer.log("initRepresentationsStart",(0,I.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,I.assertNonNullable)(this.manifest),(0,I.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new I.Subscription,this.state$.startTransitionTo("representations_ready");let r=h=>{this.representationSubscription.add((0,I.fromEvent)(h,"error").pipe((0,I.filter)(f=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?zo():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Yr())if(i){let h=document.createElement("source");r(h),h.type="application/x-mpegurl",h.src=i.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.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((h,f)=>[...h,...f.representations],[]);if(this.videoBufferManager=new zn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,I.isNonNullable)(t)){let h=this.manifest.streams.audio.reduce((f,b)=>[...f,...b.representations],[]);this.audioBufferManager=new zn("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}Qn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Qn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,I.merge)(...I$.map(h=>(0,I.fromEvent)(this.element,h))).pipe((0,I.map)(h=>this.element?Re(this.element.buffered,this.element.currentTime*1e3):0),(0,I.filterChanged)(),(0,I.tap)(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,I.merge)((0,I.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,I.filterChanged)()).subscribe(f=>this.liveStreamEndTimestamp=(0,I.now)())),this.subscription.add((0,I.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,I.interval)(1e3).subscribe(f=>{let b=Qi(this.manifestUrlString,2);this.manifestUrlString=De(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,I.fromEvent)(this.element,"play").subscribe(f=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add((0,I.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,I.map)(({isActiveLive:f,isLowLatency:b})=>f&&b),(0,I.filterChanged)()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||us(this.element,1)})),this.representationSubscription.add((0,I.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,I.filter)(({bufferLength:f,isActiveLive:b,isLowLatency:S})=>b&&S&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let b=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add((0,I.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,I.filter)(({isLive:f})=>f),(0,I.filterChanged)((f,b)=>b.bufferLength<f.bufferLength),(0,I.map)(({rtt:f,bufferLength:b,segmentServerLatency:S})=>{let v=Qi(this.manifestUrlString,2);return(f/2+b+S+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,I.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:b,isLowLatency:S})=>{if(!S||!b)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,A=f-v;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(A)>y&&(w=1+Math.sign(A)*x),us(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var S,v;let b=0;if(f){let y=((v=(S=this.element)==null?void 0:S.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(A=>{var w,L;return(L=(w=A.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?L:y}))-y}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let h=0;this.representationSubscription.add((0,I.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,I.throttle)(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:b})=>{if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,v=Qi(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),A=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,w=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,L=isFinite(f)?f:b,q=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),F=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(F);let O="none";if(q?O="active_low_latency":this.isLowLatency$.getValue()&&F?(this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),O="active_low_latency"):v!==0&&L<x?O="live_forward_buffering":L<x+w&&(O="live_with_target_offset"),isFinite(f)&&(h=f>h?f:h),O==="live_forward_buffering"||O==="live_with_target_offset"){let B=h-(x+A),H=this.normolizeLiveOffset(Math.trunc(v+B/S)),N=Math.abs(H-v),_=0;!f||N<=this.tuning.dashCmafLive.offsetCalculationError?_=v:H>0&&N>this.tuning.dashCmafLive.offsetCalculationError&&(_=H),this.manifestUrlString=De(this.manifestUrlString,_,2)}(O==="live_with_target_offset"||O==="live_forward_buffering")&&(h=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:I.ErrorCategory.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=(0,I.merge)(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe((0,I.map)(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=(0,I.merge)(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe((0,I.map)(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue()))),c=(0,I.combine)({allBuffersFull:l,someBufferEnded:d}).pipe((0,I.filterChanged)(),(0,I.map)(({allBuffersFull:h,someBufferEnded:f})=>h&&f),(0,I.filter)(h=>h));if(this.representationSubscription.add((0,I.merge)(this.forceEnded$,c).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(h=this.source)==null||h.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add((0,I.merge)(...this.bufferManagers.map(h=>h.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let h=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise((f,b)=>{var S;h&&(this.timeoutSourceOpenId=setTimeout(()=>{var v;if(((v=this.source)==null?void 0:v.readyState)==="open"){f();return}this.tuning.dash.rejectOnSourceOpenTimeout?b(new Error("Timeout reject when wait sourceopen event")):f()},this.tuning.dash.sourceOpenTimeout)),(S=this.source)==null||S.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let h=[(p=this.manifest.duration)!=null?p:0,...(0,jd.default)((0,jd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let b=[];return f.duration&&b.push(f.duration),bt(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&b.push(f.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...h)/1e3}this.audioBufferManager&&(0,I.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,I.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:I.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Du({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.liveBuffer=Vi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;(0,I.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,I.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=De(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){(0,I.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,I.merge)(...T$.map(e=>(0,I.fromEvent)(this.element,e)),(0,I.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:I.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,I.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,I.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&at(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,b,S,v,y,x,A,w,L,q;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=(0,I.now)(),n=100,o=(b=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?v:0,l=(x=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?x:0,d=(w=(A=this.audioBufferManager)==null?void 0:A.getForwardBufferDuration())!=null?w:0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||p)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let F=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(F).catch(O=>{this.error$.next({id:"stallIntervalCallback",category:I.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:O})}),r.liveLastOffset=F}else{let F=this.element.currentTime*1e3;(L=this.videoBufferManager)==null||L.maintain(F),(q=this.audioBufferManager)==null||q.maintain(F),r.position=F}this.tracer.log("stallIntervalCallback",(0,I.flattenObject)(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,I.interval)(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:I.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;(0,I.assertNonNullable)(this.element),(0,I.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),at(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!((0,I.isNullable)(this.element)||(0,I.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,I.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,I.isNonNullable)(this.element)&&(0,I.isNonNullable)(this.source)&&(0,I.isNonNullable)(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,I.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue();this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,r=null,a=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-a<=i&&o.to+a>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r=1/0:(r===null||o.to>r)&&(r=o.to));if(r!==null){let n=r+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,this.tracer.log("jumpGap",(0,I.flattenObject)({isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime,jumpTo:n,resultCurrentTime:this.element.currentTime})))}}};var Tt=require("@vkontakte/videoplayer-shared/es2018"),Ou=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 a=r.target;this.pipSize$.next({width:a.width,height:a.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:a,pipSize:n})=>a?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 kr=class{constructor(e){this.subscription=new ue.Subscription;this.videoState=new te("stopped");this.droppedFramesManager=new Zr;this.stallsManager=new Ru;this.elementSizeManager=new Ou;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ki;this.audioTrackSwitchHistory=new Ki;this.selectedRepresentations={audio:null,video:null};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==null?void 0: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.hostname$.next(void 0),this.videoState.setState("stopped"),V(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"),V(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&V(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==null?void 0:i.to)==="playing"&&V(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&V(this.params.desiredState.playbackState,"paused");return;default:return(0,ue.assertNever)(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new ls(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.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 St(e.source.url),this.params=e,this.video=et(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(qe(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 Vu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=rt(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:ue.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,ue.filter)(l=>!!l.length),(0,ue.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,ue.map)(l=>l.to.state!=="none"),(0,ue.filterChanged)());this.stallsManager.connect({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$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,ue.filter)(ue.isNonNullable),(0,ue.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,ue.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ft(this.video,t.isLooped,r)),this.subscription.add(it(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(gt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(vt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),V(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),V(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,ue.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of d.audio){p.push(Vd(h));let f=[];for(let b of h.representations){let S=zy(b);f.push(S),this.audioTracksMap.set(S,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let c=[];for(let p of d.video){c.push(Od(p));let h=[];for(let f of p.representations){let b=Gy({...f,streamId:p.id});b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(c);for(let p of d.text)for(let h of p.representations){let f=Qy(p,h);this.textTracksMap.set(f,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&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)),this.subscription.add((0,ue.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,ue.fromEvent)(this.video,"progress")).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:c,audio:p}=this.selectedRepresentations;if(!c)return;let h=Pr(this.videoTracksMap.keys(),b=>{var S;return((S=this.videoTracksMap.get(b))==null?void 0:S.representation.id)===c.id});(0,ue.isNonNullable)(h)&&(this.stallsManager.lastVideoTrackSelected=h);let f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")await this.player.initRepresentations(c.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",c.id),p){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,b)}},r)),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,ue.filterChanged)()).subscribe(l=>{let d=Pr(this.videoTracksMap.entries(),([,{representation:f}])=>f.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:p}]=d,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(Od(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,ue.filterChanged)()).subscribe(l=>{let d=Pr(this.audioTracksMap.entries(),([,{representation:f}])=>f.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:p}]=d,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Vd(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.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(),(c=this.params.tuning.spherical)!=null&&c.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 o=t.playbackState.stateChangeStarted$.pipe((0,ue.map)(({to:l})=>l==="ready"),(0,ue.filterChanged)());this.subscription.add((0,ue.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,ue.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add((0,ue.merge)(o,this.player.state$.stateChangeEnded$,(0,ue.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,ue.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,ue.observableFrom)(["init"])).pipe((0,ue.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var F,O,B,H,N,_,ne,K,M,z,D,R;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Pa:Aa,t=this.params.tuning.useNewAutoSelectVideoTrack?iu:tu,i=this.params.tuning.useNewAutoSelectVideoTrack?ci:eu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(F=r.videoTrack.getState())==null?void 0:F.id,u=Pr(this.videoTracksMap.keys(),C=>C.id===o),l=a.currentVideoTrack$.getValue(),d=((H=(B=r.videoStream.getState())!=null?B:u&&((O=this.videoTracksMap.get(u))==null?void 0:O.stream))!=null?H:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=Pr(this.videoStreamsMap.keys(),C=>C.id===d.id),p=c&&this.videoStreamsMap.get(c);if(!p)return;let h=Re(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 b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,b||1/0),1),v=(N=r.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(v==null?void 0:v.id)&&Pr(this.audioStreamsMap.keys(),C=>C.id===v.id)||this.audioStreamsMap.keys().next().value,x=0;if(y){if(u&&!n){let C=e(u,p,(_=this.audioStreamsMap.get(y))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(ne=C==null?void 0:C.bitrate)!=null?ne:-1/0)}if(l){let C=e(l,p,(K=this.audioStreamsMap.get(y))!=null?K:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(M=C==null?void 0:C.bitrate)!=null?M:-1/0)}}let A=u;(n||!A)&&(A=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:x,forwardBufferHealth:S,current:l,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 w=y&&t(A,p,(z=this.audioStreamsMap.get(y))!=null?z:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),L=(D=this.videoTracksMap.get(A))==null?void 0:D.representation,q=w&&((R=this.audioTracksMap.get(w))==null?void 0:R.representation);L&&q?(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=q):L&&!q&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){st(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),V(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}))}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),tt(this.video),this.tracer.end()}};var Wn=class extends kr{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 ve=require("@vkontakte/videoplayer-shared/es2018");var Yn=class extends kr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new ve.ValueSubject(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe((0,ve.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,ve.combine)({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ve.map)(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,ve.filter)(o=>(0,ve.isNonNullable)(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add((0,ve.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,ve.merge)(i.playbackRateState$,new ve.ValueSubject(1))}).pipe((0,ve.filter)(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||(0,ve.isNullable)(l)||(e=o-l)})).add((0,ve.combine)({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,ve.merge)(i.playbackRateState$,new ve.ValueSubject(1))}).pipe((0,ve.filterChanged)((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||(0,ve.isNullable)(o)||(0,ve.isNullable)(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Wy(o);this.params.output.availableTextTracks$.next([u])}}))}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 rT=Y(xa(),1);var ce=require("@vkontakte/videoplayer-shared/es2018"),ii={};var ps=(s,e)=>new ce.Observable(t=>{let i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)}),Kn=class{constructor(e){this.subscription=new ce.Subscription;this.videoState=new te("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,ce.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,ce.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,ce.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),V(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,ce.assertNever)(e)}break;default:(0,ce.assertNever)(t)}};this.textTracksManager=new St(e.source.url),this.video=et(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(qe(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),tt(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:ce.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,rT.default)(import("hls.js").then(r=>{e||(ii.Hls=r.default,ii.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){(0,ce.assertNonNullable)(ii.Hls,"hls.js not loaded"),this.hls=new ii.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,ce.assertNonNullable)(ii.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:ce.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=rt(this.video);this.subscription.add(()=>r.destroy());let a=(l,d)=>this.subscription.add(l.subscribe(d,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.loadedMetadata$,t.loadedMetadataEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Ft(this.video,e.isLooped,i)),this.subscription.add(it(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(gt(this.video,e.playbackRate,r.playbackRateState$,i)),a(vt(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe((0,ce.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ps(this.hls,ii.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:ce.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)==null?void 0:d.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),V(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),V(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(ps(this.hls,ii.Events.MANIFEST_PARSED).pipe((0,ce.map)(({levels:l})=>l.reduce((d,c)=>{var y,x;let p=c.name||c.height.toString(10),{width:h,height:f}=c,b=(x=li((y=c.attrs.QUALITY)!=null?y:""))!=null?x:(0,ce.videoSizeToQuality)({width:h,height:f});if(!b)return d;let S=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:h,height:f},fps:S};return this.trackLevels.set(p,{track:v,level:c}),d.push(v),d},[]))),t.availableVideoTracks$),a(ps(this.hls,ii.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let p=c.name,h=c.attrs.URI||"",f=c.lang;d.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),a(ps(this.hls,ii.Events.LEVEL_LOADING).pipe((0,ce.map)(({url:l})=>qe(l))),t.hostname$),a(ps(this.hls,ii.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=d==null?void 0:d.endPTS)!=null?p:0)-((h=d==null?void 0:d.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=c==null?void 0:c.endPTS)!=null?f:0)-((b=c==null?void 0:c.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Yi(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:c})=>c===l))==null?void 0:d.track},o=ps(this.hls,ii.Events.LEVEL_SWITCHED).pipe((0,ce.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,ce.filter)(ce.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Yi(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if((0,ce.isNullable)(l))return;let d=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,ce.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,ce.observableFrom)(["init"])).pipe((0,ce.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await st(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ce.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),V(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),V(this.params.desiredState.playbackState,"stopped",!0)}};var sT="X-Playback-Duration",Hd=async s=>{var r;let e=await Nt(s),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(sT)?parseInt(e.headers.get(sT),10):void 0};var le=require("@vkontakte/videoplayer-shared/es2018");var zd=Y(ec(),1);var _u=require("@vkontakte/videoplayer-shared/es2018");var E$=s=>{let e=null;if(s.QUALITY&&(e=li(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,_u.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},w$=(s,e)=>{var a,n;let t=s.split(`
186
+ `),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,zd.default)(l[1].split(",").map(y=>y.split("="))),p=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,h=E$(c),f;c.BANDWIDTH&&(f=parseInt(c.BANDWIDTH,10)/1e3||void 0),!f&&c["AVERAGE-BANDWIDTH"]&&(f=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,S;if(c.RESOLUTION){let[y,x]=c.RESOLUTION.split("x").map(A=>parseInt(A,10));y&&x&&(S={width:y,height:x})}let v=new URL(t[++o],e).toString();h&&i.push({id:p,quality:h,url:v,bandwidth:f,size:S,fps:b})}if(d){let c=(0,zd.default)(d[1].split(",").map(b=>{let S=b.indexOf("=");return[b.substring(0,S),b.substring(S+1)]}).map(([b,S])=>[b,S.replace(/^"|"$/g,"")])),p=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=c.LANGUAGE,f=c.NAME;p&&h&&r.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},A$=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),Gd=0,aT=async(s,e=s,t,i)=>{let a=await(await Nt(s,i)).text();Gd+=1;try{let{qualityManifests:n,textTracks:o}=w$(a,e);return{qualityManifests:n,textTracks:o}}catch(n){if(Gd<=t.manifestRetryMaxCount)return await A$((0,_u.getExponentialDelay)(Gd-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),aT(s,e,t)}return{qualityManifests:[],textTracks:[]}},Fu=aT;var Vt=require("@vkontakte/videoplayer-shared/es2018");var Nu=class{constructor(e,t,i,r,a){this.subscription=new Vt.Subscription;this.abortControllers={destroy:new be,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Vt.ValueSubject(null);this.getCurrentTime$=new Vt.ValueSubject(null);this.error$=new Vt.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe((0,Vt.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 Nt(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(`
187
+ `),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+d},url:l}),a=a+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,Vt.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 be;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(){var t;let e=(t=this.prepareUrl)!=null?t: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:Vt.ErrorCategory.WTF,thrown:t,message:e})}};var Xn=class{constructor(e){this.subscription=new le.Subscription;this.videoState=new te("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new le.ValueSubject([]);this.liveOffset=new vr;this.manifestStartTime$=new le.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(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),V(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?V(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),V(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&V(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(V(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,le.assertNever)(t)}};var i;this.params=e,this.video=et(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:le.VideoQuality.INVARIANT,url:this.params.source.url};let t=(r,a)=>Fu(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Nu(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new St(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:le.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:le.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(qe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new le.ValueSubject((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:le.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=rt(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(it(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(gt(this.video,t.playbackRate,r.playbackRateState$,i)),a(vt(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(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"),V(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),V(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,le.filterChanged)(),(0,le.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,le.isNonNullable)(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(qe(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,le.combine)({startTime:this.manifestStartTime$.pipe((0,le.filter)(le.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,le.map)(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,le.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,le.observableFrom)(["init"])).pipe((0,le.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),tt(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if((0,le.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[p,h]of[[d,"mq"],[c,"lq"]]){let f=String(parseFloat(p||""));h&&p&&r.searchParams.set(h,f)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=De(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Hd(n).then(d=>{var c;if(!(0,le.isNullable)(d))this.maxSeekBackTime$.next(d);else{let p=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();((0,le.isNullable)(p)||!isFinite(p))&&Nt(n).then(h=>h.text()).then(h=>{var b;let f=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(f){let S=new URL(f,n).toString();Hd(S).then(v=>{(0,le.isNullable)(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){st(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),V(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:le.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=De(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 me=require("@vkontakte/videoplayer-shared/es2018");var Jn=class{constructor(e){this.subscription=new me.Subscription;this.videoState=new te("stopped");this.manifests$=new me.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),V(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?V(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),V(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&V(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&V(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,me.assertNever)(t)}};this.textTracksManager=new St(e.source.url),this.params=e,this.video=et(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:me.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(qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Fu(De(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:me.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:me.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=rt(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,me.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ft(this.video,t.isLooped,i)),this.subscription.add(it(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(gt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),V(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),V(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,me.isNonNullable)(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(S=>S.id===f);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(qe(b.url)))}let c=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(c!==p){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe((0,me.map)(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!J.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,me.merge)((0,me.fromEvent)(o,"addtrack"),(0,me.fromEvent)(o,"removetrack"),(0,me.fromEvent)(o,"change"),(0,me.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,me.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,me.observableFrom)(["init"])).pipe((0,me.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),tt(this.video)}prepare(){var a,n;let e=this.selectManifest();if((0,me.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){st(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),V(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:me.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var nT=Y(pr(),1),Qd=Y(Sr(),1),oT=Y(Zt(),1);var Ie=require("@vkontakte/videoplayer-shared/es2018");var Zn=class{constructor(e){this.subscription=new Ie.Subscription;this.videoState=new te("stopped");this.trackUrls={};this.textTracksManager=new St;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.hostname$.next(void 0),this.videoState.setState("stopped"),V(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.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==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?V(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),V(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&V(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&V(this.params.desiredState.playbackState,"paused");return;default:return(0,Ie.assertNever)(e)}};this.params=e,this.video=et(e.container,e.tuning),this.params.output.element$.next(this.video),(0,nT.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Qd.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:Ie.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=rt(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,Ie.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ft(this.video,t.isLooped,i)),this.subscription.add(it(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(gt(this.video,t.playbackRate,r.playbackRateState$,i)),a(vt(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),V(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),V(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,Ie.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=(0,Ie.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(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.trackUrls={},this.params.output.element$.next(void 0),tt(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,Ie.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,Ie.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Zi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(qe(t))}playIfAllowed(){st(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),V(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(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let p=ci(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(p)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,Qd.default)(this.trackUrls).map(c=>c.track);if(!r||!a||Kr(e,n[0].quality,(d=(0,oT.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?(0,Ie.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,Ie.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var Pe=require("@vkontakte/videoplayer-shared/es2018");var lT=require("@vkontakte/videoplayer-shared/es2018"),uT=["stun:videostun.mycdn.me:80"],P$=1e3,k$=3,Wd=()=>null,Uu=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=Wd;this.externalStopCallback=Wd;this.externalErrorCallback=Wd;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:uT}]};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:lT.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),P$)}normalizeOptions(e={}){let t={stunServerList:uT,maxRetryNumber:k$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var eo=class{constructor(e){this.videoState=new te("stopped");this.maxSeekBackTime$=new Pe.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),V(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),V(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&V(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&V(this.params.desiredState.playbackState,"paused");return;default:return(0,Pe.assertNever)(e)}};this.subscription=new Pe.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=et(e.container,e.tuning),this.liveStreamClient=new Uu(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),tt(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Pe.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,Pe.merge)(this.videoState.stateChangeStarted$.pipe((0,Pe.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Pe.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=rt(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(vt(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(it(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,Pe.assertNever)(n.to)}},i)).add((0,Pe.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Pe.observableFrom)(["init"])).pipe((0,Pe.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(qe(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:Pe.VideoQuality.INVARIANT}),this.video.srcObject=e,V(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Pe.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){st(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),V(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pe.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var to=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var E=require("@vkontakte/videoplayer-shared/es2018");var Ni=require("@vkontakte/videoplayer-shared/es2018"),cT=s=>new Ni.Observable(e=>{let t=new Ni.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe((0,Ni.map)(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe((0,Ni.map)(({type:l})=>l!==void 0)),n=new Ni.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Ut=require("@vkontakte/videoplayer-shared/es2018");function dT(){return new(window.AudioContext||window.webkitAudioContext)}var io=class io{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new be;this.subscriptions=new Ut.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Ut.filter)(a=>!!a.type),(0,Ut.once)()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){J.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Ut.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Ut.filter)(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),(0,Ut.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=dT();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 a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:io.errorId,category:Ut.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${io.errorId} exception`,thrown:e})}};io.errorId="VolumeMultiplierManager";var hs=io;var R$={chunkDuration:5e3,maxParallelRequests:5},ro=class{constructor(e){this.current$=new E.ValueSubject({type:void 0});this.providerError$=new E.Subject;this.noAvailableProvidersError$=new E.Subject;this.volumeMultiplierError$=new E.Subject;this.providerOutput={position$:new E.ValueSubject(0),duration$:new E.ValueSubject(1/0),volume$:new E.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new E.ValueSubject([]),currentVideoStream$:new E.ValueSubject(void 0),availableVideoTracks$:new E.ValueSubject([]),currentVideoTrack$:new E.ValueSubject(void 0),availableAudioStreams$:new E.ValueSubject([]),currentAudioStream$:new E.ValueSubject(void 0),availableAudioTracks$:new E.ValueSubject([]),currentVideoSegmentLength$:new E.ValueSubject(0),currentAudioSegmentLength$:new E.ValueSubject(0),isAudioAvailable$:new E.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new E.ValueSubject(!1),autoVideoTrackLimits$:new E.ValueSubject(void 0),currentBuffer$:new E.ValueSubject(void 0),isBuffering$:new E.ValueSubject(!0),error$:new E.Subject,fetcherError$:new E.Subject,fetcherRecoverableError$:new E.Subject,warning$:new E.Subject,willSeekEvent$:new E.Subject,soundProhibitedEvent$:new E.Subject,seekedEvent$:new E.Subject,loopedEvent$:new E.Subject,endedEvent$:new E.Subject,firstBytesEvent$:new E.Subject,loadedMetadataEvent$:new E.Subject,firstFrameEvent$:new E.Subject,canplay$:new E.Subject,isLive$:new E.ValueSubject(void 0),isLiveEnded$:new E.ValueSubject(null),isLowLatency$:new E.ValueSubject(!1),canChangePlaybackSpeed$:new E.ValueSubject(!0),liveTime$:new E.ValueSubject(void 0),liveBufferTime$:new E.ValueSubject(void 0),liveLatency$:new E.ValueSubject(void 0),severeStallOccurred$:new E.Subject,availableTextTracks$:new E.ValueSubject([]),currentTextTrack$:new E.ValueSubject(void 0),hostname$:new E.ValueSubject(void 0),httpConnectionType$:new E.ValueSubject(void 0),httpConnectionReused$:new E.ValueSubject(void 0),inPiP$:new E.ValueSubject(!1),inFullscreen$:new E.ValueSubject(!1),element$:new E.ValueSubject(void 0),elementVisible$:new E.ValueSubject(!0),availableSources$:new E.ValueSubject(void 0),is3DVideo$:new E.ValueSubject(!1),playbackState$:new E.ValueSubject(""),getCurrentTime$:new E.ValueSubject(null)};this.subscription=new E.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=Py([...Ry(this.params.tuning),...ky(this.params.tuning)],this.params.tuning).filter(l=>(0,E.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Yd.default)(r,l)),...t.filter(l=>(0,Yd.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",(0,E.flattenObject)(a)),this.screenFormatsIterator=new to(a);let n=[...kd(!0),...kd(!1)];this.chromecastFormatsIterator=new to(n.filter(l=>(0,E.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&hs.isSupported()&&(this.volumeMultiplierManager=new hs(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,E.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:E.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),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 a=this.providerOutput.isBuffering$;a.getValue()||a.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,E.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,E.assertNonNullable)(u),this.params.tuning.useNewDashProvider?new Wn({...o,source:u,sourceHls:l}):new bn({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),this.params.tuning.useNewDashProvider?new Yn({...o,source:u}):new gn({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),J.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Jn({...o,source:u}):new Kn({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new Xn({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new Zn({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new $S({...o,source:u,config:{...R$,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new eo({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,E.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,E.assertNonNullable)(o),new Ea({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,E.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,E.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,E.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 a=new URL(r);return a.host=t,a.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,hT.default)((0,pT.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new E.Subscription,t=!1,i=0;return e.add((0,E.merge)(this.providerOutput.error$.pipe((0,E.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),cT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,E.map)(r=>({id:`ProviderHangup:${r}`,category:E.ErrorCategory.WTF,message:`A ${r} 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 r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,E.filter)(({to:a})=>a==="playing"),(0,E.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===E.ErrorCategory.NETWORK,u=r.category===E.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}this.tracer.error("providerError",(0,E.flattenObject)(n))})),e}};var ee=require("@vkontakte/videoplayer-shared/es2018");var L$=5e3,fT="one_video_throughput",mT="one_video_rtt",Ui=window.navigator.connection,bT=()=>{let s=Ui==null?void 0:Ui.downlink;if((0,ee.isNonNullable)(s)&&s!==10)return s*1e3},gT=()=>{let s=Ui==null?void 0:Ui.rtt;if((0,ee.isNonNullable)(s)&&s!==3e3)return s},ST=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Kd=class s{constructor(e){this.subscription=new ee.Subscription;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(fT)||(e.useBrowserEstimation?bT():void 0)||L$,i=(a=(r=s.load(mT))!=null?r:e.useBrowserEstimation?gT():void 0)!=null?a:0;if(this.throughput$=new ee.ValueSubject(t),this.rtt$=new ee.ValueSubject(i),this.rttAdjustedThroughput$=new ee.ValueSubject(ST(t,i,e.rttPenaltyRequestSize)),this.throughput=Vi.getSmoothedValue(t,-1,e),this.rtt=Vi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=bT();u&&this.throughput.next(u);let l=gT();(0,ee.isNonNullable)(l)&&this.rtt.next(l)};Ui&&"onchange"in Ui&&this.subscription.add((0,ee.fromEvent)(Ui,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{ee.safeStorage.set(fT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{ee.safeStorage.set(mT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,ee.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,ee.map)(({throughput:n,rtt:o})=>ST(n,o,e.rttPenaltyRequestSize)),(0,ee.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,ee.now)(),r=new ee.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,ee.fromEvent)(e,"progress").pipe((0,ee.once)()).subscribe(a=>{t=a.loaded,i=(0,ee.now)()}));break;case 1:case 0:r.add((0,ee.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,ee.now)()}));break}r.add((0,ee.fromEvent)(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=(0,ee.now)(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=(0,ee.now)(),n=0,o=(0,ee.now)(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(r,(0,ee.now)()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=(0,ee.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=(0,ee.now)()}else n+=c.byteLength;o=(0,ee.now)()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,ee.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,ee.now)()-o,this.concurrentDownloads.size),n=0,o=(0,ee.now)());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=ee.safeStorage.get(e);if((0,ee.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},vT=Kd;var Rr=require("@vkontakte/videoplayer-shared/es2018"),yT={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Rr.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Rr.VideoQuality.Q_720P,trafficSavingLimit:Rr.VideoQuality.Q_480P},stallsManager:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:0,maxTvtToBeCounted:3*60*60,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Rr.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1,vktvAbrThrottle:null},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},TT=s=>{var e;return{...(0,Rr.fillWithDefault)(s,yT),configName:[...(e=s.configName)!=null?e:[],...yT.configName]}};var m=require("@vkontakte/videoplayer-shared/es2018");var qi=require("@vkontakte/videoplayer-shared/es2018"),Xd=({seekState:s,position$:e})=>(0,qi.merge)(s.stateChangeEnded$.pipe((0,qi.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,qi.filter)(qi.isNonNullable)),e.pipe((0,qi.filter)(()=>s.getState().state==="none")));var IT=require("@vkontakte/videoplayer-shared/es2018"),xT=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return(0,IT.assertNonNullable)(e,`Wrong container or containerId {${s.container}}`),e};var qu=require("@vkontakte/videoplayer-shared/es2018"),ET=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,qu.filter)(r=>r.length>0),(0,qu.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var so=class{constructor(e={configName:[]},t=m.Tracer.createRootTracer(!1)){this.subscription=new m.Subscription;this.logger=new m.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new m.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new m.ValueSubject(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new te("stopped"),seekState:new te({state:"none"}),volume:new te({volume:1,muted:!1}),videoTrack:new te(void 0),videoStream:new te(void 0),audioStream:new te(void 0),autoVideoTrackSwitching:new te(!0),autoVideoTrackLimits:new te({}),isLooped:new te(!1),isLowLatency:new te(!1),playbackRate:new te(1),externalTextTracks:new te([]),internalTextTracks:new te([]),currentTextTrack:new te(void 0),textTrackCuesSettings:new te({}),cameraOrientation:new te({x:0,y:0})};this.info={playbackState$:new m.ValueSubject(void 0),position$:new m.ValueSubject(0),duration$:new m.ValueSubject(1/0),muted$:new m.ValueSubject(!1),volume$:new m.ValueSubject(1),availableVideoStreams$:new m.ValueSubject([]),currentVideoStream$:new m.ValueSubject(void 0),availableQualities$:new m.ValueSubject([]),availableQualitiesFps$:new m.ValueSubject({}),currentQuality$:new m.ValueSubject(void 0),isAutoQualityEnabled$:new m.ValueSubject(!0),autoQualityLimitingAvailable$:new m.ValueSubject(!1),autoQualityLimits$:new m.ValueSubject({}),predefinedQualityLimitType$:new m.ValueSubject("unknown"),availableAudioStreams$:new m.ValueSubject([]),currentAudioStream$:new m.ValueSubject(void 0),availableAudioTracks$:new m.ValueSubject([]),isAudioAvailable$:new m.ValueSubject(!0),currentPlaybackRate$:new m.ValueSubject(1),currentBuffer$:new m.ValueSubject({start:0,end:0}),isBuffering$:new m.ValueSubject(!0),isStalled$:new m.ValueSubject(!1),isEnded$:new m.ValueSubject(!1),isLooped$:new m.ValueSubject(!1),isLive$:new m.ValueSubject(void 0),isLiveEnded$:new m.ValueSubject(null),canChangePlaybackSpeed$:new m.ValueSubject(void 0),atLiveEdge$:new m.ValueSubject(void 0),atLiveDurationEdge$:new m.ValueSubject(void 0),liveTime$:new m.ValueSubject(void 0),liveBufferTime$:new m.ValueSubject(void 0),liveLatency$:new m.ValueSubject(void 0),currentFormat$:new m.ValueSubject(void 0),availableTextTracks$:new m.ValueSubject([]),currentTextTrack$:new m.ValueSubject(void 0),throughputEstimation$:new m.ValueSubject(void 0),rttEstimation$:new m.ValueSubject(void 0),videoBitrate$:new m.ValueSubject(void 0),hostname$:new m.ValueSubject(void 0),httpConnectionType$:new m.ValueSubject(void 0),httpConnectionReused$:new m.ValueSubject(void 0),surface$:new m.ValueSubject("none"),chromecastState$:new m.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new m.ValueSubject(void 0),intrinsicVideoSize$:new m.ValueSubject(void 0),availableSources$:new m.ValueSubject(void 0),is3DVideo$:new m.ValueSubject(!1),currentVideoSegmentLength$:new m.ValueSubject(0),currentAudioSegmentLength$:new m.ValueSubject(0)};this.events={inited$:new m.Subject,ready$:new m.Subject,started$:new m.Subject,playing$:new m.Subject,paused$:new m.Subject,stopped$:new m.Subject,willStart$:new m.Subject,willResume$:new m.Subject,willPause$:new m.Subject,willStop$:new m.Subject,willDestruct$:new m.Subject,watchCoverageRecord$:new m.Subject,watchCoverageLive$:new m.Subject,managedError$:new m.Subject,fatalError$:new m.Subject,fetcherRecoverableError$:new m.Subject,ended$:new m.Subject,looped$:new m.Subject,seeked$:new m.Subject,willSeek$:new m.Subject,autoplaySoundProhibited$:new m.Subject,firstBytes$:new m.Subject,loadedMetadata$:new m.Subject,firstFrame$:new m.Subject,canplay$:new m.Subject,log$:new m.Subject,fetcherError$:new m.Subject,severeStallOccured$:new m.Subject};this.experimental={element$:new m.ValueSubject(void 0),tuningConfigName$:new m.ValueSubject([]),enableDebugTelemetry$:new m.ValueSubject(!1),dumpTelemetry:bS,getCurrentTime$:new m.ValueSubject(null)};if(this.initLogs(),this.tuning=TT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ho({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new vT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new m.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let n=Reflect.get(i,r,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,wT.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:m.ErrorCategory.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var u,l,d;let{container:n,...o}=e;this.tracer.log("initVideo",(0,m.flattenObject)(o)),this.domContainer=xT(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new ro({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?J.isInited$.pipe((0,m.filter)(n=>!!n),(0,m.once)()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),(0,m.fromEvent)(document,"visibilitychange").pipe((0,m.once)()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),a=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||a;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{var n;let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,r=t.getTransition(),a=(n=r==null?void 0:r.to.volume)!=null?n:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:a,muted:i})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{(0,m.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,m.filter)(i=>i.length>0),(0,m.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",(0,m.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{var i;(0,m.assertNonNullable)(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",(0,m.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{var t;ET(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>e),(0,m.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,m.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,m.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Kc(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.filter)(({from:e})=>e==="stopped"),(0,m.once)()).subscribe(()=>{this.initedAt=(0,m.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,m.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:m.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,m.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,m.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,m.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,m.map)(n=>n.destination),(0,m.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,m.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,m.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,m.isInvariantQuality)(u)?1:(0,m.isInvariantQuality)(l)?-1:(0,m.isHigher)(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,m.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe((0,m.filter)(n=>(0,m.isNonNullable)(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,m.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,m.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe((0,m.tap)(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add((0,m.combine)({hasLiveOffsetByPaused:(0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(n=>n.to),(0,m.filterChanged)(),(0,m.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,m.combine)({atLiveEdge:(0,m.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Xd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,m.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,m.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,m.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,m.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.muted),(0,m.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.volume),(0,m.filterChanged)()).subscribe(this.info.volume$)).add(Xd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,m.merge)(e.providerOutput.endedEvent$.pipe((0,m.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,m.mapTo)(!1))).pipe((0,m.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,m.map)(n=>({id:n?`No${n}`:"NoProviders",category:m.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe((0,m.once)(),(0,m.map)(n=>n!=null?n:(0,m.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new m.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new m.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.filter)(({to:n})=>n==="playing"),(0,m.once)()).subscribe(()=>i.next(!1)));let r=0,a=(0,m.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,m.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,m.filterChanged)());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,m.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,m.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,m.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new m.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,m.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,m.filter)(i=>i.length>0),(0,m.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=ci(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,m.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,m.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,m.assertNonNullable)(this.providerContainer),(0,m.assertNonNullable)(e),mS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>fS(i)),this.providerContainer.current$.subscribe(({type:i})=>wa("provider",i)),e.duration$.subscribe(i=>wa("duration",i)),e.availableVideoTracks$.pipe((0,m.filter)(i=>!!i.length),(0,m.once)()).subscribe(i=>wa("tracks",i)),this.events.fatalError$.subscribe(new ht("fatalError")),this.events.managedError$.subscribe(new ht("managedError")),e.position$.subscribe(new ht("position")),e.currentVideoTrack$.pipe((0,m.map)(i=>i==null?void 0:i.quality)).subscribe(new ht("quality")),this.info.currentBuffer$.subscribe(new ht("buffer")),e.isBuffering$.subscribe(new ht("isBuffering"))].forEach(i=>this.subscription.add(i)),wa("codecs",J.video.supportedCodecs)}initTracerSubscription(){let e=(0,m.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,m.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,m.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,m.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,m.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,m.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,m.filter)(i=>i>0),(0,m.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,m.filter)(i=>i>0),(0,m.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,m.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,m.filter)(i=>i.end>0),(0,m.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,m.filterChanged)())}).pipe((0,m.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,m.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,m.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,m.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,m.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,m.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,m.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,m.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,m.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,m.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,m.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,m.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:m.ErrorCategory.DOM,message:String(r)})})};this.subscription.add((0,m.merge)((0,m.fromEvent)(document,"visibilitychange"),(0,m.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,m.flattenObject)({quality:t,availableTracks:(0,m.flattenObject)(e),track:(0,m.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ma()}};var hi=require("@vkontakte/videoplayer-shared/es2018"),M$=`@vkontakte/videoplayer-core@${Ku}`;