@vkontakte/videoplayer-core 2.0.135-dev.f94adb28.0 → 2.0.136-beta.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 (113) hide show
  1. package/es2015.cjs.js +46 -53
  2. package/es2015.esm.js +42 -49
  3. package/es2018.cjs.js +54 -61
  4. package/es2018.esm.js +54 -61
  5. package/es2024.cjs.js +53 -60
  6. package/es2024.esm.js +51 -58
  7. package/esnext.cjs.js +53 -60
  8. package/esnext.esm.js +51 -58
  9. package/evergreen.esm.js +39 -46
  10. package/package.json +2 -2
  11. package/types/providers/DashProvider/baseDashProvider.d.ts +2 -1
  12. package/types/providers/DashProvider/lib/LiveTextManager.d.ts +1 -1
  13. package/types/providers/DashProvider/lib/buffer.d.ts +2 -1
  14. package/types/providers/DashProvider/lib/fetcher.d.ts +2 -1
  15. package/types/providers/DashProvider/lib/player.d.ts +6 -1
  16. package/types/providers/DashProvider/lib/types.d.ts +2 -159
  17. package/types/providers/DashProvider/lib/utils.d.ts +1 -2
  18. package/types/providers/DashProviderNew/baseDashProvider.d.ts +2 -1
  19. package/types/providers/DashProviderNew/lib/LiveTextManager.d.ts +1 -1
  20. package/types/providers/DashProviderNew/lib/buffer.d.ts +2 -1
  21. package/types/providers/DashProviderNew/lib/fetcher.d.ts +2 -1
  22. package/types/providers/DashProviderNew/lib/player.d.ts +6 -1
  23. package/types/providers/DashProviderNew/lib/types.d.ts +2 -159
  24. package/types/providers/DashProviderNew/lib/utils.d.ts +1 -2
  25. package/types/providers/utils/error.d.ts +1 -0
  26. package/types/providers/{DashProvider/lib → utils}/parsers/index.d.ts +1 -1
  27. package/types/providers/{DashProviderNew/lib → utils}/parsers/mpd.d.ts +1 -1
  28. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/BoxModel.d.ts +4 -4
  29. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/BoxParser.d.ts +2 -2
  30. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/box.d.ts +8 -8
  31. package/types/providers/utils/parsers/mpeg/boxes/avc1.d.ts +8 -0
  32. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/equi.d.ts +2 -2
  33. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/ftyp.d.ts +2 -2
  34. package/types/providers/utils/parsers/mpeg/boxes/index.d.ts +26 -0
  35. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/mdat.d.ts +2 -2
  36. package/types/providers/utils/parsers/mpeg/boxes/mdia.d.ts +8 -0
  37. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/mfhd.d.ts +2 -2
  38. package/types/providers/utils/parsers/mpeg/boxes/minf.d.ts +8 -0
  39. package/types/providers/utils/parsers/mpeg/boxes/moof.d.ts +8 -0
  40. package/types/providers/utils/parsers/mpeg/boxes/moov.d.ts +8 -0
  41. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/mvhd.d.ts +2 -2
  42. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/prhd.d.ts +2 -2
  43. package/types/providers/utils/parsers/mpeg/boxes/proj.d.ts +8 -0
  44. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/sidx.d.ts +2 -2
  45. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/st3d.d.ts +2 -2
  46. package/types/providers/utils/parsers/mpeg/boxes/stbl.d.ts +8 -0
  47. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/stsd.d.ts +2 -2
  48. package/types/providers/utils/parsers/mpeg/boxes/sv3d.d.ts +8 -0
  49. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/tfdt.d.ts +2 -2
  50. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/tfhd.d.ts +2 -2
  51. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/tkhd.d.ts +2 -2
  52. package/types/providers/utils/parsers/mpeg/boxes/traf.d.ts +8 -0
  53. package/types/providers/utils/parsers/mpeg/boxes/trak.d.ts +8 -0
  54. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/trun.d.ts +2 -2
  55. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/unknown.d.ts +1 -1
  56. package/types/providers/utils/parsers/mpeg/boxes/uuid.d.ts +18 -0
  57. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/fullBox.d.ts +2 -2
  58. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/isobmff.d.ts +1 -1
  59. package/types/providers/utils/parsers/types.d.ts +159 -0
  60. package/types/providers/{DashProvider/lib → utils}/parsers/webm/webm.d.ts +1 -1
  61. package/types/utils/tuningConfig.d.ts +2 -4
  62. package/types/providers/DashProvider/lib/parsers/mpd.d.ts +0 -3
  63. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/avc1.d.ts +0 -8
  64. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/index.d.ts +0 -26
  65. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mdia.d.ts +0 -8
  66. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/minf.d.ts +0 -8
  67. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moof.d.ts +0 -8
  68. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moov.d.ts +0 -8
  69. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/proj.d.ts +0 -8
  70. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/stbl.d.ts +0 -8
  71. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/sv3d.d.ts +0 -8
  72. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/traf.d.ts +0 -8
  73. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/trak.d.ts +0 -8
  74. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/uuid.d.ts +0 -11
  75. package/types/providers/DashProviderNew/lib/parsers/ietf/index.d.ts +0 -13
  76. package/types/providers/DashProviderNew/lib/parsers/index.d.ts +0 -3
  77. package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxModel.d.ts +0 -20
  78. package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxParser.d.ts +0 -21
  79. package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxTypeEnum.d.ts +0 -30
  80. package/types/providers/DashProviderNew/lib/parsers/mpeg/box.d.ts +0 -74
  81. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/avc1.d.ts +0 -8
  82. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/equi.d.ts +0 -21
  83. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/ftyp.d.ts +0 -17
  84. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/index.d.ts +0 -26
  85. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mdat.d.ts +0 -15
  86. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mdia.d.ts +0 -8
  87. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mfhd.d.ts +0 -11
  88. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/minf.d.ts +0 -8
  89. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/moof.d.ts +0 -8
  90. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/moov.d.ts +0 -8
  91. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mvhd.d.ts +0 -35
  92. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/prhd.d.ts +0 -16
  93. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/proj.d.ts +0 -8
  94. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/sidx.d.ts +0 -48
  95. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/st3d.d.ts +0 -23
  96. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/stbl.d.ts +0 -8
  97. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/stsd.d.ts +0 -11
  98. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/sv3d.d.ts +0 -8
  99. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tfdt.d.ts +0 -17
  100. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tfhd.d.ts +0 -22
  101. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tkhd.d.ts +0 -42
  102. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/traf.d.ts +0 -8
  103. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/trak.d.ts +0 -8
  104. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/trun.d.ts +0 -31
  105. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/unknown.d.ts +0 -6
  106. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/uuid.d.ts +0 -11
  107. package/types/providers/DashProviderNew/lib/parsers/mpeg/fullBox.d.ts +0 -15
  108. package/types/providers/DashProviderNew/lib/parsers/mpeg/isobmff.d.ts +0 -12
  109. package/types/providers/DashProviderNew/lib/parsers/webm/ebml.d.ts +0 -76
  110. package/types/providers/DashProviderNew/lib/parsers/webm/webm.d.ts +0 -3
  111. /package/types/providers/{DashProvider/lib → utils}/parsers/ietf/index.d.ts +0 -0
  112. /package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/BoxTypeEnum.d.ts +0 -0
  113. /package/types/providers/{DashProvider/lib → utils}/parsers/webm/ebml.d.ts +0 -0
package/esnext.esm.js CHANGED
@@ -1,19 +1,19 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.135-dev.f94adb28.0
3
- * Tue, 01 Jul 2025 09:29:11 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-135/doc/
2
+ * @vkontakte/videoplayer-core v2.0.136-beta.0
3
+ * Fri, 11 Jul 2025 16:07:23 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-136/doc/
5
5
  */
6
- var xx=Object.create;var xp=Object.defineProperty;var Ex=Object.getOwnPropertyDescriptor;var wx=Object.getOwnPropertyNames;var Px=Object.getPrototypeOf,kx=Object.prototype.hasOwnProperty;var m=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var Ax=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of wx(e))!kx.call(s,r)&&r!==t&&xp(s,r,{get:()=>e[r],enumerable:!(i=Ex(e,r))||i.enumerable});return s};var C=(s,e,t)=>(t=s!=null?xx(Px(s)):{},Ax(e||!s||!s.__esModule?xp(t,"default",{value:s,enumerable:!0}):t,s));var ve=m((Ru,wp)=>{"use strict";var Yr=function(s){return s&&s.Math===Math&&s};wp.exports=Yr(typeof globalThis=="object"&&globalThis)||Yr(typeof window=="object"&&window)||Yr(typeof self=="object"&&self)||Yr(typeof global=="object"&&global)||Yr(typeof Ru=="object"&&Ru)||function(){return this}()||Function("return this")()});var Le=m((jV,Pp)=>{"use strict";Pp.exports=function(s){try{return!!s()}catch{return!0}}});var Kr=m((zV,kp)=>{"use strict";var Rx=Le();kp.exports=!Rx(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Mu=m((QV,Lp)=>{"use strict";var Mx=Kr(),Mp=Function.prototype,Ap=Mp.apply,Rp=Mp.call;Lp.exports=typeof Reflect=="object"&&Reflect.apply||(Mx?Rp.bind(Ap):function(){return Rp.apply(Ap,arguments)})});var ke=m((GV,Dp)=>{"use strict";var Bp=Kr(),$p=Function.prototype,Lu=$p.call,Lx=Bp&&$p.bind.bind(Lu,Lu);Dp.exports=Bp?Lx:function(s){return function(){return Lu.apply(s,arguments)}}});var Pi=m((WV,Vp)=>{"use strict";var Cp=ke(),Bx=Cp({}.toString),$x=Cp("".slice);Vp.exports=function(s){return $x(Bx(s),8,-1)}});var Bu=m((YV,Op)=>{"use strict";var Dx=Pi(),Cx=ke();Op.exports=function(s){if(Dx(s)==="Function")return Cx(s)}});var me=m((KV,_p)=>{"use strict";var $u=typeof document=="object"&&document.all;_p.exports=typeof $u>"u"&&$u!==void 0?function(s){return typeof s=="function"||s===$u}:function(s){return typeof s=="function"}});var ut=m((XV,Fp)=>{"use strict";var Vx=Le();Fp.exports=!Vx(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var lt=m((JV,Np)=>{"use strict";var Ox=Kr(),mn=Function.prototype.call;Np.exports=Ox?mn.bind(mn):function(){return mn.apply(mn,arguments)}});var Du=m(Hp=>{"use strict";var Up={}.propertyIsEnumerable,qp=Object.getOwnPropertyDescriptor,_x=qp&&!Up.call({1:2},1);Hp.f=_x?function(e){var t=qp(this,e);return!!t&&t.enumerable}:Up});var Xr=m((eO,jp)=>{"use strict";jp.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var Qp=m((tO,zp)=>{"use strict";var Fx=ke(),Nx=Le(),Ux=Pi(),Cu=Object,qx=Fx("".split);zp.exports=Nx(function(){return!Cu("z").propertyIsEnumerable(0)})?function(s){return Ux(s)==="String"?qx(s,""):Cu(s)}:Cu});var Zi=m((iO,Gp)=>{"use strict";Gp.exports=function(s){return s==null}});var ui=m((rO,Wp)=>{"use strict";var Hx=Zi(),jx=TypeError;Wp.exports=function(s){if(Hx(s))throw new jx("Can't call method on "+s);return s}});var ki=m((sO,Yp)=>{"use strict";var zx=Qp(),Qx=ui();Yp.exports=function(s){return zx(Qx(s))}});var ct=m((aO,Kp)=>{"use strict";var Gx=me();Kp.exports=function(s){return typeof s=="object"?s!==null:Gx(s)}});var er=m((nO,Xp)=>{"use strict";Xp.exports={}});var Yt=m((oO,Zp)=>{"use strict";var Vu=er(),Ou=ve(),Wx=me(),Jp=function(s){return Wx(s)?s:void 0};Zp.exports=function(s,e){return arguments.length<2?Jp(Vu[s])||Jp(Ou[s]):Vu[s]&&Vu[s][e]||Ou[s]&&Ou[s][e]}});var Jr=m((uO,eh)=>{"use strict";var Yx=ke();eh.exports=Yx({}.isPrototypeOf)});var Ai=m((lO,rh)=>{"use strict";var Kx=ve(),th=Kx.navigator,ih=th&&th.userAgent;rh.exports=ih?String(ih):""});var Fu=m((cO,lh)=>{"use strict";var uh=ve(),_u=Ai(),sh=uh.process,ah=uh.Deno,nh=sh&&sh.versions||ah&&ah.version,oh=nh&&nh.v8,xt,bn;oh&&(xt=oh.split("."),bn=xt[0]>0&&xt[0]<4?1:+(xt[0]+xt[1]));!bn&&_u&&(xt=_u.match(/Edge\/(\d+)/),(!xt||xt[1]>=74)&&(xt=_u.match(/Chrome\/(\d+)/),xt&&(bn=+xt[1])));lh.exports=bn});var Nu=m((dO,dh)=>{"use strict";var ch=Fu(),Xx=Le(),Jx=ve(),Zx=Jx.String;dh.exports=!!Object.getOwnPropertySymbols&&!Xx(function(){var s=Symbol("symbol detection");return!Zx(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&ch&&ch<41})});var Uu=m((pO,ph)=>{"use strict";var eE=Nu();ph.exports=eE&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var qu=m((hO,hh)=>{"use strict";var tE=Yt(),iE=me(),rE=Jr(),sE=Uu(),aE=Object;hh.exports=sE?function(s){return typeof s=="symbol"}:function(s){var e=tE("Symbol");return iE(e)&&rE(e.prototype,aE(s))}});var Zr=m((fO,fh)=>{"use strict";var nE=String;fh.exports=function(s){try{return nE(s)}catch{return"Object"}}});var Bt=m((mO,mh)=>{"use strict";var oE=me(),uE=Zr(),lE=TypeError;mh.exports=function(s){if(oE(s))return s;throw new lE(uE(s)+" is not a function")}});var es=m((bO,bh)=>{"use strict";var cE=Bt(),dE=Zi();bh.exports=function(s,e){var t=s[e];return dE(t)?void 0:cE(t)}});var Sh=m((gO,gh)=>{"use strict";var Hu=lt(),ju=me(),zu=ct(),pE=TypeError;gh.exports=function(s,e){var t,i;if(e==="string"&&ju(t=s.toString)&&!zu(i=Hu(t,s))||ju(t=s.valueOf)&&!zu(i=Hu(t,s))||e!=="string"&&ju(t=s.toString)&&!zu(i=Hu(t,s)))return i;throw new pE("Can't convert object to primitive value")}});var Et=m((SO,vh)=>{"use strict";vh.exports=!0});var Ih=m((vO,Th)=>{"use strict";var yh=ve(),hE=Object.defineProperty;Th.exports=function(s,e){try{hE(yh,s,{value:e,configurable:!0,writable:!0})}catch{yh[s]=e}return e}});var ts=m((yO,wh)=>{"use strict";var fE=Et(),mE=ve(),bE=Ih(),xh="__core-js_shared__",Eh=wh.exports=mE[xh]||bE(xh,{});(Eh.versions||(Eh.versions=[])).push({version:"3.38.0",mode:fE?"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 Qu=m((TO,kh)=>{"use strict";var Ph=ts();kh.exports=function(s,e){return Ph[s]||(Ph[s]=e||{})}});var tr=m((IO,Ah)=>{"use strict";var gE=ui(),SE=Object;Ah.exports=function(s){return SE(gE(s))}});var wt=m((xO,Rh)=>{"use strict";var vE=ke(),yE=tr(),TE=vE({}.hasOwnProperty);Rh.exports=Object.hasOwn||function(e,t){return TE(yE(e),t)}});var Gu=m((EO,Mh)=>{"use strict";var IE=ke(),xE=0,EE=Math.random(),wE=IE(1 .toString);Mh.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+wE(++xE+EE,36)}});var Be=m((wO,Bh)=>{"use strict";var PE=ve(),kE=Qu(),Lh=wt(),AE=Gu(),RE=Nu(),ME=Uu(),ir=PE.Symbol,Wu=kE("wks"),LE=ME?ir.for||ir:ir&&ir.withoutSetter||AE;Bh.exports=function(s){return Lh(Wu,s)||(Wu[s]=RE&&Lh(ir,s)?ir[s]:LE("Symbol."+s)),Wu[s]}});var Vh=m((PO,Ch)=>{"use strict";var BE=lt(),$h=ct(),Dh=qu(),$E=es(),DE=Sh(),CE=Be(),VE=TypeError,OE=CE("toPrimitive");Ch.exports=function(s,e){if(!$h(s)||Dh(s))return s;var t=$E(s,OE),i;if(t){if(e===void 0&&(e="default"),i=BE(t,s,e),!$h(i)||Dh(i))return i;throw new VE("Can't convert object to primitive value")}return e===void 0&&(e="number"),DE(s,e)}});var Yu=m((kO,Oh)=>{"use strict";var _E=Vh(),FE=qu();Oh.exports=function(s){var e=_E(s,"string");return FE(e)?e:e+""}});var gn=m((AO,Fh)=>{"use strict";var NE=ve(),_h=ct(),Ku=NE.document,UE=_h(Ku)&&_h(Ku.createElement);Fh.exports=function(s){return UE?Ku.createElement(s):{}}});var Xu=m((RO,Nh)=>{"use strict";var qE=ut(),HE=Le(),jE=gn();Nh.exports=!qE&&!HE(function(){return Object.defineProperty(jE("div"),"a",{get:function(){return 7}}).a!==7})});var Hh=m(qh=>{"use strict";var zE=ut(),QE=lt(),GE=Du(),WE=Xr(),YE=ki(),KE=Yu(),XE=wt(),JE=Xu(),Uh=Object.getOwnPropertyDescriptor;qh.f=zE?Uh:function(e,t){if(e=YE(e),t=KE(t),JE)try{return Uh(e,t)}catch{}if(XE(e,t))return WE(!QE(GE.f,e,t),e[t])}});var Ju=m((LO,jh)=>{"use strict";var ZE=Le(),ew=me(),tw=/#|\.prototype\./,is=function(s,e){var t=rw[iw(s)];return t===aw?!0:t===sw?!1:ew(e)?ZE(e):!!e},iw=is.normalize=function(s){return String(s).replace(tw,".").toLowerCase()},rw=is.data={},sw=is.NATIVE="N",aw=is.POLYFILL="P";jh.exports=is});var rr=m((BO,Qh)=>{"use strict";var zh=Bu(),nw=Bt(),ow=Kr(),uw=zh(zh.bind);Qh.exports=function(s,e){return nw(s),e===void 0?s:ow?uw(s,e):function(){return s.apply(e,arguments)}}});var Zu=m(($O,Gh)=>{"use strict";var lw=ut(),cw=Le();Gh.exports=lw&&cw(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var $t=m((DO,Wh)=>{"use strict";var dw=ct(),pw=String,hw=TypeError;Wh.exports=function(s){if(dw(s))return s;throw new hw(pw(s)+" is not an object")}});var Ri=m(Kh=>{"use strict";var fw=ut(),mw=Xu(),bw=Zu(),Sn=$t(),Yh=Yu(),gw=TypeError,el=Object.defineProperty,Sw=Object.getOwnPropertyDescriptor,tl="enumerable",il="configurable",rl="writable";Kh.f=fw?bw?function(e,t,i){if(Sn(e),t=Yh(t),Sn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&rl in i&&!i[rl]){var r=Sw(e,t);r&&r[rl]&&(e[t]=i.value,i={configurable:il in i?i[il]:r[il],enumerable:tl in i?i[tl]:r[tl],writable:!1})}return el(e,t,i)}:el:function(e,t,i){if(Sn(e),t=Yh(t),Sn(i),mw)try{return el(e,t,i)}catch{}if("get"in i||"set"in i)throw new gw("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var sr=m((VO,Xh)=>{"use strict";var vw=ut(),yw=Ri(),Tw=Xr();Xh.exports=vw?function(s,e,t){return yw.f(s,e,Tw(1,t))}:function(s,e,t){return s[e]=t,s}});var Ie=m((OO,Zh)=>{"use strict";var rs=ve(),Iw=Mu(),xw=Bu(),Ew=me(),ww=Hh().f,Pw=Ju(),ar=er(),kw=rr(),nr=sr(),Jh=wt();ts();var Aw=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 Iw(s,this,arguments)};return e.prototype=s.prototype,e};Zh.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?rs:r?rs[t]:rs[t]&&rs[t].prototype,o=i?ar:ar[t]||nr(ar,t,{})[t],u=o.prototype,l,d,c,p,h,f,b,g,S;for(p in e)l=Pw(i?p:t+(r?".":"#")+p,s.forced),d=!l&&n&&Jh(n,p),f=o[p],d&&(s.dontCallGetSet?(S=ww(n,p),b=S&&S.value):b=n[p]),h=d&&b?b:e[p],!(!l&&!a&&typeof f==typeof h)&&(s.bind&&d?g=kw(h,rs):s.wrap&&d?g=Aw(h):a&&Ew(h)?g=xw(h):g=h,(s.sham||h&&h.sham||f&&f.sham)&&nr(g,"sham",!0),nr(o,p,g),a&&(c=t+"Prototype",Jh(ar,c)||nr(ar,c,{}),nr(ar[c],p,h),s.real&&u&&(l||!u[p])&&nr(u,p,h)))}});var tf=m((_O,ef)=>{"use strict";var Rw=Math.ceil,Mw=Math.floor;ef.exports=Math.trunc||function(e){var t=+e;return(t>0?Mw:Rw)(t)}});var ss=m((FO,rf)=>{"use strict";var Lw=tf();rf.exports=function(s){var e=+s;return e!==e||e===0?0:Lw(e)}});var af=m((NO,sf)=>{"use strict";var Bw=ss(),$w=Math.max,Dw=Math.min;sf.exports=function(s,e){var t=Bw(s);return t<0?$w(t+e,0):Dw(t,e)}});var sl=m((UO,nf)=>{"use strict";var Cw=ss(),Vw=Math.min;nf.exports=function(s){var e=Cw(s);return e>0?Vw(e,9007199254740991):0}});var or=m((qO,of)=>{"use strict";var Ow=sl();of.exports=function(s){return Ow(s.length)}});var al=m((HO,lf)=>{"use strict";var _w=ki(),Fw=af(),Nw=or(),uf=function(s){return function(e,t,i){var r=_w(e),a=Nw(r);if(a===0)return!s&&-1;var n=Fw(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}};lf.exports={includes:uf(!0),indexOf:uf(!1)}});var as=m((jO,cf)=>{"use strict";cf.exports=function(){}});var df=m(()=>{"use strict";var Uw=Ie(),qw=al().includes,Hw=Le(),jw=as(),zw=Hw(function(){return!Array(1).includes()});Uw({target:"Array",proto:!0,forced:zw},{includes:function(e){return qw(this,e,arguments.length>1?arguments[1]:void 0)}});jw("includes")});var li=m((GO,pf)=>{"use strict";var Qw=Yt();pf.exports=Qw});var ff=m((WO,hf)=>{"use strict";df();var Gw=li();hf.exports=Gw("Array","includes")});var bf=m((YO,mf)=>{"use strict";var Ww=ff();mf.exports=Ww});var dt=m((KO,gf)=>{"use strict";var Yw=bf();gf.exports=Yw});var Tn=m((u_,wf)=>{"use strict";var rP=Qu(),sP=Gu(),Ef=rP("keys");wf.exports=function(s){return Ef[s]||(Ef[s]=sP(s))}});var kf=m((l_,Pf)=>{"use strict";var aP=Le();Pf.exports=!aP(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var In=m((c_,Rf)=>{"use strict";var nP=wt(),oP=me(),uP=tr(),lP=Tn(),cP=kf(),Af=lP("IE_PROTO"),ul=Object,dP=ul.prototype;Rf.exports=cP?ul.getPrototypeOf:function(s){var e=uP(s);if(nP(e,Af))return e[Af];var t=e.constructor;return oP(t)&&e instanceof t?t.prototype:e instanceof ul?dP:null}});var xn=m((d_,Mf)=>{"use strict";Mf.exports={}});var $f=m((p_,Bf)=>{"use strict";var pP=ke(),ll=wt(),hP=ki(),fP=al().indexOf,mP=xn(),Lf=pP([].push);Bf.exports=function(s,e){var t=hP(s),i=0,r=[],a;for(a in t)!ll(mP,a)&&ll(t,a)&&Lf(r,a);for(;e.length>i;)ll(t,a=e[i++])&&(~fP(r,a)||Lf(r,a));return r}});var cl=m((h_,Df)=>{"use strict";Df.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var dl=m((f_,Cf)=>{"use strict";var bP=$f(),gP=cl();Cf.exports=Object.keys||function(e){return bP(e,gP)}});var pl=m((m_,Nf)=>{"use strict";var Of=ut(),SP=Le(),_f=ke(),vP=In(),yP=dl(),TP=ki(),IP=Du().f,Ff=_f(IP),xP=_f([].push),EP=Of&&SP(function(){var s=Object.create(null);return s[2]=2,!Ff(s,2)}),Vf=function(s){return function(e){for(var t=TP(e),i=yP(t),r=EP&&vP(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!Of||(r?u in t:Ff(t,u)))&&xP(o,s?[u,t[u]]:t[u]);return o}};Nf.exports={entries:Vf(!0),values:Vf(!1)}});var Uf=m(()=>{"use strict";var wP=Ie(),PP=pl().entries;wP({target:"Object",stat:!0},{entries:function(e){return PP(e)}})});var Hf=m((S_,qf)=>{"use strict";Uf();var kP=er();qf.exports=kP.Object.entries});var zf=m((v_,jf)=>{"use strict";var AP=Hf();jf.exports=AP});var Mi=m((y_,Qf)=>{"use strict";var RP=zf();Qf.exports=RP});var Li=m((T_,Gf)=>{"use strict";Gf.exports={}});var Kf=m((I_,Yf)=>{"use strict";var MP=ve(),LP=me(),Wf=MP.WeakMap;Yf.exports=LP(Wf)&&/native code/.test(String(Wf))});var bl=m((x_,Zf)=>{"use strict";var BP=Kf(),Jf=ve(),$P=ct(),DP=sr(),hl=wt(),fl=ts(),CP=Tn(),VP=xn(),Xf="Object already initialized",ml=Jf.TypeError,OP=Jf.WeakMap,En,ns,wn,_P=function(s){return wn(s)?ns(s):En(s,{})},FP=function(s){return function(e){var t;if(!$P(e)||(t=ns(e)).type!==s)throw new ml("Incompatible receiver, "+s+" required");return t}};BP||fl.state?(Pt=fl.state||(fl.state=new OP),Pt.get=Pt.get,Pt.has=Pt.has,Pt.set=Pt.set,En=function(s,e){if(Pt.has(s))throw new ml(Xf);return e.facade=s,Pt.set(s,e),e},ns=function(s){return Pt.get(s)||{}},wn=function(s){return Pt.has(s)}):(Bi=CP("state"),VP[Bi]=!0,En=function(s,e){if(hl(s,Bi))throw new ml(Xf);return e.facade=s,DP(s,Bi,e),e},ns=function(s){return hl(s,Bi)?s[Bi]:{}},wn=function(s){return hl(s,Bi)});var Pt,Bi;Zf.exports={set:En,get:ns,has:wn,enforce:_P,getterFor:FP}});var vl=m((E_,tm)=>{"use strict";var gl=ut(),NP=wt(),em=Function.prototype,UP=gl&&Object.getOwnPropertyDescriptor,Sl=NP(em,"name"),qP=Sl&&function(){}.name==="something",HP=Sl&&(!gl||gl&&UP(em,"name").configurable);tm.exports={EXISTS:Sl,PROPER:qP,CONFIGURABLE:HP}});var rm=m(im=>{"use strict";var jP=ut(),zP=Zu(),QP=Ri(),GP=$t(),WP=ki(),YP=dl();im.f=jP&&!zP?Object.defineProperties:function(e,t){GP(e);for(var i=WP(t),r=YP(t),a=r.length,n=0,o;a>n;)QP.f(e,o=r[n++],i[o]);return e}});var yl=m((P_,sm)=>{"use strict";var KP=Yt();sm.exports=KP("document","documentElement")});var El=m((k_,dm)=>{"use strict";var XP=$t(),JP=rm(),am=cl(),ZP=xn(),ek=yl(),tk=gn(),ik=Tn(),nm=">",om="<",Il="prototype",xl="script",lm=ik("IE_PROTO"),Tl=function(){},cm=function(s){return om+xl+nm+s+om+"/"+xl+nm},um=function(s){s.write(cm("")),s.close();var e=s.parentWindow.Object;return s=null,e},rk=function(){var s=tk("iframe"),e="java"+xl+":",t;return s.style.display="none",ek.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(cm("document.F=Object")),t.close(),t.F},Pn,kn=function(){try{Pn=new ActiveXObject("htmlfile")}catch{}kn=typeof document<"u"?document.domain&&Pn?um(Pn):rk():um(Pn);for(var s=am.length;s--;)delete kn[Il][am[s]];return kn()};ZP[lm]=!0;dm.exports=Object.create||function(e,t){var i;return e!==null?(Tl[Il]=XP(e),i=new Tl,Tl[Il]=null,i[lm]=e):i=kn(),t===void 0?i:JP.f(i,t)}});var ur=m((A_,pm)=>{"use strict";var sk=sr();pm.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:sk(s,e,t),s}});var Al=m((R_,mm)=>{"use strict";var ak=Le(),nk=me(),ok=ct(),uk=El(),hm=In(),lk=ur(),ck=Be(),dk=Et(),kl=ck("iterator"),fm=!1,Kt,wl,Pl;[].keys&&(Pl=[].keys(),"next"in Pl?(wl=hm(hm(Pl)),wl!==Object.prototype&&(Kt=wl)):fm=!0);var pk=!ok(Kt)||ak(function(){var s={};return Kt[kl].call(s)!==s});pk?Kt={}:dk&&(Kt=uk(Kt));nk(Kt[kl])||lk(Kt,kl,function(){return this});mm.exports={IteratorPrototype:Kt,BUGGY_SAFARI_ITERATORS:fm}});var An=m((M_,gm)=>{"use strict";var hk=Be(),fk=hk("toStringTag"),bm={};bm[fk]="z";gm.exports=String(bm)==="[object z]"});var os=m((L_,Sm)=>{"use strict";var mk=An(),bk=me(),Rn=Pi(),gk=Be(),Sk=gk("toStringTag"),vk=Object,yk=Rn(function(){return arguments}())==="Arguments",Tk=function(s,e){try{return s[e]}catch{}};Sm.exports=mk?Rn:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Tk(e=vk(s),Sk))=="string"?t:yk?Rn(e):(i=Rn(e))==="Object"&&bk(e.callee)?"Arguments":i}});var ym=m((B_,vm)=>{"use strict";var Ik=An(),xk=os();vm.exports=Ik?{}.toString:function(){return"[object "+xk(this)+"]"}});var us=m(($_,Im)=>{"use strict";var Ek=An(),wk=Ri().f,Pk=sr(),kk=wt(),Ak=ym(),Rk=Be(),Tm=Rk("toStringTag");Im.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(kk(r,Tm)||wk(r,Tm,{configurable:!0,value:e}),i&&!Ek&&Pk(r,"toString",Ak))}});var Em=m((D_,xm)=>{"use strict";var Mk=Al().IteratorPrototype,Lk=El(),Bk=Xr(),$k=us(),Dk=Li(),Ck=function(){return this};xm.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Lk(Mk,{next:Bk(+!i,t)}),$k(s,r,!1,!0),Dk[r]=Ck,s}});var Pm=m((C_,wm)=>{"use strict";var Vk=ke(),Ok=Bt();wm.exports=function(s,e,t){try{return Vk(Ok(Object.getOwnPropertyDescriptor(s,e)[t]))}catch{}}});var Am=m((V_,km)=>{"use strict";var _k=ct();km.exports=function(s){return _k(s)||s===null}});var Mm=m((O_,Rm)=>{"use strict";var Fk=Am(),Nk=String,Uk=TypeError;Rm.exports=function(s){if(Fk(s))return s;throw new Uk("Can't set "+Nk(s)+" as a prototype")}});var Rl=m((__,Lm)=>{"use strict";var qk=Pm(),Hk=ct(),jk=ui(),zk=Mm();Lm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=qk(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch{}return function(r,a){return jk(r),zk(a),Hk(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var qm=m((F_,Um)=>{"use strict";var Qk=Ie(),Gk=lt(),Mn=Et(),Fm=vl(),Wk=me(),Yk=Em(),Bm=In(),$m=Rl(),Kk=us(),Xk=sr(),Ml=ur(),Jk=Be(),Dm=Li(),Nm=Al(),Zk=Fm.PROPER,eA=Fm.CONFIGURABLE,Cm=Nm.IteratorPrototype,Ln=Nm.BUGGY_SAFARI_ITERATORS,ls=Jk("iterator"),Vm="keys",cs="values",Om="entries",_m=function(){return this};Um.exports=function(s,e,t,i,r,a,n){Yk(t,e,i);var o=function(S){if(S===r&&p)return p;if(!Ln&&S&&S in d)return d[S];switch(S){case Vm:return function(){return new t(this,S)};case cs:return function(){return new t(this,S)};case Om:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[ls]||d["@@iterator"]||r&&d[r],p=!Ln&&c||o(r),h=e==="Array"&&d.entries||c,f,b,g;if(h&&(f=Bm(h.call(new s)),f!==Object.prototype&&f.next&&(!Mn&&Bm(f)!==Cm&&($m?$m(f,Cm):Wk(f[ls])||Ml(f,ls,_m)),Kk(f,u,!0,!0),Mn&&(Dm[u]=_m))),Zk&&r===cs&&c&&c.name!==cs&&(!Mn&&eA?Xk(d,"name",cs):(l=!0,p=function(){return Gk(c,this)})),r)if(b={values:o(cs),keys:a?p:o(Vm),entries:o(Om)},n)for(g in b)(Ln||l||!(g in d))&&Ml(d,g,b[g]);else Qk({target:e,proto:!0,forced:Ln||l},b);return(!Mn||n)&&d[ls]!==p&&Ml(d,ls,p,{name:r}),Dm[e]=p,b}});var jm=m((N_,Hm)=>{"use strict";Hm.exports=function(s,e){return{value:s,done:e}}});var Bl=m((U_,Ym)=>{"use strict";var tA=ki(),Ll=as(),zm=Li(),Gm=bl(),iA=Ri().f,rA=qm(),Bn=jm(),sA=Et(),aA=ut(),Wm="Array Iterator",nA=Gm.set,oA=Gm.getterFor(Wm);Ym.exports=rA(Array,"Array",function(s,e){nA(this,{type:Wm,target:tA(s),index:0,kind:e})},function(){var s=oA(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,Bn(void 0,!0);switch(s.kind){case"keys":return Bn(t,!1);case"values":return Bn(e[t],!1)}return Bn([t,e[t]],!1)},"values");var Qm=zm.Arguments=zm.Array;Ll("keys");Ll("values");Ll("entries");if(!sA&&aA&&Qm.name!=="values")try{iA(Qm,"name",{value:"values"})}catch{}});var Xm=m((q_,Km)=>{"use strict";var uA=Be(),lA=Li(),cA=uA("iterator"),dA=Array.prototype;Km.exports=function(s){return s!==void 0&&(lA.Array===s||dA[cA]===s)}});var $l=m((H_,Zm)=>{"use strict";var pA=os(),Jm=es(),hA=Zi(),fA=Li(),mA=Be(),bA=mA("iterator");Zm.exports=function(s){if(!hA(s))return Jm(s,bA)||Jm(s,"@@iterator")||fA[pA(s)]}});var tb=m((j_,eb)=>{"use strict";var gA=lt(),SA=Bt(),vA=$t(),yA=Zr(),TA=$l(),IA=TypeError;eb.exports=function(s,e){var t=arguments.length<2?TA(s):e;if(SA(t))return vA(gA(t,s));throw new IA(yA(s)+" is not iterable")}});var sb=m((z_,rb)=>{"use strict";var xA=lt(),ib=$t(),EA=es();rb.exports=function(s,e,t){var i,r;ib(s);try{if(i=EA(s,"return"),!i){if(e==="throw")throw t;return t}i=xA(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return ib(i),t}});var Dn=m((Q_,ub)=>{"use strict";var wA=rr(),PA=lt(),kA=$t(),AA=Zr(),RA=Xm(),MA=or(),ab=Jr(),LA=tb(),BA=$l(),nb=sb(),$A=TypeError,$n=function(s,e){this.stopped=s,this.result=e},ob=$n.prototype;ub.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=wA(e,i),l,d,c,p,h,f,b,g=function(T){return l&&nb(l,"normal",T),new $n(!0,T)},S=function(T){return r?(kA(T),o?u(T[0],T[1],g):u(T[0],T[1])):o?u(T,g):u(T)};if(a)l=s.iterator;else if(n)l=s;else{if(d=BA(s),!d)throw new $A(AA(s)+" is not iterable");if(RA(d)){for(c=0,p=MA(s);p>c;c++)if(h=S(s[c]),h&&ab(ob,h))return h;return new $n(!1)}l=LA(s,d)}for(f=a?s.next:l.next;!(b=PA(f,l)).done;){try{h=S(b.value)}catch(T){nb(l,"throw",T)}if(typeof h=="object"&&h&&ab(ob,h))return h}return new $n(!1)}});var cb=m((G_,lb)=>{"use strict";var DA=ut(),CA=Ri(),VA=Xr();lb.exports=function(s,e,t){DA?CA.f(s,e,VA(0,t)):s[e]=t}});var db=m(()=>{"use strict";var OA=Ie(),_A=Dn(),FA=cb();OA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return _A(e,function(i,r){FA(t,i,r)},{AS_ENTRIES:!0}),t}})});var hb=m((K_,pb)=>{"use strict";Bl();db();var NA=er();pb.exports=NA.Object.fromEntries});var mb=m((X_,fb)=>{"use strict";fb.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 gb=m(()=>{"use strict";Bl();var UA=mb(),qA=ve(),HA=us(),bb=Li();for(Cn in UA)HA(qA[Cn],Cn),bb[Cn]=bb.Array;var Cn});var vb=m((eF,Sb)=>{"use strict";var jA=hb();gb();Sb.exports=jA});var Dl=m((tF,yb)=>{"use strict";var zA=vb();yb.exports=zA});var Tb=m(()=>{"use strict"});var Cl=m((sF,Ib)=>{"use strict";var ds=ve(),QA=Ai(),GA=Pi(),Vn=function(s){return QA.slice(0,s.length)===s};Ib.exports=function(){return Vn("Bun/")?"BUN":Vn("Cloudflare-Workers")?"CLOUDFLARE":Vn("Deno/")?"DENO":Vn("Node.js/")?"NODE":ds.Bun&&typeof Bun.version=="string"?"BUN":ds.Deno&&typeof Deno.version=="object"?"DENO":GA(ds.process)==="process"?"NODE":ds.window&&ds.document?"BROWSER":"REST"}()});var On=m((aF,xb)=>{"use strict";var WA=Cl();xb.exports=WA==="NODE"});var wb=m((nF,Eb)=>{"use strict";var YA=Ri();Eb.exports=function(s,e,t){return YA.f(s,e,t)}});var Ab=m((oF,kb)=>{"use strict";var KA=Yt(),XA=wb(),JA=Be(),ZA=ut(),Pb=JA("species");kb.exports=function(s){var e=KA(s);ZA&&e&&!e[Pb]&&XA(e,Pb,{configurable:!0,get:function(){return this}})}});var Mb=m((uF,Rb)=>{"use strict";var eR=Jr(),tR=TypeError;Rb.exports=function(s,e){if(eR(e,s))return s;throw new tR("Incorrect invocation")}});var Ol=m((lF,Lb)=>{"use strict";var iR=ke(),rR=me(),Vl=ts(),sR=iR(Function.toString);rR(Vl.inspectSource)||(Vl.inspectSource=function(s){return sR(s)});Lb.exports=Vl.inspectSource});var Fl=m((cF,Vb)=>{"use strict";var aR=ke(),nR=Le(),Bb=me(),oR=os(),uR=Yt(),lR=Ol(),$b=function(){},Db=uR("Reflect","construct"),_l=/^\s*(?:class|function)\b/,cR=aR(_l.exec),dR=!_l.test($b),ps=function(e){if(!Bb(e))return!1;try{return Db($b,[],e),!0}catch{return!1}},Cb=function(e){if(!Bb(e))return!1;switch(oR(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return dR||!!cR(_l,lR(e))}catch{return!0}};Cb.sham=!0;Vb.exports=!Db||nR(function(){var s;return ps(ps.call)||!ps(Object)||!ps(function(){s=!0})||s})?Cb:ps});var _b=m((dF,Ob)=>{"use strict";var pR=Fl(),hR=Zr(),fR=TypeError;Ob.exports=function(s){if(pR(s))return s;throw new fR(hR(s)+" is not a constructor")}});var Nl=m((pF,Nb)=>{"use strict";var Fb=$t(),mR=_b(),bR=Zi(),gR=Be(),SR=gR("species");Nb.exports=function(s,e){var t=Fb(s).constructor,i;return t===void 0||bR(i=Fb(t)[SR])?e:mR(i)}});var qb=m((hF,Ub)=>{"use strict";var vR=ke();Ub.exports=vR([].slice)});var jb=m((fF,Hb)=>{"use strict";var yR=TypeError;Hb.exports=function(s,e){if(s<e)throw new yR("Not enough arguments");return s}});var Ul=m((mF,zb)=>{"use strict";var TR=Ai();zb.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(TR)});var Kl=m((bF,eg)=>{"use strict";var pt=ve(),IR=Mu(),xR=rr(),Qb=me(),ER=wt(),Zb=Le(),Gb=yl(),wR=qb(),Wb=gn(),PR=jb(),kR=Ul(),AR=On(),Gl=pt.setImmediate,Wl=pt.clearImmediate,RR=pt.process,ql=pt.Dispatch,MR=pt.Function,Yb=pt.MessageChannel,LR=pt.String,Hl=0,hs={},Kb="onreadystatechange",fs,$i,jl,zl;Zb(function(){fs=pt.location});var Yl=function(s){if(ER(hs,s)){var e=hs[s];delete hs[s],e()}},Ql=function(s){return function(){Yl(s)}},Xb=function(s){Yl(s.data)},Jb=function(s){pt.postMessage(LR(s),fs.protocol+"//"+fs.host)};(!Gl||!Wl)&&(Gl=function(e){PR(arguments.length,1);var t=Qb(e)?e:MR(e),i=wR(arguments,1);return hs[++Hl]=function(){IR(t,void 0,i)},$i(Hl),Hl},Wl=function(e){delete hs[e]},AR?$i=function(s){RR.nextTick(Ql(s))}:ql&&ql.now?$i=function(s){ql.now(Ql(s))}:Yb&&!kR?(jl=new Yb,zl=jl.port2,jl.port1.onmessage=Xb,$i=xR(zl.postMessage,zl)):pt.addEventListener&&Qb(pt.postMessage)&&!pt.importScripts&&fs&&fs.protocol!=="file:"&&!Zb(Jb)?($i=Jb,pt.addEventListener("message",Xb,!1)):Kb in Wb("script")?$i=function(s){Gb.appendChild(Wb("script"))[Kb]=function(){Gb.removeChild(this),Yl(s)}}:$i=function(s){setTimeout(Ql(s),0)});eg.exports={set:Gl,clear:Wl}});var rg=m((gF,ig)=>{"use strict";var tg=ve(),BR=ut(),$R=Object.getOwnPropertyDescriptor;ig.exports=function(s){if(!BR)return tg[s];var e=$R(tg,s);return e&&e.value}});var Xl=m((SF,ag)=>{"use strict";var sg=function(){this.head=null,this.tail=null};sg.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}}};ag.exports=sg});var og=m((vF,ng)=>{"use strict";var DR=Ai();ng.exports=/ipad|iphone|ipod/i.test(DR)&&typeof Pebble<"u"});var lg=m((yF,ug)=>{"use strict";var CR=Ai();ug.exports=/web0s(?!.*chrome)/i.test(CR)});var bg=m((TF,mg)=>{"use strict";var cr=ve(),VR=rg(),cg=rr(),Jl=Kl().set,OR=Xl(),_R=Ul(),FR=og(),NR=lg(),Zl=On(),dg=cr.MutationObserver||cr.WebKitMutationObserver,pg=cr.document,hg=cr.process,_n=cr.Promise,ic=VR("queueMicrotask"),lr,ec,tc,Fn,fg;ic||(ms=new OR,bs=function(){var s,e;for(Zl&&(s=hg.domain)&&s.exit();e=ms.get();)try{e()}catch(t){throw ms.head&&lr(),t}s&&s.enter()},!_R&&!Zl&&!NR&&dg&&pg?(ec=!0,tc=pg.createTextNode(""),new dg(bs).observe(tc,{characterData:!0}),lr=function(){tc.data=ec=!ec}):!FR&&_n&&_n.resolve?(Fn=_n.resolve(void 0),Fn.constructor=_n,fg=cg(Fn.then,Fn),lr=function(){fg(bs)}):Zl?lr=function(){hg.nextTick(bs)}:(Jl=cg(Jl,cr),lr=function(){Jl(bs)}),ic=function(s){ms.head||lr(),ms.add(s)});var ms,bs;mg.exports=ic});var Sg=m((IF,gg)=>{"use strict";gg.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch{}}});var Nn=m((xF,vg)=>{"use strict";vg.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var Di=m((EF,yg)=>{"use strict";var UR=ve();yg.exports=UR.Promise});var dr=m((wF,Eg)=>{"use strict";var qR=ve(),gs=Di(),HR=me(),jR=Ju(),zR=Ol(),QR=Be(),Tg=Cl(),GR=Et(),rc=Fu(),Ig=gs&&gs.prototype,WR=QR("species"),sc=!1,xg=HR(qR.PromiseRejectionEvent),YR=jR("Promise",function(){var s=zR(gs),e=s!==String(gs);if(!e&&rc===66||GR&&!(Ig.catch&&Ig.finally))return!0;if(!rc||rc<51||!/native code/.test(s)){var t=new gs(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[WR]=i,sc=t.then(function(){})instanceof i,!sc)return!0}return!e&&(Tg==="BROWSER"||Tg==="DENO")&&!xg});Eg.exports={CONSTRUCTOR:YR,REJECTION_EVENT:xg,SUBCLASSING:sc}});var pr=m((PF,Pg)=>{"use strict";var wg=Bt(),KR=TypeError,XR=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new KR("Bad Promise constructor");e=i,t=r}),this.resolve=wg(e),this.reject=wg(t)};Pg.exports.f=function(s){return new XR(s)}});var zg=m(()=>{"use strict";var JR=Ie(),ZR=Et(),jn=On(),ci=ve(),br=lt(),kg=ur(),Ag=Rl(),eM=us(),tM=Ab(),iM=Bt(),Hn=me(),rM=ct(),sM=Mb(),aM=Nl(),$g=Kl().set,lc=bg(),nM=Sg(),oM=Nn(),uM=Xl(),Dg=bl(),zn=Di(),cc=dr(),Cg=pr(),Qn="Promise",Vg=cc.CONSTRUCTOR,lM=cc.REJECTION_EVENT,cM=cc.SUBCLASSING,ac=Dg.getterFor(Qn),dM=Dg.set,hr=zn&&zn.prototype,Ci=zn,Un=hr,Og=ci.TypeError,nc=ci.document,dc=ci.process,oc=Cg.f,pM=oc,hM=!!(nc&&nc.createEvent&&ci.dispatchEvent),_g="unhandledrejection",fM="rejectionhandled",Rg=0,Fg=1,mM=2,pc=1,Ng=2,qn,Mg,bM,Lg,Ug=function(s){var e;return rM(s)&&Hn(e=s.then)?e:!1},qg=function(s,e){var t=e.value,i=e.state===Fg,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===Ng&&SM(e),e.rejection=pc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new Og("Promise-chain cycle")):(l=Ug(u))?br(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},Hg=function(s,e){s.notified||(s.notified=!0,lc(function(){for(var t=s.reactions,i;i=t.get();)qg(i,s);s.notified=!1,e&&!s.rejection&&gM(s)}))},jg=function(s,e,t){var i,r;hM?(i=nc.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),ci.dispatchEvent(i)):i={promise:e,reason:t},!lM&&(r=ci["on"+s])?r(i):s===_g&&nM("Unhandled promise rejection",t)},gM=function(s){br($g,ci,function(){var e=s.facade,t=s.value,i=Bg(s),r;if(i&&(r=oM(function(){jn?dc.emit("unhandledRejection",t,e):jg(_g,e,t)}),s.rejection=jn||Bg(s)?Ng:pc,r.error))throw r.value})},Bg=function(s){return s.rejection!==pc&&!s.parent},SM=function(s){br($g,ci,function(){var e=s.facade;jn?dc.emit("rejectionHandled",e):jg(fM,e,s.value)})},fr=function(s,e,t){return function(i){s(e,i,t)}},mr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=mM,Hg(s,!0))},uc=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new Og("Promise can't be resolved itself");var i=Ug(e);i?lc(function(){var r={done:!1};try{br(i,e,fr(uc,r,s),fr(mr,r,s))}catch(a){mr(r,a,s)}}):(s.value=e,s.state=Fg,Hg(s,!1))}catch(r){mr({done:!1},r,s)}}};if(Vg&&(Ci=function(e){sM(this,Un),iM(e),br(qn,this);var t=ac(this);try{e(fr(uc,t),fr(mr,t))}catch(i){mr(t,i)}},Un=Ci.prototype,qn=function(e){dM(this,{type:Qn,done:!1,notified:!1,parent:!1,reactions:new uM,rejection:!1,state:Rg,value:void 0})},qn.prototype=kg(Un,"then",function(e,t){var i=ac(this),r=oc(aM(this,Ci));return i.parent=!0,r.ok=Hn(e)?e:!0,r.fail=Hn(t)&&t,r.domain=jn?dc.domain:void 0,i.state===Rg?i.reactions.add(r):lc(function(){qg(r,i)}),r.promise}),Mg=function(){var s=new qn,e=ac(s);this.promise=s,this.resolve=fr(uc,e),this.reject=fr(mr,e)},Cg.f=oc=function(s){return s===Ci||s===bM?new Mg(s):pM(s)},!ZR&&Hn(zn)&&hr!==Object.prototype)){Lg=hr.then,cM||kg(hr,"then",function(e,t){var i=this;return new Ci(function(r,a){br(Lg,i,r,a)}).then(e,t)},{unsafe:!0});try{delete hr.constructor}catch{}Ag&&Ag(hr,Un)}JR({global:!0,constructor:!0,wrap:!0,forced:Vg},{Promise:Ci});eM(Ci,Qn,!1,!0);tM(Qn)});var Kg=m((RF,Yg)=>{"use strict";var vM=Be(),Gg=vM("iterator"),Wg=!1;try{Qg=0,hc={next:function(){return{done:!!Qg++}},return:function(){Wg=!0}},hc[Gg]=function(){return this},Array.from(hc,function(){throw 2})}catch{}var Qg,hc;Yg.exports=function(s,e){try{if(!e&&!Wg)return!1}catch{return!1}var t=!1;try{var i={};i[Gg]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch{}return t}});var fc=m((MF,Xg)=>{"use strict";var yM=Di(),TM=Kg(),IM=dr().CONSTRUCTOR;Xg.exports=IM||!TM(function(s){yM.all(s).then(void 0,function(){})})});var Jg=m(()=>{"use strict";var xM=Ie(),EM=lt(),wM=Bt(),PM=pr(),kM=Nn(),AM=Dn(),RM=fc();xM({target:"Promise",stat:!0,forced:RM},{all:function(e){var t=this,i=PM.f(t),r=i.resolve,a=i.reject,n=kM(function(){var o=wM(t.resolve),u=[],l=0,d=1;AM(e,function(c){var p=l++,h=!1;d++,EM(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 eS=m(()=>{"use strict";var MM=Ie(),LM=Et(),BM=dr().CONSTRUCTOR,bc=Di(),$M=Yt(),DM=me(),CM=ur(),Zg=bc&&bc.prototype;MM({target:"Promise",proto:!0,forced:BM,real:!0},{catch:function(s){return this.then(void 0,s)}});!LM&&DM(bc)&&(mc=$M("Promise").prototype.catch,Zg.catch!==mc&&CM(Zg,"catch",mc,{unsafe:!0}));var mc});var tS=m(()=>{"use strict";var VM=Ie(),OM=lt(),_M=Bt(),FM=pr(),NM=Nn(),UM=Dn(),qM=fc();VM({target:"Promise",stat:!0,forced:qM},{race:function(e){var t=this,i=FM.f(t),r=i.reject,a=NM(function(){var n=_M(t.resolve);UM(e,function(o){OM(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var iS=m(()=>{"use strict";var HM=Ie(),jM=pr(),zM=dr().CONSTRUCTOR;HM({target:"Promise",stat:!0,forced:zM},{reject:function(e){var t=jM.f(this),i=t.reject;return i(e),t.promise}})});var gc=m((FF,rS)=>{"use strict";var QM=$t(),GM=ct(),WM=pr();rS.exports=function(s,e){if(QM(s),GM(e)&&e.constructor===s)return e;var t=WM.f(s),i=t.resolve;return i(e),t.promise}});var nS=m(()=>{"use strict";var YM=Ie(),KM=Yt(),sS=Et(),XM=Di(),aS=dr().CONSTRUCTOR,JM=gc(),ZM=KM("Promise"),eL=sS&&!aS;YM({target:"Promise",stat:!0,forced:sS||aS},{resolve:function(e){return JM(eL&&this===ZM?XM:this,e)}})});var oS=m(()=>{"use strict";zg();Jg();eS();tS();iS();nS()});var dS=m(()=>{"use strict";var tL=Ie(),iL=Et(),Gn=Di(),rL=Le(),lS=Yt(),cS=me(),sL=Nl(),uS=gc(),aL=ur(),vc=Gn&&Gn.prototype,nL=!!Gn&&rL(function(){vc.finally.call({then:function(){}},function(){})});tL({target:"Promise",proto:!0,real:!0,forced:nL},{finally:function(s){var e=sL(this,lS("Promise")),t=cS(s);return this.then(t?function(i){return uS(e,s()).then(function(){return i})}:s,t?function(i){return uS(e,s()).then(function(){throw i})}:s)}});!iL&&cS(Gn)&&(Sc=lS("Promise").prototype.finally,vc.finally!==Sc&&aL(vc,"finally",Sc,{unsafe:!0}));var Sc});var hS=m((QF,pS)=>{"use strict";Tb();oS();dS();var oL=li();pS.exports=oL("Promise","finally")});var mS=m((GF,fS)=>{"use strict";var uL=hS();fS.exports=uL});var Wn=m((WF,bS)=>{"use strict";var lL=mS();bS.exports=lL});var RS=m(()=>{"use strict";var xL=Ie(),EL=pl().values;xL({target:"Object",stat:!0},{values:function(e){return EL(e)}})});var LS=m((BN,MS)=>{"use strict";RS();var wL=er();MS.exports=wL.Object.values});var $S=m(($N,BS)=>{"use strict";var PL=LS();BS.exports=PL});var _i=m((DN,DS)=>{"use strict";var kL=$S();DS.exports=kL});var XS=m(()=>{"use strict";var KL=Ie(),XL=tr(),JL=or(),ZL=ss(),eB=as();KL({target:"Array",proto:!0},{at:function(e){var t=XL(this),i=JL(t),r=ZL(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});eB("at")});var ZS=m((HU,JS)=>{"use strict";XS();var tB=li();JS.exports=tB("Array","at")});var tv=m((jU,ev)=>{"use strict";var iB=ZS();ev.exports=iB});var kt=m((zU,iv)=>{"use strict";var rB=tv();iv.exports=rB});var qc=m((L1,Cv)=>{"use strict";var OB=Pi();Cv.exports=Array.isArray||function(e){return OB(e)==="Array"}});var Ov=m((B1,Vv)=>{"use strict";var _B=TypeError,FB=9007199254740991;Vv.exports=function(s){if(s>FB)throw _B("Maximum allowed index exceeded");return s}});var Nv=m(($1,Fv)=>{"use strict";var NB=qc(),UB=or(),qB=Ov(),HB=rr(),_v=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?HB(n,o):!1,c,p;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&NB(c)?(p=UB(c),u=_v(s,e,c,p,u,a-1)-1):(qB(u+1),s[u]=c),u++),l++;return u};Fv.exports=_v});var jv=m((D1,Hv)=>{"use strict";var Uv=qc(),jB=Fl(),zB=ct(),QB=Be(),GB=QB("species"),qv=Array;Hv.exports=function(s){var e;return Uv(s)&&(e=s.constructor,jB(e)&&(e===qv||Uv(e.prototype))?e=void 0:zB(e)&&(e=e[GB],e===null&&(e=void 0))),e===void 0?qv:e}});var Qv=m((C1,zv)=>{"use strict";var WB=jv();zv.exports=function(s,e){return new(WB(s))(e===0?0:e)}});var Gv=m(()=>{"use strict";var YB=Ie(),KB=Nv(),XB=Bt(),JB=tr(),ZB=or(),e$=Qv();YB({target:"Array",proto:!0},{flatMap:function(e){var t=JB(this),i=ZB(t),r;return XB(e),r=e$(t,0),r.length=KB(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Wv=m(()=>{"use strict";var t$=as();t$("flatMap")});var Kv=m((N1,Yv)=>{"use strict";Gv();Wv();var i$=li();Yv.exports=i$("Array","flatMap")});var Jv=m((U1,Xv)=>{"use strict";var r$=Kv();Xv.exports=r$});var Ds=m((q1,Zv)=>{"use strict";var s$=Jv();Zv.exports=s$});var Cs=m((H1,ey)=>{"use strict";var a$=os(),n$=String;ey.exports=function(s){if(a$(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return n$(s)}});var Hc=m((j1,ty)=>{"use strict";ty.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 sy=m((z1,ry)=>{"use strict";var o$=ke(),u$=ui(),l$=Cs(),zc=Hc(),iy=o$("".replace),c$=RegExp("^["+zc+"]+"),d$=RegExp("(^|[^"+zc+"])["+zc+"]+$"),jc=function(s){return function(e){var t=l$(u$(e));return s&1&&(t=iy(t,c$,"")),s&2&&(t=iy(t,d$,"$1")),t}};ry.exports={start:jc(1),end:jc(2),trim:jc(3)}});var uy=m((Q1,oy)=>{"use strict";var p$=vl().PROPER,h$=Le(),ay=Hc(),ny="\u200B\x85\u180E";oy.exports=function(s){return h$(function(){return!!ay[s]()||ny[s]()!==ny||p$&&ay[s].name!==s})}});var Qc=m((G1,ly)=>{"use strict";var f$=sy().start,m$=uy();ly.exports=m$("trimStart")?function(){return f$(this)}:"".trimStart});var dy=m(()=>{"use strict";var b$=Ie(),cy=Qc();b$({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==cy},{trimLeft:cy})});var hy=m(()=>{"use strict";dy();var g$=Ie(),py=Qc();g$({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==py},{trimStart:py})});var my=m((J1,fy)=>{"use strict";hy();var S$=li();fy.exports=S$("String","trimLeft")});var gy=m((Z1,by)=>{"use strict";var v$=my();by.exports=v$});var vy=m((eH,Sy)=>{"use strict";var y$=gy();Sy.exports=y$});var Dy=m(()=>{"use strict"});var Cy=m(()=>{"use strict"});var Oy=m((D2,Vy)=>{"use strict";var H$=ct(),j$=Pi(),z$=Be(),Q$=z$("match");Vy.exports=function(s){var e;return H$(s)&&((e=s[Q$])!==void 0?!!e:j$(s)==="RegExp")}});var Fy=m((C2,_y)=>{"use strict";var G$=$t();_y.exports=function(){var s=G$(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 qy=m((V2,Uy)=>{"use strict";var W$=lt(),Y$=wt(),K$=Jr(),X$=Fy(),Ny=RegExp.prototype;Uy.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in Ny)&&!Y$(s,"flags")&&K$(Ny,s)?W$(X$,s):e}});var jy=m((O2,Hy)=>{"use strict";var Jc=ke(),J$=tr(),Z$=Math.floor,Kc=Jc("".charAt),eD=Jc("".replace),Xc=Jc("".slice),tD=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,iD=/\$([$&'`]|\d{1,2})/g;Hy.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=iD;return r!==void 0&&(r=J$(r),u=tD),eD(a,u,function(l,d){var c;switch(Kc(d,0)){case"$":return"$";case"&":return s;case"`":return Xc(e,0,t);case"'":return Xc(e,n);case"<":c=r[Xc(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=Z$(p/10);return h===0?l:h<=o?i[h-1]===void 0?Kc(d,1):i[h-1]+Kc(d,1):l}c=i[p-1]}return c===void 0?"":c})}});var Gy=m(()=>{"use strict";var rD=Ie(),sD=lt(),ed=ke(),zy=ui(),aD=me(),nD=Zi(),oD=Oy(),Mr=Cs(),uD=es(),lD=qy(),cD=jy(),dD=Be(),pD=Et(),hD=dD("replace"),fD=TypeError,Zc=ed("".indexOf),mD=ed("".replace),Qy=ed("".slice),bD=Math.max;rD({target:"String",proto:!0},{replaceAll:function(e,t){var i=zy(this),r,a,n,o,u,l,d,c,p,h,f=0,b="";if(!nD(e)){if(r=oD(e),r&&(a=Mr(zy(lD(e))),!~Zc(a,"g")))throw new fD("`.replaceAll` does not allow non-global regexes");if(n=uD(e,hD),n)return sD(n,e,i,t);if(pD&&r)return mD(Mr(i),e,t)}for(o=Mr(i),u=Mr(e),l=aD(t),l||(t=Mr(t)),d=u.length,c=bD(1,d),p=Zc(o,u);p!==-1;)h=l?Mr(t(u,p,o)):cD(u,o,p,[],void 0,t),b+=Qy(o,f,p)+h,f=p+d,p=p+c>o.length?-1:Zc(o,u,p+c);return f<o.length&&(b+=Qy(o,f)),b}})});var Yy=m((N2,Wy)=>{"use strict";Dy();Cy();Gy();var gD=li();Wy.exports=gD("String","replaceAll")});var Xy=m((U2,Ky)=>{"use strict";var SD=Yy();Ky.exports=SD});var td=m((q2,Jy)=>{"use strict";var vD=Xy();Jy.exports=vD});var eT=m((H2,Zy)=>{"use strict";var yD=ss(),TD=Cs(),ID=ui(),xD=RangeError;Zy.exports=function(e){var t=TD(ID(this)),i="",r=yD(e);if(r<0||r===1/0)throw new xD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var aT=m((j2,sT)=>{"use strict";var rT=ke(),ED=sl(),tT=Cs(),wD=eT(),PD=ui(),kD=rT(wD),AD=rT("".slice),RD=Math.ceil,iT=function(s){return function(e,t,i){var r=tT(PD(e)),a=ED(t),n=r.length,o=i===void 0?" ":tT(i),u,l;return a<=n||o===""?r:(u=a-n,l=kD(o,RD(u/o.length)),l.length>u&&(l=AD(l,0,u)),s?r+l:l+r)}};sT.exports={start:iT(!1),end:iT(!0)}});var oT=m((z2,nT)=>{"use strict";var MD=Ai();nT.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(MD)});var uT=m(()=>{"use strict";var LD=Ie(),BD=aT().start,$D=oT();LD({target:"String",proto:!0,forced:$D},{padStart:function(e){return BD(this,e,arguments.length>1?arguments[1]:void 0)}})});var cT=m((W2,lT)=>{"use strict";uT();var DD=li();lT.exports=DD("String","padStart")});var pT=m((Y2,dT)=>{"use strict";var CD=cT();dT.exports=CD});var id=m((K2,hT)=>{"use strict";var VD=pT();hT.exports=VD});var Ep="2.0.135-dev.f94adb28.0";var Qe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Qe||{}),Wt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(Wt||{});var hn=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(hn||{}),ku=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(ku||{});var Au=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Au||{}),fn=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(fn||{});var Ix=C(dt(),1);import{assertNever as xf,assertNonNullable as Kw,isNonNullable as vn,ValueSubject as nl,Subject as Xw,Subscription as Jw,merge as Zw,observableFrom as eP,fromEvent as vf,map as yf,tap as Tf,filterChanged as tP,isNullable as ol,ErrorCategory as If}from"@vkontakte/videoplayer-shared";var Sf=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 yn=class{constructor(e){this.connection$=new nl(void 0);this.castState$=new nl("NOT_AVAILABLE");this.errorEvent$=new Xw;this.realCastState$=new nl("NOT_AVAILABLE");this.subscription=new Jw;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=vn(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&!this.isDestroyed&&this.initializeCastApi()},r||Sf("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:If.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){vn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();ol(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();ol(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(vf(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return xf(r.sessionState)}})).add(Zw(vf(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Tf(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),yf(r=>r.castState)),eP([i.getCastState()])).pipe(tP(),yf(iP),Tf(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",n=vn(this.connection$.getValue());if(a&&!n){let o=i.getCurrentSession();Kw(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(ol(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?vn(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:If.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},iP=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 xf(s)}};var mp=C(dt(),1),rx=C(Mi(),1),sx=C(Dl(),1);var PS=C(Wn(),1);import{assertNever as gS}from"@vkontakte/videoplayer-shared";var be=(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:gS(t)}return s},di=(s,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(s);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(s);return Number(t.searchParams.get("offset_p")??0)}default:gS(e)}};var R=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as cL,Subject as Yn,merge as SS}from"@vkontakte/videoplayer-shared";var U=class{constructor(e){this.transitionStarted$=new Yn;this.transitionEnded$=new Yn;this.transitionUpdated$=new Yn;this.forceChanged$=new Yn;this.stateChangeStarted$=SS(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=SS(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||cL(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}};import{assertNever as dL}from"@vkontakte/videoplayer-shared";var vS=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 dL(s)}};import{assertNever as gr,assertNonNullable as Vi,debounce as yS,ErrorCategory as TS,fromEvent as Oi,isNonNullable as IS,map as xS,merge as ES,observableFrom as pL,Subject as hL,Subscription as yc,timeout as fL,getHighestQuality as mL}from"@vkontakte/videoplayer-shared";var bL=5,gL=5,SL=500,wS=7e3,Ss=class{constructor(e){this.subscription=new yc;this.loadMediaTimeoutSubscription=new yc;this.videoState=new U("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?.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:gr(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:gr(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:gr(e)}break}default:gr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(vS(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 yc;this.subscription.add(e),this.subscription.add(ES(this.videoState.stateChangeStarted$.pipe(xS(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(xS(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 hL;e.add(r.pipe(yS(SL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(Oi(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)>bL)&&r.next(o),a=o})),e.add(Oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Oi(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<gL&&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:gr(n)}}),t(Oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=ES(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,pL(["init"])).pipe(yS(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();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),R(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&R(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,a;switch(e){case"MPEG":{let l=t[e];Vi(l);let d=mL(Object.keys(l));Vi(d);let c=l[d];Vi(c),i=c,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Vi(l),i=l.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 l=t[e];Vi(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Vi(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Vi(l),i=be(l.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:TS.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return gr(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return IS(o)&&(n.metadata.title=o),IS(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(fL(wS).subscribe(()=>a(`timeout(${wS})`)))});(0,PS.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:TS.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Nc=C(dt(),1);import{clearVideoElement as AS}from"@vkontakte/videoplayer-shared";import{clearVideoElement as vL}from"@vkontakte/videoplayer-shared";var kS=s=>{try{s.pause(),s.playbackRate=0,vL(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as yL,Subscription as TL}from"@vkontakte/videoplayer-shared";var Tc=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)}},Ic=window.WeakMap?new WeakMap:new Tc,xc=window.WeakMap?new WeakMap:new Map,IL=(s,e=20)=>{let t=0;return yL(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Ge=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?AS(i):(i=document.createElement("video"),s.appendChild(i)),Ic.set(i,r);let a=new TL;return a.add(IL(i,e)),xc.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},We=s=>{xc.get(s)?.unsubscribe(),xc.delete(s);let t=Ic.get(s);Ic.delete(s),t?AS(s):kS(s)};var wc=C(_i(),1);import{assertNonNullable as ys,isNonNullable as Ct,isNullable as ML,fromEvent as Sr,merge as CS,observableFrom as VS,filterChanged as OS,map as Ts,Subject as _S,Subscription as LL,ValueSubject as BL,ErrorCategory as $L}from"@vkontakte/videoplayer-shared";import{isNonNullable as Ec,isNullable as AL,Subscription as RL}from"@vkontakte/videoplayer-shared";var Kn=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=AL(r),l=new RL;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},Dt=(s,e,t)=>Kn(e,()=>s.loop,i=>{Ec(i)&&(s.loop=i)},{onError:t}),Ye=(s,e,t,i)=>Kn(e,()=>({muted:s.muted,volume:s.volume}),r=>{Ec(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),mt=(s,e,t,i)=>Kn(e,()=>s.playbackRate,r=>{Ec(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),vs=Kn;var DL=s=>["__",s.language,s.label].join("|"),CL=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Pc=class s{constructor(e){this.available$=new _S;this.current$=new BL(void 0);this.error$=new _S;this.subscription=new LL;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:$L.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(vs(t.internalTextTracks,()=>(0,wc.default)(this.internalTracks),a=>{Ct(a)&&this.setInternal(a)},{equal:(a,n)=>Ct(a)&&Ct(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ts(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(vs(t.externalTextTracks,()=>(0,wc.default)(this.externalTracks),a=>{Ct(a)&&this.setExternal(a)},{equal:(a,n)=>Ct(a)&&Ct(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ts(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(vs(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(vs(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){ys(this.video);let{textTracks:e}=this.video;this.subscription.add(Sr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(CS(Sr(e,"addtrack"),Sr(e,"removetrack"),VS(["init"])).pipe(Ts(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),OS((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(CS(Sr(e,"change"),VS(["init"])).pipe(Ts(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ts(i=>i&&this.htmlTextTrackToITextTrack(i).id),OS()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Sr(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(Sr(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;Ct(t.align)&&(r.align=t.align),Ct(t.position)&&(r.position=t.position),Ct(t.size)&&(r.size=t.size),Ct(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ys(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:DL(e),a=this.externalTracks.has(r),n=(a?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto: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){ys(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(ML(e)||!CL(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){ys(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){ys(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)}},bt=Pc;var Fi=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 FS=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},kc=s=>{let e=FS(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},NS=s=>{let e=FS(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as Ue,map as Vt,merge as ro,filterChanged as WS,isNonNullable as YS,Subject as jL,filter as Rc,mapTo as Mc,combine as zL,once as QL,throttle as GL,ErrorCategory as WL,ValueSubject as KS,Subscription as YL}from"@vkontakte/videoplayer-shared";var VL=3,US=(s,e,t=VL)=>{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 Xn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,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._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var qS=C(dt(),1);var Is=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Jn=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,qS.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=Is()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){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 Zn=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(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}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(t){console.error(t)}}};var ht=()=>window.ManagedMediaSource||window.MediaSource,vr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),HS=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),eo=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var OL=document.createElement("video"),_L='video/mp4; codecs="avc1.42000a,mp4a.40.2"',FL='video/mp4; codecs="hev1.1.6.L93.B0"',jS='video/webm; codecs="vp09.00.10.08"',zS='video/webm; codecs="av01.0.00M.08"',NL='audio/mp4; codecs="mp4a.40.2"',UL='audio/webm; codecs="opus"',QS,qL=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:zS}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:jS}})]);QS={DASH_WEBM_AV1:e,DASH_WEBM:t}};qL().catch(s=>{console.log(OL),console.error(s)});var to=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 QS}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:vr(),mse:HS(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!ht()?.isTypeSupported?.(_L),t=!!ht()?.isTypeSupported?.(FL),i=!!ht()?.isTypeSupported?.(NL);this._codecs={h264:e,h265:t,vp9:!!ht()?.isTypeSupported?.(jS),av1:!!ht()?.isTypeSupported?.(zS),aac:i,opus:!!ht()?.isTypeSupported?.(UL),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var GS="audio/mpeg",io=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(GS)},this._codecs={mp3:!!ht()?.isTypeSupported?.(GS)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as HL}from"@vkontakte/videoplayer-shared";var Ac=class{constructor(){this.isInited$=new HL(!1);this._displayChecker=new Zn,this._deviceChecker=new Jn(this._displayChecker),this._browserChecker=new Xn,this._videoChecker=new to(this._deviceChecker,this._browserChecker),this._audioChecker=new io,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)}},F=new Ac;var Ke=s=>{let e=v=>Ue(s,v).pipe(Mc(void 0)),t=new YL,i=()=>t.unsubscribe(),r=ro(Ue(s,"progress"),Ue(s,"timeupdate")).pipe(Vt(()=>US(s.buffered,s.currentTime))),a=F.browser.isSafari?zL({play:e("play").pipe(QL()),playing:e("playing")}).pipe(Mc(void 0)):e("playing"),n=Ue(s,"volumechange").pipe(Vt(()=>({muted:s.muted,volume:s.volume}))),o=Ue(s,"ratechange").pipe(Vt(()=>s.playbackRate)),u=Ue(s,"error").pipe(Rc(()=>!!(s.error||s.played.length)),Vt(()=>{let v=s.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:WL.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:s.error??void 0}})),l=Ue(s,"timeupdate").pipe(Vt(()=>s.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new jL,p=.3,h;t.add(ro(...d.map(v=>Ue(s,v))).subscribe(v=>{let D=s.currentTime;s.loop&&YS(h)&&YS(D)&&h>=s.duration-p&&D<=p&&c.next(h),h=D}));let f=e("pause").pipe(Rc(()=>!s.error&&h!==s.duration)),b=Ue(s,"enterpictureinpicture"),g=Ue(s,"leavepictureinpicture"),S=new KS(NS(s));t.add(b.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let T=new KS(kc(s)),y=Ue(s,"fullscreenchange");t.add(y.pipe(Vt(()=>kc(s))).subscribe(T));let E=.1,w=1e3,L=Ue(s,"timeupdate").pipe(Vt(v=>s.duration-s.currentTime<E),WS()),O=ro(L.pipe(Rc(v=>!s.loop&&v)),Ue(s,"ended")).pipe(GL(w),Mc(void 0)),k=ro(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>Ue(s,v)),L.pipe(Vt(v=>({type:v?"ended":"unknown"})))).pipe(Vt(v=>F.browser.isFirefox&&v.type==="ended"?s.readyState<2:s.readyState<3),WS());return{playing$:a,pause$:f,canplay$:e("canplay"),ended$:O,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ue(s,"durationchange").pipe(Vt(()=>s.duration)),isBuffering$:k,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:T,enterPip$:b,leavePip$:g,destroy:i}};import{VideoQuality as pi}from"@vkontakte/videoplayer-shared";var hi=s=>{switch(s){case"mobile":return pi.Q_144P;case"lowest":return pi.Q_240P;case"low":return pi.Q_360P;case"sd":case"medium":return pi.Q_480P;case"hd":case"high":return pi.Q_720P;case"fullhd":case"full":return pi.Q_1080P;case"quadhd":case"quad":return pi.Q_1440P;case"ultrahd":case"ultra":return pi.Q_2160P}};var He=C(kt(),1),$c=C(dt(),1),Ni=C(Mi(),1);import{isNonNullable as J,isNullable as uo,now as pv,isHigher as lo,isHigherOrEqual as Tr,isInvariantQuality as co,isLowerOrEqual as Ir,videoSizeToQuality as hv,assertNotEmptyArray as po,assertNonNullable as fv}from"@vkontakte/videoplayer-shared";var Lc=!1,Jt={},rv=s=>{Lc=s},sv=()=>{Jt={}},av=s=>{s(Jt)},xs=(s,e)=>{Lc&&(Jt.meta=Jt.meta??{},Jt.meta[s]=e)},qe=class{constructor(e){this.name=e}next(e){if(!Lc)return;Jt.series=Jt.series??{};let t=Jt.series[this.name]??[];t.push([Date.now(),e]),Jt.series[this.name]=t}};import{isHigher as sB,isHigherOrEqual as XU,isLower as nv,isLowerOrEqual as JU,isNonNullable as so,isNullable as aB,videoHeightToQuality as ao}from"@vkontakte/videoplayer-shared";function Bc(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function no(s,e,t){return!!s&&Bc(s,e,t)==="high_quality"}function yr(s,e,t){return aB(s)||so(s.min)&&so(s.max)&&nv(s.max,s.min)||so(s.min)&&e&&sB(s.min,e)||so(s.max)&&t&&nv(s.max,t)}function ov({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return yr({max:s?.max?ao(s.max):void 0,min:s?.min?ao(s.min):void 0},e?ao(e):void 0,t?ao(t):void 0)}var mv=new qe("best_bitrate"),ho=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var xr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),fi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=pv()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},fo='Assertion "ABR Tracks is empty array" failed',oo=new WeakMap,uv=new WeakMap,lv=new WeakMap,Es=(s,e,t,i)=>{let r=[...e].sort(xr(1)),a=[...t].sort(xr(1)),n=a.filter(u=>J(u.bitrate)&&J(s.bitrate)?s.bitrate/u.bitrate>i:!0),o=(0,He.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,He.default)(a,-1);return o&&(0,$c.default)(n,o)?o:n.length?(0,He.default)(n,-1):(0,He.default)(a,0)},ws=(s,e,t,i)=>{let r=oo.get(e);r||(r=[...e].sort(xr(1)),oo.set(e,r));let a=oo.get(t);a||(a=[...t].sort(xr(1)),oo.set(t,a));let n=lv.get(s);n||(n=a.filter(u=>J(u.bitrate)&&J(s.bitrate)?s.bitrate/u.bitrate>i:!0),lv.set(s,n));let o=(0,He.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,He.default)(a,-1);return o&&(0,$c.default)(n,o)?o:n.length?(0,He.default)(n,-1):(0,He.default)(a,0)},cv=s=>"quality"in s,mo=(s,e,t,i)=>{let r=J(i?.last?.bitrate)&&J(t?.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&pv()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!a&&i.recordSelection(t),a&&i?.last){let n=i.last;i?.recordSwitch(n);let o=cv(n)?"video":"audio",u=cv(n)?n.quality:n.bitrate;return e({message:`
8
- [last ${o} selected] ${u}
9
- `}),n}return i?.recordSwitch(t),t},nB=(s,e)=>Math.log(e)/Math.log(s),bv=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&F.display.pixelRatio){let a=F.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=nB(n,o*a+u)+l;Number.isFinite(d)&&(r*=d)}}return no(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}},dv=new WeakMap,Ot=(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})=>{po(s,fo);let{containerSizeFactor:g,containerSizeLimit:S}=bv({container:e,tuning:i,limits:r,panelSize:b}),T=i.considerPlaybackRate&&J(o)?o:1,y=dv.get(s);y||(y=s.filter(x=>!co(x.quality)).sort((x,A)=>lo(x.quality,A.quality)?-1:1),dv.set(s,y));let E=(0,He.default)(y,-1)?.quality,w=(0,He.default)(y,0)?.quality,L=yr(r,w,E),O=T*ho(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),P={},k=null;for(let x of y){let A=!0;if(S)if(x.size)A=x.size.width<=S.width&&x.size.height<=S.height;else{let M=S&&hv(S);A=M?Ir(x.quality,M):!0}if(!A){P[x.quality]="FitsContainer";continue}let re=h||t,$=J(re)&&isFinite(re)&&J(x.bitrate)?re-a>=x.bitrate*O:!0,q=no(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===x.quality;if(!$&&!q){P[x.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&J(i.minBufferToSwitchUp)&&u&&!co(u.quality)&&(n??0)<i.minBufferToSwitchUp&&lo(x.quality,u.quality)){P[x.quality]="Buffer";continue}if(!!c&&Tr(x.quality,c)&&!q){P[x.quality]="DroppedFramesLimit";continue}if(!!p&&Tr(x.quality,p)&&!q){P[x.quality]="StallsLimit";continue}let oe=L||(uo(r?.max)||Ir(x.quality,r.max))&&(uo(r?.min)||Tr(x.quality,r.min)),Z=J(d)&&!d?Ir(x.quality,i.backgroundVideoQualityLimit):!0;if(!oe||!Z){P[x.quality]="FitsQualityLimits";continue}k||(k=x)}k&&k.bitrate&&mv.next(k.bitrate);let v=k??(0,He.default)(y,-1)??s[0],D=l?.last,I=mo(i,f,v,l);return J(l)&&I.quality!==D?.quality&&f({message:`
6
+ var MI=Object.create;var $d=Object.defineProperty;var DI=Object.getOwnPropertyDescriptor;var CI=Object.getOwnPropertyNames;var BI=Object.getPrototypeOf,VI=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var _I=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of CI(e))!VI.call(a,r)&&r!==t&&$d(a,r,{get:()=>e[r],enumerable:!(i=DI(e,r))||i.enumerable});return a};var C=(a,e,t)=>(t=a!=null?MI(BI(a)):{},_I(e||!a||!a.__esModule?$d(t,"default",{value:a,enumerable:!0}):t,a));var re=m((Go,Dd)=>{"use strict";var Dr=function(a){return a&&a.Math===Math&&a};Dd.exports=Dr(typeof globalThis=="object"&&globalThis)||Dr(typeof window=="object"&&window)||Dr(typeof self=="object"&&self)||Dr(typeof global=="object"&&global)||Dr(typeof Go=="object"&&Go)||function(){return this}()||Function("return this")()});var le=m((V0,Cd)=>{"use strict";Cd.exports=function(a){try{return!!a()}catch{return!0}}});var Cr=m((_0,Bd)=>{"use strict";var OI=le();Bd.exports=!OI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Wo=m((O0,Fd)=>{"use strict";var FI=Cr(),Od=Function.prototype,Vd=Od.apply,_d=Od.call;Fd.exports=typeof Reflect=="object"&&Reflect.apply||(FI?_d.bind(Vd):function(){return _d.apply(Vd,arguments)})});var ce=m((F0,qd)=>{"use strict";var Nd=Cr(),Ud=Function.prototype,zo=Ud.call,NI=Nd&&Ud.bind.bind(zo,zo);qd.exports=Nd?NI:function(a){return function(){return zo.apply(a,arguments)}}});var ri=m((N0,jd)=>{"use strict";var Hd=ce(),UI=Hd({}.toString),qI=Hd("".slice);jd.exports=function(a){return qI(UI(a),8,-1)}});var Yo=m((U0,Qd)=>{"use strict";var HI=ri(),jI=ce();Qd.exports=function(a){if(HI(a)==="Function")return jI(a)}});var ae=m((q0,Gd)=>{"use strict";var Ko=typeof document=="object"&&document.all;Gd.exports=typeof Ko>"u"&&Ko!==void 0?function(a){return typeof a=="function"||a===Ko}:function(a){return typeof a=="function"}});var Oe=m((H0,Wd)=>{"use strict";var QI=le();Wd.exports=!QI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Fe=m((j0,zd)=>{"use strict";var GI=Cr(),Ms=Function.prototype.call;zd.exports=GI?Ms.bind(Ms):function(){return Ms.apply(Ms,arguments)}});var Xo=m(Xd=>{"use strict";var Yd={}.propertyIsEnumerable,Kd=Object.getOwnPropertyDescriptor,WI=Kd&&!Yd.call({1:2},1);Xd.f=WI?function(e){var t=Kd(this,e);return!!t&&t.enumerable}:Yd});var Br=m((G0,Jd)=>{"use strict";Jd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var ep=m((W0,Zd)=>{"use strict";var zI=ce(),YI=le(),KI=ri(),Jo=Object,XI=zI("".split);Zd.exports=YI(function(){return!Jo("z").propertyIsEnumerable(0)})?function(a){return KI(a)==="String"?XI(a,""):Jo(a)}:Jo});var Vr=m((z0,tp)=>{"use strict";tp.exports=function(a){return a==null}});var Ft=m((Y0,ip)=>{"use strict";var JI=Vr(),ZI=TypeError;ip.exports=function(a){if(JI(a))throw new ZI("Can't call method on "+a);return a}});var ai=m((K0,rp)=>{"use strict";var eE=ep(),tE=Ft();rp.exports=function(a){return eE(tE(a))}});var Re=m((X0,ap)=>{"use strict";var iE=ae();ap.exports=function(a){return typeof a=="object"?a!==null:iE(a)}});var si=m((J0,sp)=>{"use strict";sp.exports={}});var wt=m((Z0,op)=>{"use strict";var Zo=si(),eu=re(),rE=ae(),np=function(a){return rE(a)?a:void 0};op.exports=function(a,e){return arguments.length<2?np(Zo[a])||np(eu[a]):Zo[a]&&Zo[a][e]||eu[a]&&eu[a][e]}});var _r=m((eV,up)=>{"use strict";var aE=ce();up.exports=aE({}.isPrototypeOf)});var ni=m((tV,dp)=>{"use strict";var sE=re(),lp=sE.navigator,cp=lp&&lp.userAgent;dp.exports=cp?String(cp):""});var iu=m((iV,gp)=>{"use strict";var bp=re(),tu=ni(),pp=bp.process,hp=bp.Deno,fp=pp&&pp.versions||hp&&hp.version,mp=fp&&fp.v8,et,Ds;mp&&(et=mp.split("."),Ds=et[0]>0&&et[0]<4?1:+(et[0]+et[1]));!Ds&&tu&&(et=tu.match(/Edge\/(\d+)/),(!et||et[1]>=74)&&(et=tu.match(/Chrome\/(\d+)/),et&&(Ds=+et[1])));gp.exports=Ds});var ru=m((rV,vp)=>{"use strict";var Sp=iu(),nE=le(),oE=re(),uE=oE.String;vp.exports=!!Object.getOwnPropertySymbols&&!nE(function(){var a=Symbol("symbol detection");return!uE(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Sp&&Sp<41})});var au=m((aV,yp)=>{"use strict";var lE=ru();yp.exports=lE&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var su=m((sV,Tp)=>{"use strict";var cE=wt(),dE=ae(),pE=_r(),hE=au(),fE=Object;Tp.exports=hE?function(a){return typeof a=="symbol"}:function(a){var e=cE("Symbol");return dE(e)&&pE(e.prototype,fE(a))}});var Or=m((nV,Ip)=>{"use strict";var mE=String;Ip.exports=function(a){try{return mE(a)}catch{return"Object"}}});var ht=m((oV,Ep)=>{"use strict";var bE=ae(),gE=Or(),SE=TypeError;Ep.exports=function(a){if(bE(a))return a;throw new SE(gE(a)+" is not a function")}});var Fr=m((uV,xp)=>{"use strict";var vE=ht(),yE=Vr();xp.exports=function(a,e){var t=a[e];return yE(t)?void 0:vE(t)}});var Ap=m((lV,wp)=>{"use strict";var nu=Fe(),ou=ae(),uu=Re(),TE=TypeError;wp.exports=function(a,e){var t,i;if(e==="string"&&ou(t=a.toString)&&!uu(i=nu(t,a))||ou(t=a.valueOf)&&!uu(i=nu(t,a))||e!=="string"&&ou(t=a.toString)&&!uu(i=nu(t,a)))return i;throw new TE("Can't convert object to primitive value")}});var tt=m((cV,kp)=>{"use strict";kp.exports=!0});var Lp=m((dV,Rp)=>{"use strict";var Pp=re(),IE=Object.defineProperty;Rp.exports=function(a,e){try{IE(Pp,a,{value:e,configurable:!0,writable:!0})}catch{Pp[a]=e}return e}});var Nr=m((pV,Dp)=>{"use strict";var EE=tt(),xE=re(),wE=Lp(),$p="__core-js_shared__",Mp=Dp.exports=xE[$p]||wE($p,{});(Mp.versions||(Mp.versions=[])).push({version:"3.43.0",mode:EE?"pure":"global",copyright:"\xA9 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var lu=m((hV,Bp)=>{"use strict";var Cp=Nr();Bp.exports=function(a,e){return Cp[a]||(Cp[a]=e||{})}});var Vi=m((fV,Vp)=>{"use strict";var AE=Ft(),kE=Object;Vp.exports=function(a){return kE(AE(a))}});var it=m((mV,_p)=>{"use strict";var PE=ce(),RE=Vi(),LE=PE({}.hasOwnProperty);_p.exports=Object.hasOwn||function(e,t){return LE(RE(e),t)}});var cu=m((bV,Op)=>{"use strict";var $E=ce(),ME=0,DE=Math.random(),CE=$E(1.1.toString);Op.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+CE(++ME+DE,36)}});var be=m((gV,Np)=>{"use strict";var BE=re(),VE=lu(),Fp=it(),_E=cu(),OE=ru(),FE=au(),_i=BE.Symbol,du=VE("wks"),NE=FE?_i.for||_i:_i&&_i.withoutSetter||_E;Np.exports=function(a){return Fp(du,a)||(du[a]=OE&&Fp(_i,a)?_i[a]:NE("Symbol."+a)),du[a]}});var jp=m((SV,Hp)=>{"use strict";var UE=Fe(),Up=Re(),qp=su(),qE=Fr(),HE=Ap(),jE=be(),QE=TypeError,GE=jE("toPrimitive");Hp.exports=function(a,e){if(!Up(a)||qp(a))return a;var t=qE(a,GE),i;if(t){if(e===void 0&&(e="default"),i=UE(t,a,e),!Up(i)||qp(i))return i;throw new QE("Can't convert object to primitive value")}return e===void 0&&(e="number"),HE(a,e)}});var pu=m((vV,Qp)=>{"use strict";var WE=jp(),zE=su();Qp.exports=function(a){var e=WE(a,"string");return zE(e)?e:e+""}});var Cs=m((yV,Wp)=>{"use strict";var YE=re(),Gp=Re(),hu=YE.document,KE=Gp(hu)&&Gp(hu.createElement);Wp.exports=function(a){return KE?hu.createElement(a):{}}});var fu=m((TV,zp)=>{"use strict";var XE=Oe(),JE=le(),ZE=Cs();zp.exports=!XE&&!JE(function(){return Object.defineProperty(ZE("div"),"a",{get:function(){return 7}}).a!==7})});var Xp=m(Kp=>{"use strict";var ex=Oe(),tx=Fe(),ix=Xo(),rx=Br(),ax=ai(),sx=pu(),nx=it(),ox=fu(),Yp=Object.getOwnPropertyDescriptor;Kp.f=ex?Yp:function(e,t){if(e=ax(e),t=sx(t),ox)try{return Yp(e,t)}catch{}if(nx(e,t))return rx(!tx(ix.f,e,t),e[t])}});var mu=m((EV,Jp)=>{"use strict";var ux=le(),lx=ae(),cx=/#|\.prototype\./,Ur=function(a,e){var t=px[dx(a)];return t===fx?!0:t===hx?!1:lx(e)?ux(e):!!e},dx=Ur.normalize=function(a){return String(a).replace(cx,".").toLowerCase()},px=Ur.data={},hx=Ur.NATIVE="N",fx=Ur.POLYFILL="P";Jp.exports=Ur});var Oi=m((xV,eh)=>{"use strict";var Zp=Yo(),mx=ht(),bx=Cr(),gx=Zp(Zp.bind);eh.exports=function(a,e){return mx(a),e===void 0?a:bx?gx(a,e):function(){return a.apply(e,arguments)}}});var bu=m((wV,th)=>{"use strict";var Sx=Oe(),vx=le();th.exports=Sx&&vx(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ft=m((AV,ih)=>{"use strict";var yx=Re(),Tx=String,Ix=TypeError;ih.exports=function(a){if(yx(a))return a;throw new Ix(Tx(a)+" is not an object")}});var oi=m(ah=>{"use strict";var Ex=Oe(),xx=fu(),wx=bu(),Bs=ft(),rh=pu(),Ax=TypeError,gu=Object.defineProperty,kx=Object.getOwnPropertyDescriptor,Su="enumerable",vu="configurable",yu="writable";ah.f=Ex?wx?function(e,t,i){if(Bs(e),t=rh(t),Bs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&yu in i&&!i[yu]){var r=kx(e,t);r&&r[yu]&&(e[t]=i.value,i={configurable:vu in i?i[vu]:r[vu],enumerable:Su in i?i[Su]:r[Su],writable:!1})}return gu(e,t,i)}:gu:function(e,t,i){if(Bs(e),t=rh(t),Bs(i),xx)try{return gu(e,t,i)}catch{}if("get"in i||"set"in i)throw new Ax("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Fi=m((PV,sh)=>{"use strict";var Px=Oe(),Rx=oi(),Lx=Br();sh.exports=Px?function(a,e,t){return Rx.f(a,e,Lx(1,t))}:function(a,e,t){return a[e]=t,a}});var ne=m((RV,oh)=>{"use strict";var qr=re(),$x=Wo(),Mx=Yo(),Dx=ae(),Cx=Xp().f,Bx=mu(),Ni=si(),Vx=Oi(),Ui=Fi(),nh=it();Nr();var _x=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 $x(a,this,arguments)};return e.prototype=a.prototype,e};oh.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?qr:r?qr[t]:qr[t]&&qr[t].prototype,u=i?Ni:Ni[t]||Ui(Ni,t,{})[t],o=u.prototype,l,c,p,d,h,f,b,g,S;for(d in e)l=Bx(i?d:t+(r?".":"#")+d,a.forced),c=!l&&n&&nh(n,d),f=u[d],c&&(a.dontCallGetSet?(S=Cx(n,d),b=S&&S.value):b=n[d]),h=c&&b?b:e[d],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=Vx(h,qr):a.wrap&&c?g=_x(h):s&&Dx(h)?g=Mx(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Ui(g,"sham",!0),Ui(u,d,g),s&&(p=t+"Prototype",nh(Ni,p)||Ui(Ni,p,{}),Ui(Ni[p],d,h),a.real&&o&&(l||!o[d])&&Ui(o,d,h)))}});var lh=m((LV,uh)=>{"use strict";var Ox=Math.ceil,Fx=Math.floor;uh.exports=Math.trunc||function(e){var t=+e;return(t>0?Fx:Ox)(t)}});var Hr=m(($V,ch)=>{"use strict";var Nx=lh();ch.exports=function(a){var e=+a;return e!==e||e===0?0:Nx(e)}});var ph=m((MV,dh)=>{"use strict";var Ux=Hr(),qx=Math.max,Hx=Math.min;dh.exports=function(a,e){var t=Ux(a);return t<0?qx(t+e,0):Hx(t,e)}});var Tu=m((DV,hh)=>{"use strict";var jx=Hr(),Qx=Math.min;hh.exports=function(a){var e=jx(a);return e>0?Qx(e,9007199254740991):0}});var qi=m((CV,fh)=>{"use strict";var Gx=Tu();fh.exports=function(a){return Gx(a.length)}});var Iu=m((BV,bh)=>{"use strict";var Wx=ai(),zx=ph(),Yx=qi(),mh=function(a){return function(e,t,i){var r=Wx(e),s=Yx(r);if(s===0)return!a&&-1;var n=zx(i,s),u;if(a&&t!==t){for(;s>n;)if(u=r[n++],u!==u)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};bh.exports={includes:mh(!0),indexOf:mh(!1)}});var jr=m((VV,gh)=>{"use strict";gh.exports=function(){}});var Sh=m(()=>{"use strict";var Kx=ne(),Xx=Iu().includes,Jx=le(),Zx=jr(),ew=Jx(function(){return!Array(1).includes()});Kx({target:"Array",proto:!0,forced:ew},{includes:function(e){return Xx(this,e,arguments.length>1?arguments[1]:void 0)}});Zx("includes")});var Nt=m((FV,vh)=>{"use strict";var tw=wt();vh.exports=tw});var Th=m((NV,yh)=>{"use strict";Sh();var iw=Nt();yh.exports=iw("Array","includes")});var Eh=m((UV,Ih)=>{"use strict";var rw=Th();Ih.exports=rw});var We=m((qV,xh)=>{"use strict";var aw=Eh();xh.exports=aw});var Os=m((e_,Mh)=>{"use strict";var pw=lu(),hw=cu(),$h=pw("keys");Mh.exports=function(a){return $h[a]||($h[a]=hw(a))}});var Ch=m((t_,Dh)=>{"use strict";var fw=le();Dh.exports=!fw(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Fs=m((i_,Vh)=>{"use strict";var mw=it(),bw=ae(),gw=Vi(),Sw=Os(),vw=Ch(),Bh=Sw("IE_PROTO"),wu=Object,yw=wu.prototype;Vh.exports=vw?wu.getPrototypeOf:function(a){var e=gw(a);if(mw(e,Bh))return e[Bh];var t=e.constructor;return bw(t)&&e instanceof t?t.prototype:e instanceof wu?yw:null}});var Ns=m((r_,_h)=>{"use strict";_h.exports={}});var Nh=m((a_,Fh)=>{"use strict";var Tw=ce(),Au=it(),Iw=ai(),Ew=Iu().indexOf,xw=Ns(),Oh=Tw([].push);Fh.exports=function(a,e){var t=Iw(a),i=0,r=[],s;for(s in t)!Au(xw,s)&&Au(t,s)&&Oh(r,s);for(;e.length>i;)Au(t,s=e[i++])&&(~Ew(r,s)||Oh(r,s));return r}});var ku=m((s_,Uh)=>{"use strict";Uh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Pu=m((n_,qh)=>{"use strict";var ww=Nh(),Aw=ku();qh.exports=Object.keys||function(e){return ww(e,Aw)}});var Ru=m((o_,Wh)=>{"use strict";var jh=Oe(),kw=le(),Qh=ce(),Pw=Fs(),Rw=Pu(),Lw=ai(),$w=Xo().f,Gh=Qh($w),Mw=Qh([].push),Dw=jh&&kw(function(){var a=Object.create(null);return a[2]=2,!Gh(a,2)}),Hh=function(a){return function(e){for(var t=Lw(e),i=Rw(t),r=Dw&&Pw(t)===null,s=i.length,n=0,u=[],o;s>n;)o=i[n++],(!jh||(r?o in t:Gh(t,o)))&&Mw(u,a?[o,t[o]]:t[o]);return u}};Wh.exports={entries:Hh(!0),values:Hh(!1)}});var zh=m(()=>{"use strict";var Cw=ne(),Bw=Ru().entries;Cw({target:"Object",stat:!0},{entries:function(e){return Bw(e)}})});var Kh=m((c_,Yh)=>{"use strict";zh();var Vw=si();Yh.exports=Vw.Object.entries});var Jh=m((d_,Xh)=>{"use strict";var _w=Kh();Xh.exports=_w});var Hi=m((p_,Zh)=>{"use strict";var Ow=Jh();Zh.exports=Ow});var ui=m((h_,ef)=>{"use strict";ef.exports={}});var af=m((f_,rf)=>{"use strict";var Fw=re(),Nw=ae(),tf=Fw.WeakMap;rf.exports=Nw(tf)&&/native code/.test(String(tf))});var Du=m((m_,of)=>{"use strict";var Uw=af(),nf=re(),qw=Re(),Hw=Fi(),Lu=it(),$u=Nr(),jw=Os(),Qw=Ns(),sf="Object already initialized",Mu=nf.TypeError,Gw=nf.WeakMap,Us,Qr,qs,Ww=function(a){return qs(a)?Qr(a):Us(a,{})},zw=function(a){return function(e){var t;if(!qw(e)||(t=Qr(e)).type!==a)throw new Mu("Incompatible receiver, "+a+" required");return t}};Uw||$u.state?(rt=$u.state||($u.state=new Gw),rt.get=rt.get,rt.has=rt.has,rt.set=rt.set,Us=function(a,e){if(rt.has(a))throw new Mu(sf);return e.facade=a,rt.set(a,e),e},Qr=function(a){return rt.get(a)||{}},qs=function(a){return rt.has(a)}):(li=jw("state"),Qw[li]=!0,Us=function(a,e){if(Lu(a,li))throw new Mu(sf);return e.facade=a,Hw(a,li,e),e},Qr=function(a){return Lu(a,li)?a[li]:{}},qs=function(a){return Lu(a,li)});var rt,li;of.exports={set:Us,get:Qr,has:qs,enforce:Ww,getterFor:zw}});var Vu=m((b_,lf)=>{"use strict";var Cu=Oe(),Yw=it(),uf=Function.prototype,Kw=Cu&&Object.getOwnPropertyDescriptor,Bu=Yw(uf,"name"),Xw=Bu&&function(){}.name==="something",Jw=Bu&&(!Cu||Cu&&Kw(uf,"name").configurable);lf.exports={EXISTS:Bu,PROPER:Xw,CONFIGURABLE:Jw}});var df=m(cf=>{"use strict";var Zw=Oe(),eA=bu(),tA=oi(),iA=ft(),rA=ai(),aA=Pu();cf.f=Zw&&!eA?Object.defineProperties:function(e,t){iA(e);for(var i=rA(t),r=aA(t),s=r.length,n=0,u;s>n;)tA.f(e,u=r[n++],i[u]);return e}});var _u=m((S_,pf)=>{"use strict";var sA=wt();pf.exports=sA("document","documentElement")});var Uu=m((v_,vf)=>{"use strict";var nA=ft(),oA=df(),hf=ku(),uA=Ns(),lA=_u(),cA=Cs(),dA=Os(),ff=">",mf="<",Fu="prototype",Nu="script",gf=dA("IE_PROTO"),Ou=function(){},Sf=function(a){return mf+Nu+ff+a+mf+"/"+Nu+ff},bf=function(a){a.write(Sf("")),a.close();var e=a.parentWindow.Object;return a=null,e},pA=function(){var a=cA("iframe"),e="java"+Nu+":",t;return a.style.display="none",lA.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Sf("document.F=Object")),t.close(),t.F},Hs,js=function(){try{Hs=new ActiveXObject("htmlfile")}catch{}js=typeof document<"u"?document.domain&&Hs?bf(Hs):pA():bf(Hs);for(var a=hf.length;a--;)delete js[Fu][hf[a]];return js()};uA[gf]=!0;vf.exports=Object.create||function(e,t){var i;return e!==null?(Ou[Fu]=nA(e),i=new Ou,Ou[Fu]=null,i[gf]=e):i=js(),t===void 0?i:oA.f(i,t)}});var ji=m((y_,yf)=>{"use strict";var hA=Fi();yf.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:hA(a,e,t),a}});var Qu=m((T_,Ef)=>{"use strict";var fA=le(),mA=ae(),bA=Re(),gA=Uu(),Tf=Fs(),SA=ji(),vA=be(),yA=tt(),ju=vA("iterator"),If=!1,At,qu,Hu;[].keys&&(Hu=[].keys(),"next"in Hu?(qu=Tf(Tf(Hu)),qu!==Object.prototype&&(At=qu)):If=!0);var TA=!bA(At)||fA(function(){var a={};return At[ju].call(a)!==a});TA?At={}:yA&&(At=gA(At));mA(At[ju])||SA(At,ju,function(){return this});Ef.exports={IteratorPrototype:At,BUGGY_SAFARI_ITERATORS:If}});var Qs=m((I_,wf)=>{"use strict";var IA=be(),EA=IA("toStringTag"),xf={};xf[EA]="z";wf.exports=String(xf)==="[object z]"});var Gr=m((E_,Af)=>{"use strict";var xA=Qs(),wA=ae(),Gs=ri(),AA=be(),kA=AA("toStringTag"),PA=Object,RA=Gs(function(){return arguments}())==="Arguments",LA=function(a,e){try{return a[e]}catch{}};Af.exports=xA?Gs:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=LA(e=PA(a),kA))=="string"?t:RA?Gs(e):(i=Gs(e))==="Object"&&wA(e.callee)?"Arguments":i}});var Pf=m((x_,kf)=>{"use strict";var $A=Qs(),MA=Gr();kf.exports=$A?{}.toString:function(){return"[object "+MA(this)+"]"}});var Wr=m((w_,Lf)=>{"use strict";var DA=Qs(),CA=oi().f,BA=Fi(),VA=it(),_A=Pf(),OA=be(),Rf=OA("toStringTag");Lf.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(VA(r,Rf)||CA(r,Rf,{configurable:!0,value:e}),i&&!DA&&BA(r,"toString",_A))}});var Mf=m((A_,$f)=>{"use strict";var FA=Qu().IteratorPrototype,NA=Uu(),UA=Br(),qA=Wr(),HA=ui(),jA=function(){return this};$f.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=NA(FA,{next:UA(+!i,t)}),qA(a,r,!1,!0),HA[r]=jA,a}});var Cf=m((k_,Df)=>{"use strict";var QA=ce(),GA=ht();Df.exports=function(a,e,t){try{return QA(GA(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var Vf=m((P_,Bf)=>{"use strict";var WA=Re();Bf.exports=function(a){return WA(a)||a===null}});var Of=m((R_,_f)=>{"use strict";var zA=Vf(),YA=String,KA=TypeError;_f.exports=function(a){if(zA(a))return a;throw new KA("Can't set "+YA(a)+" as a prototype")}});var Gu=m((L_,Ff)=>{"use strict";var XA=Cf(),JA=Re(),ZA=Ft(),ek=Of();Ff.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=XA(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return ZA(r),ek(s),JA(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Kf=m(($_,Yf)=>{"use strict";var tk=ne(),ik=Fe(),Ws=tt(),Wf=Vu(),rk=ae(),ak=Mf(),Nf=Fs(),Uf=Gu(),sk=Wr(),nk=Fi(),Wu=ji(),ok=be(),qf=ui(),zf=Qu(),uk=Wf.PROPER,lk=Wf.CONFIGURABLE,Hf=zf.IteratorPrototype,zs=zf.BUGGY_SAFARI_ITERATORS,zr=ok("iterator"),jf="keys",Yr="values",Qf="entries",Gf=function(){return this};Yf.exports=function(a,e,t,i,r,s,n){ak(t,e,i);var u=function(S){if(S===r&&d)return d;if(!zs&&S&&S in c)return c[S];switch(S){case jf:return function(){return new t(this,S)};case Yr:return function(){return new t(this,S)};case Qf:return function(){return new t(this,S)}}return function(){return new t(this)}},o=e+" Iterator",l=!1,c=a.prototype,p=c[zr]||c["@@iterator"]||r&&c[r],d=!zs&&p||u(r),h=e==="Array"&&c.entries||p,f,b,g;if(h&&(f=Nf(h.call(new a)),f!==Object.prototype&&f.next&&(!Ws&&Nf(f)!==Hf&&(Uf?Uf(f,Hf):rk(f[zr])||Wu(f,zr,Gf)),sk(f,o,!0,!0),Ws&&(qf[o]=Gf))),uk&&r===Yr&&p&&p.name!==Yr&&(!Ws&&lk?nk(c,"name",Yr):(l=!0,d=function(){return ik(p,this)})),r)if(b={values:u(Yr),keys:s?d:u(jf),entries:u(Qf)},n)for(g in b)(zs||l||!(g in c))&&Wu(c,g,b[g]);else tk({target:e,proto:!0,forced:zs||l},b);return(!Ws||n)&&c[zr]!==d&&Wu(c,zr,d,{name:r}),qf[e]=d,b}});var Jf=m((M_,Xf)=>{"use strict";Xf.exports=function(a,e){return{value:a,done:e}}});var Yu=m((D_,rm)=>{"use strict";var ck=ai(),zu=jr(),Zf=ui(),tm=Du(),dk=oi().f,pk=Kf(),Ys=Jf(),hk=tt(),fk=Oe(),im="Array Iterator",mk=tm.set,bk=tm.getterFor(im);rm.exports=pk(Array,"Array",function(a,e){mk(this,{type:im,target:ck(a),index:0,kind:e})},function(){var a=bk(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,Ys(void 0,!0);switch(a.kind){case"keys":return Ys(t,!1);case"values":return Ys(e[t],!1)}return Ys([t,e[t]],!1)},"values");var em=Zf.Arguments=Zf.Array;zu("keys");zu("values");zu("entries");if(!hk&&fk&&em.name!=="values")try{dk(em,"name",{value:"values"})}catch{}});var sm=m((C_,am)=>{"use strict";var gk=be(),Sk=ui(),vk=gk("iterator"),yk=Array.prototype;am.exports=function(a){return a!==void 0&&(Sk.Array===a||yk[vk]===a)}});var Ku=m((B_,om)=>{"use strict";var Tk=Gr(),nm=Fr(),Ik=Vr(),Ek=ui(),xk=be(),wk=xk("iterator");om.exports=function(a){if(!Ik(a))return nm(a,wk)||nm(a,"@@iterator")||Ek[Tk(a)]}});var lm=m((V_,um)=>{"use strict";var Ak=Fe(),kk=ht(),Pk=ft(),Rk=Or(),Lk=Ku(),$k=TypeError;um.exports=function(a,e){var t=arguments.length<2?Lk(a):e;if(kk(t))return Pk(Ak(t,a));throw new $k(Rk(a)+" is not iterable")}});var pm=m((__,dm)=>{"use strict";var Mk=Fe(),cm=ft(),Dk=Fr();dm.exports=function(a,e,t){var i,r;cm(a);try{if(i=Dk(a,"return"),!i){if(e==="throw")throw t;return t}i=Mk(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return cm(i),t}});var Xs=m((O_,bm)=>{"use strict";var Ck=Oi(),Bk=Fe(),Vk=ft(),_k=Or(),Ok=sm(),Fk=qi(),hm=_r(),Nk=lm(),Uk=Ku(),fm=pm(),qk=TypeError,Ks=function(a,e){this.stopped=a,this.result=e},mm=Ks.prototype;bm.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),u=!!(t&&t.INTERRUPTED),o=Ck(e,i),l,c,p,d,h,f,b,g=function(I){return l&&fm(l,"normal"),new Ks(!0,I)},S=function(I){return r?(Vk(I),u?o(I[0],I[1],g):o(I[0],I[1])):u?o(I,g):o(I)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Uk(a),!c)throw new qk(_k(a)+" is not iterable");if(Ok(c)){for(p=0,d=Fk(a);d>p;p++)if(h=S(a[p]),h&&hm(mm,h))return h;return new Ks(!1)}l=Nk(a,c)}for(f=s?a.next:l.next;!(b=Bk(f,l)).done;){try{h=S(b.value)}catch(I){fm(l,"throw",I)}if(typeof h=="object"&&h&&hm(mm,h))return h}return new Ks(!1)}});var Sm=m((F_,gm)=>{"use strict";var Hk=Oe(),jk=oi(),Qk=Br();gm.exports=function(a,e,t){Hk?jk.f(a,e,Qk(0,t)):a[e]=t}});var vm=m(()=>{"use strict";var Gk=ne(),Wk=Xs(),zk=Sm();Gk({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Wk(e,function(i,r){zk(t,i,r)},{AS_ENTRIES:!0}),t}})});var Tm=m((q_,ym)=>{"use strict";Yu();vm();var Yk=si();ym.exports=Yk.Object.fromEntries});var Em=m((H_,Im)=>{"use strict";Im.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 wm=m(()=>{"use strict";Yu();var Kk=Em(),Xk=re(),Jk=Wr(),xm=ui();for(Js in Kk)Jk(Xk[Js],Js),xm[Js]=xm.Array;var Js});var km=m((G_,Am)=>{"use strict";var Zk=Tm();wm();Am.exports=Zk});var Xu=m((W_,Pm)=>{"use strict";var eP=km();Pm.exports=eP});var Rm=m(()=>{"use strict"});var Ju=m((K_,Lm)=>{"use strict";var Kr=re(),tP=ni(),iP=ri(),Zs=function(a){return tP.slice(0,a.length)===a};Lm.exports=function(){return Zs("Bun/")?"BUN":Zs("Cloudflare-Workers")?"CLOUDFLARE":Zs("Deno/")?"DENO":Zs("Node.js/")?"NODE":Kr.Bun&&typeof Bun.version=="string"?"BUN":Kr.Deno&&typeof Deno.version=="object"?"DENO":iP(Kr.process)==="process"?"NODE":Kr.window&&Kr.document?"BROWSER":"REST"}()});var en=m((X_,$m)=>{"use strict";var rP=Ju();$m.exports=rP==="NODE"});var Dm=m((J_,Mm)=>{"use strict";var aP=oi();Mm.exports=function(a,e,t){return aP.f(a,e,t)}});var Vm=m((Z_,Bm)=>{"use strict";var sP=wt(),nP=Dm(),oP=be(),uP=Oe(),Cm=oP("species");Bm.exports=function(a){var e=sP(a);uP&&e&&!e[Cm]&&nP(e,Cm,{configurable:!0,get:function(){return this}})}});var Om=m((eO,_m)=>{"use strict";var lP=_r(),cP=TypeError;_m.exports=function(a,e){if(lP(e,a))return a;throw new cP("Incorrect invocation")}});var el=m((tO,Fm)=>{"use strict";var dP=ce(),pP=ae(),Zu=Nr(),hP=dP(Function.toString);pP(Zu.inspectSource)||(Zu.inspectSource=function(a){return hP(a)});Fm.exports=Zu.inspectSource});var il=m((iO,jm)=>{"use strict";var fP=ce(),mP=le(),Nm=ae(),bP=Gr(),gP=wt(),SP=el(),Um=function(){},qm=gP("Reflect","construct"),tl=/^\s*(?:class|function)\b/,vP=fP(tl.exec),yP=!tl.test(Um),Xr=function(e){if(!Nm(e))return!1;try{return qm(Um,[],e),!0}catch{return!1}},Hm=function(e){if(!Nm(e))return!1;switch(bP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return yP||!!vP(tl,SP(e))}catch{return!0}};Hm.sham=!0;jm.exports=!qm||mP(function(){var a;return Xr(Xr.call)||!Xr(Object)||!Xr(function(){a=!0})||a})?Hm:Xr});var Gm=m((rO,Qm)=>{"use strict";var TP=il(),IP=Or(),EP=TypeError;Qm.exports=function(a){if(TP(a))return a;throw new EP(IP(a)+" is not a constructor")}});var rl=m((aO,zm)=>{"use strict";var Wm=ft(),xP=Gm(),wP=Vr(),AP=be(),kP=AP("species");zm.exports=function(a,e){var t=Wm(a).constructor,i;return t===void 0||wP(i=Wm(t)[kP])?e:xP(i)}});var Km=m((sO,Ym)=>{"use strict";var PP=ce();Ym.exports=PP([].slice)});var Jm=m((nO,Xm)=>{"use strict";var RP=TypeError;Xm.exports=function(a,e){if(a<e)throw new RP("Not enough arguments");return a}});var al=m((oO,Zm)=>{"use strict";var LP=ni();Zm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(LP)});var hl=m((uO,ub)=>{"use strict";var Ne=re(),$P=Wo(),MP=Oi(),eb=ae(),DP=it(),ob=le(),tb=_u(),CP=Km(),ib=Cs(),BP=Jm(),VP=al(),_P=en(),cl=Ne.setImmediate,dl=Ne.clearImmediate,OP=Ne.process,sl=Ne.Dispatch,FP=Ne.Function,rb=Ne.MessageChannel,NP=Ne.String,nl=0,Jr={},ab="onreadystatechange",Zr,ci,ol,ul;ob(function(){Zr=Ne.location});var pl=function(a){if(DP(Jr,a)){var e=Jr[a];delete Jr[a],e()}},ll=function(a){return function(){pl(a)}},sb=function(a){pl(a.data)},nb=function(a){Ne.postMessage(NP(a),Zr.protocol+"//"+Zr.host)};(!cl||!dl)&&(cl=function(e){BP(arguments.length,1);var t=eb(e)?e:FP(e),i=CP(arguments,1);return Jr[++nl]=function(){$P(t,void 0,i)},ci(nl),nl},dl=function(e){delete Jr[e]},_P?ci=function(a){OP.nextTick(ll(a))}:sl&&sl.now?ci=function(a){sl.now(ll(a))}:rb&&!VP?(ol=new rb,ul=ol.port2,ol.port1.onmessage=sb,ci=MP(ul.postMessage,ul)):Ne.addEventListener&&eb(Ne.postMessage)&&!Ne.importScripts&&Zr&&Zr.protocol!=="file:"&&!ob(nb)?(ci=nb,Ne.addEventListener("message",sb,!1)):ab in ib("script")?ci=function(a){tb.appendChild(ib("script"))[ab]=function(){tb.removeChild(this),pl(a)}}:ci=function(a){setTimeout(ll(a),0)});ub.exports={set:cl,clear:dl}});var db=m((lO,cb)=>{"use strict";var lb=re(),UP=Oe(),qP=Object.getOwnPropertyDescriptor;cb.exports=function(a){if(!UP)return lb[a];var e=qP(lb,a);return e&&e.value}});var fl=m((cO,hb)=>{"use strict";var pb=function(){this.head=null,this.tail=null};pb.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}}};hb.exports=pb});var mb=m((dO,fb)=>{"use strict";var HP=ni();fb.exports=/ipad|iphone|ipod/i.test(HP)&&typeof Pebble<"u"});var gb=m((pO,bb)=>{"use strict";var jP=ni();bb.exports=/web0s(?!.*chrome)/i.test(jP)});var xb=m((hO,Eb)=>{"use strict";var Gi=re(),QP=db(),Sb=Oi(),ml=hl().set,GP=fl(),WP=al(),zP=mb(),YP=gb(),bl=en(),vb=Gi.MutationObserver||Gi.WebKitMutationObserver,yb=Gi.document,Tb=Gi.process,tn=Gi.Promise,vl=QP("queueMicrotask"),Qi,gl,Sl,rn,Ib;vl||(ea=new GP,ta=function(){var a,e;for(bl&&(a=Tb.domain)&&a.exit();e=ea.get();)try{e()}catch(t){throw ea.head&&Qi(),t}a&&a.enter()},!WP&&!bl&&!YP&&vb&&yb?(gl=!0,Sl=yb.createTextNode(""),new vb(ta).observe(Sl,{characterData:!0}),Qi=function(){Sl.data=gl=!gl}):!zP&&tn&&tn.resolve?(rn=tn.resolve(void 0),rn.constructor=tn,Ib=Sb(rn.then,rn),Qi=function(){Ib(ta)}):bl?Qi=function(){Tb.nextTick(ta)}:(ml=Sb(ml,Gi),Qi=function(){ml(ta)}),vl=function(a){ea.head||Qi(),ea.add(a)});var ea,ta;Eb.exports=vl});var Ab=m((fO,wb)=>{"use strict";wb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var an=m((mO,kb)=>{"use strict";kb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var di=m((bO,Pb)=>{"use strict";var KP=re();Pb.exports=KP.Promise});var Wi=m((gO,Mb)=>{"use strict";var XP=re(),ia=di(),JP=ae(),ZP=mu(),eR=el(),tR=be(),Rb=Ju(),iR=tt(),yl=iu(),Lb=ia&&ia.prototype,rR=tR("species"),Tl=!1,$b=JP(XP.PromiseRejectionEvent),aR=ZP("Promise",function(){var a=eR(ia),e=a!==String(ia);if(!e&&yl===66||iR&&!(Lb.catch&&Lb.finally))return!0;if(!yl||yl<51||!/native code/.test(a)){var t=new ia(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[rR]=i,Tl=t.then(function(){})instanceof i,!Tl)return!0}return!e&&(Rb==="BROWSER"||Rb==="DENO")&&!$b});Mb.exports={CONSTRUCTOR:aR,REJECTION_EVENT:$b,SUBCLASSING:Tl}});var zi=m((SO,Cb)=>{"use strict";var Db=ht(),sR=TypeError,nR=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new sR("Bad Promise constructor");e=i,t=r}),this.resolve=Db(e),this.reject=Db(t)};Cb.exports.f=function(a){return new nR(a)}});var eg=m(()=>{"use strict";var oR=ne(),uR=tt(),un=en(),Ut=re(),lR=si(),Ji=Fe(),Bb=ji(),Vb=Gu(),cR=Wr(),dR=Vm(),pR=ht(),on=ae(),hR=Re(),fR=Om(),mR=rl(),Ub=hl().set,Al=xb(),bR=Ab(),gR=an(),SR=fl(),qb=Du(),ln=di(),kl=Wi(),Hb=zi(),cn="Promise",jb=kl.CONSTRUCTOR,vR=kl.REJECTION_EVENT,yR=kl.SUBCLASSING,Il=qb.getterFor(cn),TR=qb.set,Yi=ln&&ln.prototype,pi=ln,sn=Yi,Qb=Ut.TypeError,El=Ut.document,Pl=Ut.process,xl=Hb.f,IR=xl,ER=!!(El&&El.createEvent&&Ut.dispatchEvent),Gb="unhandledrejection",xR="rejectionhandled",_b=0,Wb=1,wR=2,Rl=1,zb=2,nn,Ob,Yb,Fb,Kb=function(a){var e;return hR(a)&&on(e=a.then)?e:!1},Xb=function(a,e){var t=e.value,i=e.state===Wb,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,u=a.domain,o,l,c;try{r?(i||(e.rejection===zb&&kR(e),e.rejection=Rl),r===!0?o=t:(u&&u.enter(),o=r(t),u&&(u.exit(),c=!0)),o===a.promise?n(new Qb("Promise-chain cycle")):(l=Kb(o))?Ji(l,o,s,n):s(o)):n(t)}catch(p){u&&!c&&u.exit(),n(p)}},Jb=function(a,e){a.notified||(a.notified=!0,Al(function(){for(var t=a.reactions,i;i=t.get();)Xb(i,a);a.notified=!1,e&&!a.rejection&&AR(a)}))},Zb=function(a,e,t){var i,r;ER?(i=El.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Ut.dispatchEvent(i)):i={promise:e,reason:t},!vR&&(r=Ut["on"+a])?r(i):a===Gb&&bR("Unhandled promise rejection",t)},AR=function(a){Ji(Ub,Ut,function(){var e=a.facade,t=a.value,i=Nb(a),r;if(i&&(r=gR(function(){un?Pl.emit("unhandledRejection",t,e):Zb(Gb,e,t)}),a.rejection=un||Nb(a)?zb:Rl,r.error))throw r.value})},Nb=function(a){return a.rejection!==Rl&&!a.parent},kR=function(a){Ji(Ub,Ut,function(){var e=a.facade;un?Pl.emit("rejectionHandled",e):Zb(xR,e,a.value)})},Ki=function(a,e,t){return function(i){a(e,i,t)}},Xi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=wR,Jb(a,!0))},wl=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Qb("Promise can't be resolved itself");var i=Kb(e);i?Al(function(){var r={done:!1};try{Ji(i,e,Ki(wl,r,a),Ki(Xi,r,a))}catch(s){Xi(r,s,a)}}):(a.value=e,a.state=Wb,Jb(a,!1))}catch(r){Xi({done:!1},r,a)}}};if(jb&&(pi=function(e){fR(this,sn),pR(e),Ji(nn,this);var t=Il(this);try{e(Ki(wl,t),Ki(Xi,t))}catch(i){Xi(t,i)}},sn=pi.prototype,nn=function(e){TR(this,{type:cn,done:!1,notified:!1,parent:!1,reactions:new SR,rejection:!1,state:_b,value:null})},nn.prototype=Bb(sn,"then",function(e,t){var i=Il(this),r=xl(mR(this,pi));return i.parent=!0,r.ok=on(e)?e:!0,r.fail=on(t)&&t,r.domain=un?Pl.domain:void 0,i.state===_b?i.reactions.add(r):Al(function(){Xb(r,i)}),r.promise}),Ob=function(){var a=new nn,e=Il(a);this.promise=a,this.resolve=Ki(wl,e),this.reject=Ki(Xi,e)},Hb.f=xl=function(a){return a===pi||a===Yb?new Ob(a):IR(a)},!uR&&on(ln)&&Yi!==Object.prototype)){Fb=Yi.then,yR||Bb(Yi,"then",function(e,t){var i=this;return new pi(function(r,s){Ji(Fb,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Yi.constructor}catch{}Vb&&Vb(Yi,sn)}oR({global:!0,constructor:!0,wrap:!0,forced:jb},{Promise:pi});Yb=lR.Promise;cR(pi,cn,!1,!0);dR(cn)});var sg=m((TO,ag)=>{"use strict";var PR=be(),ig=PR("iterator"),rg=!1;try{tg=0,Ll={next:function(){return{done:!!tg++}},return:function(){rg=!0}},Ll[ig]=function(){return this},Array.from(Ll,function(){throw 2})}catch{}var tg,Ll;ag.exports=function(a,e){try{if(!e&&!rg)return!1}catch{return!1}var t=!1;try{var i={};i[ig]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var $l=m((IO,ng)=>{"use strict";var RR=di(),LR=sg(),$R=Wi().CONSTRUCTOR;ng.exports=$R||!LR(function(a){RR.all(a).then(void 0,function(){})})});var og=m(()=>{"use strict";var MR=ne(),DR=Fe(),CR=ht(),BR=zi(),VR=an(),_R=Xs(),OR=$l();MR({target:"Promise",stat:!0,forced:OR},{all:function(e){var t=this,i=BR.f(t),r=i.resolve,s=i.reject,n=VR(function(){var u=CR(t.resolve),o=[],l=0,c=1;_R(e,function(p){var d=l++,h=!1;c++,DR(u,t,p).then(function(f){h||(h=!0,o[d]=f,--c||r(o))},s)}),--c||r(o)});return n.error&&s(n.value),i.promise}})});var lg=m(()=>{"use strict";var FR=ne(),NR=tt(),UR=Wi().CONSTRUCTOR,Dl=di(),qR=wt(),HR=ae(),jR=ji(),ug=Dl&&Dl.prototype;FR({target:"Promise",proto:!0,forced:UR,real:!0},{catch:function(a){return this.then(void 0,a)}});!NR&&HR(Dl)&&(Ml=qR("Promise").prototype.catch,ug.catch!==Ml&&jR(ug,"catch",Ml,{unsafe:!0}));var Ml});var cg=m(()=>{"use strict";var QR=ne(),GR=Fe(),WR=ht(),zR=zi(),YR=an(),KR=Xs(),XR=$l();QR({target:"Promise",stat:!0,forced:XR},{race:function(e){var t=this,i=zR.f(t),r=i.reject,s=YR(function(){var n=WR(t.resolve);KR(e,function(u){GR(n,t,u).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var dg=m(()=>{"use strict";var JR=ne(),ZR=zi(),eL=Wi().CONSTRUCTOR;JR({target:"Promise",stat:!0,forced:eL},{reject:function(e){var t=ZR.f(this),i=t.reject;return i(e),t.promise}})});var Cl=m(($O,pg)=>{"use strict";var tL=ft(),iL=Re(),rL=zi();pg.exports=function(a,e){if(tL(a),iL(e)&&e.constructor===a)return e;var t=rL.f(a),i=t.resolve;return i(e),t.promise}});var mg=m(()=>{"use strict";var aL=ne(),sL=wt(),hg=tt(),nL=di(),fg=Wi().CONSTRUCTOR,oL=Cl(),uL=sL("Promise"),lL=hg&&!fg;aL({target:"Promise",stat:!0,forced:hg||fg},{resolve:function(e){return oL(lL&&this===uL?nL:this,e)}})});var bg=m(()=>{"use strict";eg();og();lg();cg();dg();mg()});var yg=m(()=>{"use strict";var cL=ne(),dL=tt(),dn=di(),pL=le(),Sg=wt(),vg=ae(),hL=rl(),gg=Cl(),fL=ji(),Vl=dn&&dn.prototype,mL=!!dn&&pL(function(){Vl.finally.call({then:function(){}},function(){})});cL({target:"Promise",proto:!0,real:!0,forced:mL},{finally:function(a){var e=hL(this,Sg("Promise")),t=vg(a);return this.then(t?function(i){return gg(e,a()).then(function(){return i})}:a,t?function(i){return gg(e,a()).then(function(){throw i})}:a)}});!dL&&vg(dn)&&(Bl=Sg("Promise").prototype.finally,Vl.finally!==Bl&&fL(Vl,"finally",Bl,{unsafe:!0}));var Bl});var Ig=m((OO,Tg)=>{"use strict";Rm();bg();yg();var bL=Nt();Tg.exports=bL("Promise","finally")});var xg=m((FO,Eg)=>{"use strict";var gL=Ig();Eg.exports=gL});var pn=m((NO,wg)=>{"use strict";var SL=xg();wg.exports=SL});var Og=m(()=>{"use strict";var ML=ne(),DL=Ru().values;ML({target:"Object",stat:!0},{values:function(e){return DL(e)}})});var Ng=m((xF,Fg)=>{"use strict";Og();var CL=si();Fg.exports=CL.Object.values});var qg=m((wF,Ug)=>{"use strict";var BL=Ng();Ug.exports=BL});var er=m((AF,Hg)=>{"use strict";var VL=qg();Hg.exports=VL});var nS=m(()=>{"use strict";var s$=ne(),n$=Vi(),o$=qi(),u$=Hr(),l$=jr();s$({target:"Array",proto:!0},{at:function(e){var t=n$(this),i=o$(t),r=u$(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});l$("at")});var uS=m((BN,oS)=>{"use strict";nS();var c$=Nt();oS.exports=c$("Array","at")});var cS=m((VN,lS)=>{"use strict";var d$=uS();lS.exports=d$});var at=m((_N,dS)=>{"use strict";var p$=cS();dS.exports=p$});var sc=m((Pq,GS)=>{"use strict";var G$=ri();GS.exports=Array.isArray||function(e){return G$(e)==="Array"}});var zS=m((Rq,WS)=>{"use strict";var W$=TypeError,z$=9007199254740991;WS.exports=function(a){if(a>z$)throw W$("Maximum allowed index exceeded");return a}});var XS=m((Lq,KS)=>{"use strict";var Y$=sc(),K$=qi(),X$=zS(),J$=Oi(),YS=function(a,e,t,i,r,s,n,u){for(var o=r,l=0,c=n?J$(n,u):!1,p,d;l<i;)l in t&&(p=c?c(t[l],l,e):t[l],s>0&&Y$(p)?(d=K$(p),o=YS(a,e,p,d,o,s-1)-1):(X$(o+1),a[o]=p),o++),l++;return o};KS.exports=YS});var tv=m(($q,ev)=>{"use strict";var JS=sc(),Z$=il(),eM=Re(),tM=be(),iM=tM("species"),ZS=Array;ev.exports=function(a){var e;return JS(a)&&(e=a.constructor,Z$(e)&&(e===ZS||JS(e.prototype))?e=void 0:eM(e)&&(e=e[iM],e===null&&(e=void 0))),e===void 0?ZS:e}});var rv=m((Mq,iv)=>{"use strict";var rM=tv();iv.exports=function(a,e){return new(rM(a))(e===0?0:e)}});var av=m(()=>{"use strict";var aM=ne(),sM=XS(),nM=ht(),oM=Vi(),uM=qi(),lM=rv();aM({target:"Array",proto:!0},{flatMap:function(e){var t=oM(this),i=uM(t),r;return nM(e),r=lM(t,0),r.length=sM(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var sv=m(()=>{"use strict";var cM=jr();cM("flatMap")});var ov=m((_q,nv)=>{"use strict";av();sv();var dM=Nt();nv.exports=dM("Array","flatMap")});var lv=m((Oq,uv)=>{"use strict";var pM=ov();uv.exports=pM});var Sa=m((Fq,cv)=>{"use strict";var hM=lv();cv.exports=hM});var va=m((Nq,dv)=>{"use strict";var fM=Gr(),mM=String;dv.exports=function(a){if(fM(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return mM(a)}});var nc=m((Uq,pv)=>{"use strict";pv.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 mv=m((qq,fv)=>{"use strict";var bM=ce(),gM=Ft(),SM=va(),uc=nc(),hv=bM("".replace),vM=RegExp("^["+uc+"]+"),yM=RegExp("(^|[^"+uc+"])["+uc+"]+$"),oc=function(a){return function(e){var t=SM(gM(e));return a&1&&(t=hv(t,vM,"")),a&2&&(t=hv(t,yM,"$1")),t}};fv.exports={start:oc(1),end:oc(2),trim:oc(3)}});var vv=m((Hq,Sv)=>{"use strict";var TM=Vu().PROPER,IM=le(),bv=nc(),gv="\u200B\x85\u180E";Sv.exports=function(a){return IM(function(){return!!bv[a]()||gv[a]()!==gv||TM&&bv[a].name!==a})}});var lc=m((jq,yv)=>{"use strict";var EM=mv().start,xM=vv();yv.exports=xM("trimStart")?function(){return EM(this)}:"".trimStart});var Iv=m(()=>{"use strict";var wM=ne(),Tv=lc();wM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Tv},{trimLeft:Tv})});var xv=m(()=>{"use strict";Iv();var AM=ne(),Ev=lc();AM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Ev},{trimStart:Ev})});var Av=m((Yq,wv)=>{"use strict";xv();var kM=Nt();wv.exports=kM("String","trimLeft")});var Pv=m((Kq,kv)=>{"use strict";var PM=Av();kv.exports=PM});var Lv=m((Xq,Rv)=>{"use strict";var RM=Pv();Rv.exports=RM});var Gv=m(()=>{"use strict"});var Wv=m(()=>{"use strict"});var Yv=m((_j,zv)=>{"use strict";var ZM=Re(),eD=ri(),tD=be(),iD=tD("match");zv.exports=function(a){var e;return ZM(a)&&((e=a[iD])!==void 0?!!e:eD(a)==="RegExp")}});var Jv=m((Oj,Xv)=>{"use strict";var rD=re(),aD=le(),Kv=rD.RegExp,sD=!aD(function(){var a=!0;try{Kv(".","d")}catch{a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(o,l){Object.defineProperty(e,o,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var u=Object.getOwnPropertyDescriptor(Kv.prototype,"flags").get.call(e);return u!==i||t!==i});Xv.exports={correct:sD}});var ey=m((Fj,Zv)=>{"use strict";var nD=ft();Zv.exports=function(){var a=nD(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 ry=m((Nj,iy)=>{"use strict";var oD=Fe(),uD=it(),lD=_r(),ty=Jv(),cD=ey(),dD=RegExp.prototype;iy.exports=ty.correct?function(a){return a.flags}:function(a){return!ty.correct&&lD(dD,a)&&!uD(a,"flags")?oD(cD,a):a.flags}});var sy=m((Uj,ay)=>{"use strict";var fc=ce(),pD=Vi(),hD=Math.floor,pc=fc("".charAt),fD=fc("".replace),hc=fc("".slice),mD=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,bD=/\$([$&'`]|\d{1,2})/g;ay.exports=function(a,e,t,i,r,s){var n=t+a.length,u=i.length,o=bD;return r!==void 0&&(r=pD(r),o=mD),fD(s,o,function(l,c){var p;switch(pc(c,0)){case"$":return"$";case"&":return a;case"`":return hc(e,0,t);case"'":return hc(e,n);case"<":p=r[hc(c,1,-1)];break;default:var d=+c;if(d===0)return l;if(d>u){var h=hD(d/10);return h===0?l:h<=u?i[h-1]===void 0?pc(c,1):i[h-1]+pc(c,1):l}p=i[d-1]}return p===void 0?"":p})}});var uy=m(()=>{"use strict";var gD=ne(),SD=Fe(),bc=ce(),ny=Ft(),vD=ae(),yD=Re(),TD=Yv(),hr=va(),ID=Fr(),ED=ry(),xD=sy(),wD=be(),AD=tt(),kD=wD("replace"),PD=TypeError,mc=bc("".indexOf),RD=bc("".replace),oy=bc("".slice),LD=Math.max;gD({target:"String",proto:!0},{replaceAll:function(e,t){var i=ny(this),r,s,n,u,o,l,c,p,d,h,f=0,b="";if(yD(e)){if(r=TD(e),r&&(s=hr(ny(ED(e))),!~mc(s,"g")))throw new PD("`.replaceAll` does not allow non-global regexes");if(n=ID(e,kD),n)return SD(n,e,i,t);if(AD&&r)return RD(hr(i),e,t)}for(u=hr(i),o=hr(e),l=vD(t),l||(t=hr(t)),c=o.length,p=LD(1,c),d=mc(u,o);d!==-1;)h=l?hr(t(o,d,u)):xD(o,u,d,[],void 0,t),b+=oy(u,f,d)+h,f=d+c,d=d+p>u.length?-1:mc(u,o,d+p);return f<u.length&&(b+=oy(u,f)),b}})});var cy=m((jj,ly)=>{"use strict";Gv();Wv();uy();var $D=Nt();ly.exports=$D("String","replaceAll")});var py=m((Qj,dy)=>{"use strict";var MD=cy();dy.exports=MD});var fy=m((Gj,hy)=>{"use strict";var DD=py();hy.exports=DD});var by=m((Wj,my)=>{"use strict";var CD=Hr(),BD=va(),VD=Ft(),_D=RangeError;my.exports=function(e){var t=BD(VD(this)),i="",r=CD(e);if(r<0||r===1/0)throw new _D("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var Ty=m((zj,yy)=>{"use strict";var vy=ce(),OD=Tu(),gy=va(),FD=by(),ND=Ft(),UD=vy(FD),qD=vy("".slice),HD=Math.ceil,Sy=function(a){return function(e,t,i){var r=gy(ND(e)),s=OD(t),n=r.length,u=i===void 0?" ":gy(i),o,l;return s<=n||u===""?r:(o=s-n,l=UD(u,HD(o/u.length)),l.length>o&&(l=qD(l,0,o)),a?r+l:l+r)}};yy.exports={start:Sy(!1),end:Sy(!0)}});var Ey=m((Yj,Iy)=>{"use strict";var jD=ni();Iy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(jD)});var xy=m(()=>{"use strict";var QD=ne(),GD=Ty().start,WD=Ey();QD({target:"String",proto:!0,forced:WD},{padStart:function(e){return GD(this,e,arguments.length>1?arguments[1]:void 0)}})});var Ay=m((Jj,wy)=>{"use strict";xy();var zD=Nt();wy.exports=zD("String","padStart")});var Py=m((Zj,ky)=>{"use strict";var YD=Ay();ky.exports=YD});var Ly=m((eQ,Ry)=>{"use strict";var KD=Py();Ry.exports=KD});var Md="2.0.136-beta.0";var Pe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Pe||{}),xt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(xt||{});var Ls=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Ls||{}),jo=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(jo||{});var Qo=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Qo||{}),$s=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))($s||{});var kI=C(We(),1);import{assertNever as Lh,assertNonNullable as sw,isNonNullable as Vs,ValueSubject as Eu,Subject as nw,Subscription as ow,merge as uw,observableFrom as lw,fromEvent as Ah,map as kh,tap as Ph,filterChanged as cw,isNullable as xu,ErrorCategory as Rh}from"@vkontakte/videoplayer-shared";var wh=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var _s=class{constructor(e){this.connection$=new Eu(void 0);this.castState$=new Eu("NOT_AVAILABLE");this.errorEvent$=new nw;this.realCastState$=new Eu("NOT_AVAILABLE");this.subscription=new ow;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Vs(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||wh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Rh.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Vs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();xu(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();xu(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(Ah(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Lh(r.sessionState)}})).add(uw(Ah(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ph(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),kh(r=>r.castState)),lw([i.getCastState()])).pipe(cw(),kh(dw),Ph(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",n=Vs(this.connection$.getValue());if(s&&!n){let u=i.getCurrentSession();sw(u);let o=u.getCastDevice(),l=u.getMediaSession()?.media?.contentId;(xu(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:o}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Vs(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:Rh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},dw=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 Lh(a)}};var Id=C(We(),1),uI=C(Hi(),1),lI=C(Xu(),1);var Bg=C(pn(),1);import{assertNever as Ag}from"@vkontakte/videoplayer-shared";var se=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let 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:Ag(t)}return a},qt=(a,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:Ag(e)}};var k=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as vL,Subject as hn,merge as kg}from"@vkontakte/videoplayer-shared";var O=class{constructor(e){this.transitionStarted$=new hn;this.transitionEnded$=new hn;this.transitionUpdated$=new hn;this.forceChanged$=new hn;this.stateChangeStarted$=kg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=kg(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||vL(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}};import{assertNever as yL}from"@vkontakte/videoplayer-shared";var Pg=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 yL(a)}};import{assertNever as Zi,assertNonNullable as hi,debounce as Rg,ErrorCategory as Lg,fromEvent as fi,isNonNullable as $g,map as Mg,merge as Dg,observableFrom as TL,Subject as IL,Subscription as _l,timeout as EL,getHighestQuality as xL}from"@vkontakte/videoplayer-shared";var wL=5,AL=5,kL=500,Cg=7e3,ra=class{constructor(e){this.subscription=new _l;this.loadMediaTimeoutSubscription=new _l;this.videoState=new O("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Zi(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:Zi(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:Zi(e)}break}default:Zi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Pg(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new _l;this.subscription.add(e),this.subscription.add(Dg(this.videoState.stateChangeStarted$.pipe(Mg(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Mg(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 IL;e.add(r.pipe(Rg(kL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(fi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let u=n.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(u-s)>wL)&&r.next(u),s=u})),e.add(fi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(fi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(fi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(fi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,u=this.params.output.isBuffering$.getValue(),o=n===chrome.cast.media.PlayerState.BUFFERING;switch(u!==o&&this.params.output.isBuffering$.next(o),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<AL&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Zi(n)}}),t(fi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(fi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Dg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,TL(["init"])).pipe(Rg(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let l=t[e];hi(l);let c=xL(Object.keys(l));hi(c);let p=l[c];hi(p),i=p,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];hi(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];hi(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];hi(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];hi(l),i=se(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Lg.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Zi(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:u,subtitle:o}=this.params.meta;return $g(u)&&(n.metadata.title=u),$g(o)&&(n.metadata.subtitle=o),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(EL(Cg).subscribe(()=>s(`timeout(${Cg})`)))});(0,Bg.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:Lg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var rc=C(We(),1);import{clearVideoElement as _g}from"@vkontakte/videoplayer-shared";import{clearVideoElement as PL}from"@vkontakte/videoplayer-shared";var Vg=a=>{try{a.pause(),a.playbackRate=0,PL(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as RL,Subscription as LL}from"@vkontakte/videoplayer-shared";var Ol=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)}},Fl=window.WeakMap?new WeakMap:new Ol,Nl=window.WeakMap?new WeakMap:new Map,$L=(a,e=20)=>{let t=0;return RL(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Le=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?_g(i):(i=document.createElement("video"),a.appendChild(i)),Fl.set(i,r);let s=new LL;return s.add($L(i,e)),Nl.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},$e=a=>{Nl.get(a)?.unsubscribe(),Nl.delete(a);let t=Fl.get(a);Fl.delete(a),t?_g(a):Vg(a)};var ql=C(er(),1);import{assertNonNullable as sa,isNonNullable as bt,isNullable as FL,fromEvent as tr,merge as jg,observableFrom as Qg,filterChanged as Gg,map as na,Subject as Wg,Subscription as NL,ValueSubject as UL,ErrorCategory as qL}from"@vkontakte/videoplayer-shared";import{isNonNullable as Ul,isNullable as _L,Subscription as OL}from"@vkontakte/videoplayer-shared";var fn=(a,e,t,{equal:i=(n,u)=>n===u,changed$:r,onError:s}={})=>{let n=a.getState(),u=e(),o=_L(r),l=new OL;return r&&l.add(r.subscribe(c=>{let p=a.getState();i(c,p)&&a.setState(c)},s)),i(u,n)||(t(n),o&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),o&&a.setState(c.to)},s)),l},mt=(a,e,t)=>fn(e,()=>a.loop,i=>{Ul(i)&&(a.loop=i)},{onError:t}),Me=(a,e,t,i)=>fn(e,()=>({muted:a.muted,volume:a.volume}),r=>{Ul(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),ze=(a,e,t,i)=>fn(e,()=>a.playbackRate,r=>{Ul(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),aa=fn;var HL=a=>["__",a.language,a.label].join("|"),jL=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Hl=class a{constructor(e){this.available$=new Wg;this.current$=new UL(void 0);this.error$=new Wg;this.subscription=new NL;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:qL.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(aa(t.internalTextTracks,()=>(0,ql.default)(this.internalTracks),s=>{bt(s)&&this.setInternal(s)},{equal:(s,n)=>bt(s)&&bt(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe(na(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(aa(t.externalTextTracks,()=>(0,ql.default)(this.externalTracks),s=>{bt(s)&&this.setExternal(s)},{equal:(s,n)=>bt(s)&&bt(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe(na(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(aa(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(aa(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){sa(this.video);let{textTracks:e}=this.video;this.subscription.add(tr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(jg(tr(e,"addtrack"),tr(e,"removetrack"),Qg(["init"])).pipe(na(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Gg((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(jg(tr(e,"change"),Qg(["init"])).pipe(na(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),na(i=>i&&this.htmlTextTrackToITextTrack(i).id),Gg()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(tr(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(tr(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;bt(t.align)&&(r.align=t.align),bt(t.position)&&(r.position=t.position),bt(t.size)&&(r.size=t.size),bt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){sa(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:HL(e),s=this.externalTracks.has(r),n=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){sa(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(FL(e)||!jL(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){sa(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){sa(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)}},Ye=Hl;var mi=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 zg=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},jl=a=>{let e=zg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Yg=a=>{let e=zg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ee,map as gt,merge as Tn,filterChanged as rS,isNonNullable as aS,Subject as ZL,filter as Gl,mapTo as Wl,combine as e$,once as t$,shareReplay as xe,throttle as i$,ErrorCategory as r$,ValueSubject as sS,Subscription as a$}from"@vkontakte/videoplayer-shared";var QL=3,Kg=(a,e,t=QL)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),u=a.end(s);if(n<=e&&e<=u){if(i=n,r=u,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)a.end(o)+t>=i&&(i=a.start(o));for(let o=s+1;o<a.length;o++)a.start(o)-t<=r&&(r=a.end(o))}}return{from:i,to:r}};var mn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,u=/webkit|safari|khtml/i.test(e)?"Safari":void 0,o=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||o||l||r||s||u||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Xg=C(We(),1);var oa=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var bn=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,Xg.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=oa()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){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,u=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||u||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 gn=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(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}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(t){console.error(t)}}};var Ue=()=>window.ManagedMediaSource||window.MediaSource,ir=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Jg=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Sn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var GL=document.createElement("video"),WL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',zL='video/mp4; codecs="hev1.1.6.L93.B0"',Zg='video/webm; codecs="vp09.00.10.08"',eS='video/webm; codecs="av01.0.00M.08"',YL='audio/mp4; codecs="mp4a.40.2"',KL='audio/webm; codecs="opus"',tS,XL=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:eS}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Zg}})]);tS={DASH_WEBM_AV1:e,DASH_WEBM:t}};XL().catch(a=>{console.log(GL),console.error(a)});var vn=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 tS}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:ir(),mse:Jg(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Ue()?.isTypeSupported?.(WL),t=!!Ue()?.isTypeSupported?.(zL),i=!!Ue()?.isTypeSupported?.(YL);this._codecs={h264:e,h265:t,vp9:!!Ue()?.isTypeSupported?.(Zg),av1:!!Ue()?.isTypeSupported?.(eS),aac:i,opus:!!Ue()?.isTypeSupported?.(KL),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var iS="audio/mpeg",yn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(iS)},this._codecs={mp3:!!Ue()?.isTypeSupported?.(iS)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as JL}from"@vkontakte/videoplayer-shared";var Ql=class{constructor(){this.isInited$=new JL(!1);this._displayChecker=new gn,this._deviceChecker=new bn(this._displayChecker),this._browserChecker=new mn,this._videoChecker=new vn(this._deviceChecker,this._browserChecker),this._audioChecker=new yn,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)}},V=new Ql;var De=a=>{let e=T=>Ee(a,T).pipe(Wl(void 0),xe(1)),t=new a$,i=()=>t.unsubscribe(),r=Tn(Ee(a,"progress"),Ee(a,"timeupdate")).pipe(gt(()=>Kg(a.buffered,a.currentTime)),xe(1)),s=V.browser.isSafari?e$({play:e("play").pipe(t$()),playing:e("playing")}).pipe(Wl(void 0),xe(1)):e("playing"),n=Ee(a,"volumechange").pipe(gt(()=>({muted:a.muted,volume:a.volume})),xe(1)),u=Ee(a,"ratechange").pipe(gt(()=>a.playbackRate),xe(1)),o=Ee(a,"error").pipe(Gl(()=>!!(a.error||a.played.length)),gt(()=>{let T=a.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:r$.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:a.error??void 0}}),xe(1)),l=Ee(a,"timeupdate").pipe(gt(()=>a.currentTime),xe(1)),c=["waiting","seeking","seeked","timeupdate"],p=new ZL,d=.3,h;t.add(Tn(...c.map(T=>Ee(a,T))).subscribe(T=>{let F=a.currentTime;a.loop&&aS(h)&&aS(F)&&h>=a.duration-d&&F<=d&&p.next(h),h=F}));let f=e("pause").pipe(Gl(()=>!a.error&&h!==a.duration),xe(1)),b=Ee(a,"enterpictureinpicture").pipe(xe(1)),g=Ee(a,"leavepictureinpicture").pipe(xe(1)),S=new sS(Yg(a));t.add(b.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let I=new sS(jl(a)),y=Ee(a,"fullscreenchange").pipe(xe(1));t.add(y.pipe(gt(()=>jl(a))).subscribe(I));let x=.1,A=1e3,R=Ee(a,"timeupdate").pipe(gt(T=>a.duration-a.currentTime<x),rS(),xe(1)),$=Tn(R.pipe(Gl(T=>!a.loop&&T)),Ee(a,"ended")).pipe(i$(A),Wl(void 0),xe(1)),L=Tn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>Ee(a,T)),R.pipe(gt(T=>({type:T?"ended":"unknown"})))).pipe(gt(T=>V.browser.isFirefox&&T.type==="ended"?a.readyState<2:a.readyState<3),rS(),xe(1));return{playing$:s,pause$:f,canplay$:e("canplay"),ended$:$,looped$:p,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ee(a,"durationchange").pipe(gt(()=>a.duration),xe(1)),isBuffering$:L,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:S,inFullscreen$:I,enterPip$:b,leavePip$:g,destroy:i}};import{VideoQuality as Ht}from"@vkontakte/videoplayer-shared";var jt=a=>{switch(a){case"mobile":return Ht.Q_144P;case"lowest":return Ht.Q_240P;case"low":return Ht.Q_360P;case"sd":case"medium":return Ht.Q_480P;case"hd":case"high":return Ht.Q_720P;case"fullhd":case"full":return Ht.Q_1080P;case"quadhd":case"quad":return Ht.Q_1440P;case"ultrahd":case"ultra":return Ht.Q_2160P}};var Ae=C(at(),1),Kl=C(We(),1),bi=C(Hi(),1);import{isNonNullable as K,isNullable as An,now as TS,isHigher as kn,isHigherOrEqual as ar,isInvariantQuality as Pn,isLowerOrEqual as sr,videoSizeToQuality as IS,assertNotEmptyArray as Rn,assertNonNullable as ES}from"@vkontakte/videoplayer-shared";var zl=!1,Pt={},pS=a=>{zl=a},hS=()=>{Pt={}},fS=a=>{a(Pt)},ua=(a,e)=>{zl&&(Pt.meta=Pt.meta??{},Pt.meta[a]=e)},we=class{constructor(e){this.name=e}next(e){if(!zl)return;Pt.series=Pt.series??{};let t=Pt.series[this.name]??[];t.push([Date.now(),e]),Pt.series[this.name]=t}};import{isHigher as h$,isHigherOrEqual as HN,isLower as mS,isLowerOrEqual as jN,isNonNullable as In,isNullable as f$,videoHeightToQuality as En}from"@vkontakte/videoplayer-shared";function Yl(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function xn(a,e,t){return!!a&&Yl(a,e,t)==="high_quality"}function rr(a,e,t){return f$(a)||In(a.min)&&In(a.max)&&mS(a.max,a.min)||In(a.min)&&e&&h$(a.min,e)||In(a.max)&&t&&mS(a.max,t)}function bS({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return rr({max:a?.max?En(a.max):void 0,min:a?.min?En(a.min):void 0},e?En(e):void 0,t?En(t):void 0)}var xS=new we("best_bitrate"),Ln=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var nr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Qt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=TS()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},$n='Assertion "ABR Tracks is empty array" failed',wn=new WeakMap,gS=new WeakMap,SS=new WeakMap,la=(a,e,t,i)=>{let r=[...e].sort(nr(1)),s=[...t].sort(nr(1)),n=s.filter(o=>K(o.bitrate)&&K(a.bitrate)?a.bitrate/o.bitrate>i:!0),u=(0,Ae.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Ae.default)(s,-1);return u&&(0,Kl.default)(n,u)?u:n.length?(0,Ae.default)(n,-1):(0,Ae.default)(s,0)},ca=(a,e,t,i)=>{let r=wn.get(e);r||(r=[...e].sort(nr(1)),wn.set(e,r));let s=wn.get(t);s||(s=[...t].sort(nr(1)),wn.set(t,s));let n=SS.get(a);n||(n=s.filter(o=>K(o.bitrate)&&K(a.bitrate)?a.bitrate/o.bitrate>i:!0),SS.set(a,n));let u=(0,Ae.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Ae.default)(s,-1);return u&&(0,Kl.default)(n,u)?u:n.length?(0,Ae.default)(n,-1):(0,Ae.default)(s,0)},vS=a=>"quality"in a,Mn=(a,e,t,i)=>{let r=K(i?.last?.bitrate)&&K(t?.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&TS()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let u=vS(n)?"video":"audio",o=vS(n)?n.quality:n.bitrate;return e({message:`
8
+ [last ${u} selected] ${o}
9
+ `}),n}return i?.recordSwitch(t),t},m$=(a,e)=>Math.log(e)/Math.log(a),wS=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&V.display.pixelRatio){let s=V.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[u=0,o=0,l=0]=a.pixelRatioLogCoefficients,c=m$(n,u*s+o)+l;Number.isFinite(c)&&(r*=c)}}return xn(t,a.highQualityLimit,a.trafficSavingLimit)&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},yS=new WeakMap,St=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:c,droppedVideoMaxQualityLimit:p,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:f,panelSize:b})=>{Rn(a,$n);let{containerSizeFactor:g,containerSizeLimit:S}=wS({container:e,tuning:i,limits:r,panelSize:b}),I=i.considerPlaybackRate&&K(u)?u:1,y=yS.get(a);y||(y=a.filter(v=>!Pn(v.quality)).sort((v,E)=>kn(v.quality,E.quality)?-1:1),yS.set(a,y));let x=(0,Ae.default)(y,-1)?.quality,A=(0,Ae.default)(y,0)?.quality,R=rr(r,A,x),$=I*Ln(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),w={},L=null;for(let v of y){let E=!0;if(S)if(v.size)E=v.size.width<=S.width&&v.size.height<=S.height;else{let j=S&&IS(S);E=j?sr(v.quality,j):!0}if(!E){w[v.quality]="FitsContainer";continue}let W=h||t,D=K(W)&&isFinite(W)&&K(v.bitrate)?W-s>=v.bitrate*$:!0,q=xn(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===v.quality;if(!D&&!q){w[v.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&o&&!Pn(o.quality)&&(n??0)<i.minBufferToSwitchUp&&kn(v.quality,o.quality)){w[v.quality]="Buffer";continue}if(!!p&&ar(v.quality,p)&&!q){w[v.quality]="DroppedFramesLimit";continue}if(!!d&&ar(v.quality,d)&&!q){w[v.quality]="StallsLimit";continue}let fe=R||(An(r?.max)||sr(v.quality,r.max))&&(An(r?.min)||ar(v.quality,r.min)),me=K(c)&&!c?sr(v.quality,i.backgroundVideoQualityLimit):!0;if(!fe||!me){w[v.quality]="FitsQualityLimits";continue}L||(L=v)}L&&L.bitrate&&xS.next(L.bitrate);let T=L??(0,Ae.default)(y,-1)??a[0],F=l?.last,M=Mn(i,f,T,l);return K(l)&&M.quality!==F?.quality&&f({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${s.map(x=>`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${x.size?.width}:${x.size?.height} }`).join(`
12
+ ${a.map(v=>`{ id: ${v.id}, quality: ${v.quality}, bitrate: ${v.bitrate}, size: ${v.size?.width}:${v.size?.height} }`).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,Ni.default)(i??{}).map(([x,A])=>`${x}: ${A}`).join(`
16
+ ${(0,bi.default)(i??{}).map(([v,E])=>`${v}: ${E}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
@@ -21,32 +21,32 @@ var xx=Object.create;var xp=Object.defineProperty;var Ex=Object.getOwnPropertyDe
21
21
  containerSizeLimit: ${S?.width??0} x ${S?.height??0},
22
22
  estimatedThroughput: ${t},
23
23
  stallsPredictedThroughput: ${h},
24
- reserve: ${a},
25
- playbackRate: ${o},
26
- playbackRateFactor: ${T},
24
+ reserve: ${s},
25
+ playbackRate: ${u},
26
+ playbackRateFactor: ${I},
27
27
  forwardBufferHealth: ${n},
28
- bitrateFactor: ${O},
28
+ bitrateFactor: ${$},
29
29
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
30
- droppedVideoMaxQualityLimit: ${c},
31
- stallsVideoMaxQualityLimit: ${p},
32
- limitsAreInvalid: ${L},
30
+ droppedVideoMaxQualityLimit: ${p},
31
+ stallsVideoMaxQualityLimit: ${d},
32
+ limitsAreInvalid: ${R},
33
33
  maxQualityLimit: ${r?.max},
34
34
  minQualityLimit: ${r?.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,Ni.default)(P).map(([x,A])=>`${x}: ${A}`).join(`
37
+ ${(0,bi.default)(w).map(([v,E])=>`${v}: ${E}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
- [best video track] ${k?.quality}
41
- [selected video track] ${I?.quality}
42
- `}),I},bo=(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})=>{po(s,fo);let{containerSizeFactor:g,containerSizeLimit:S}=bv({container:e,tuning:i,limits:r,panelSize:b}),T=i.considerPlaybackRate&&J(o)?o:1,y=s.filter(A=>!co(A.quality)).sort((A,re)=>lo(A.quality,re.quality)?-1:1),E=(0,He.default)(y,-1)?.quality,w=(0,He.default)(y,0)?.quality,L=yr(r,w,E),O=T*ho(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),P={},v=y.filter(A=>{let re=!0;if(S)if(A.size)re=A.size.width<=S.width&&A.size.height<=S.height;else{let V=S&&hv(S);re=V?Ir(A.quality,V):!0}if(!re)return P[A.quality]="FitsContainer",!1;let $=h||t,q=J($)&&isFinite($)&&J(A.bitrate)?$-a>=A.bitrate*O:!0,X=no(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===A.quality;if(!q&&!X)return P[A.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&J(i.minBufferToSwitchUp)&&u&&!co(u.quality)&&(n??0)<i.minBufferToSwitchUp&&lo(A.quality,u.quality))return P[A.quality]="Buffer",!1;if(!!c&&Tr(A.quality,c)&&!X)return P[A.quality]="DroppedFramesLimit",!1;if(!!p&&Tr(A.quality,p)&&!X)return P[A.quality]="StallsLimit",!1;let Z=L||(uo(r?.max)||Ir(A.quality,r.max))&&(uo(r?.min)||Tr(A.quality,r.min)),M=J(d)&&!d?Ir(A.quality,i.backgroundVideoQualityLimit):!0;return!Z||!M?(P[A.quality]="FitsQualityLimits",!1):!0})[0];v&&v.bitrate&&mv.next(v.bitrate);let D=v??(0,He.default)(y,-1)??s[0],I=l?.last,x=mo(i,f,D,l);return J(l)&&x.quality!==I?.quality&&f({message:`
40
+ [best video track] ${L?.quality}
41
+ [selected video track] ${M?.quality}
42
+ `}),M},Dn=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:c,droppedVideoMaxQualityLimit:p,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:f,panelSize:b})=>{Rn(a,$n);let{containerSizeFactor:g,containerSizeLimit:S}=wS({container:e,tuning:i,limits:r,panelSize:b}),I=i.considerPlaybackRate&&K(u)?u:1,y=a.filter(E=>!Pn(E.quality)).sort((E,W)=>kn(E.quality,W.quality)?-1:1),x=(0,Ae.default)(y,-1)?.quality,A=(0,Ae.default)(y,0)?.quality,R=rr(r,A,x),$=I*Ln(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),w={},T=y.filter(E=>{let W=!0;if(S)if(E.size)W=E.size.width<=S.width&&E.size.height<=S.height;else{let N=S&&IS(S);W=N?sr(E.quality,N):!0}if(!W)return w[E.quality]="FitsContainer",!1;let D=h||t,q=K(D)&&isFinite(D)&&K(E.bitrate)?D-s>=E.bitrate*$:!0,J=xn(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===E.quality;if(!q&&!J)return w[E.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&o&&!Pn(o.quality)&&(n??0)<i.minBufferToSwitchUp&&kn(E.quality,o.quality))return w[E.quality]="Buffer",!1;if(!!p&&ar(E.quality,p)&&!J)return w[E.quality]="DroppedFramesLimit",!1;if(!!d&&ar(E.quality,d)&&!J)return w[E.quality]="StallsLimit",!1;let me=R||(An(r?.max)||sr(E.quality,r.max))&&(An(r?.min)||ar(E.quality,r.min)),j=K(c)&&!c?sr(E.quality,i.backgroundVideoQualityLimit):!0;return!me||!j?(w[E.quality]="FitsQualityLimits",!1):!0})[0];T&&T.bitrate&&xS.next(T.bitrate);let F=T??(0,Ae.default)(y,-1)??a[0],M=l?.last,v=Mn(i,f,F,l);return K(l)&&v.quality!==M?.quality&&f({message:`
43
43
  [VIDEO TRACKS ABR]
44
44
  [available video tracks]
45
- ${s.map(A=>`{ id: ${A.id}, quality: ${A.quality}, bitrate: ${A.bitrate}, size: ${A.size?.width}:${A.size?.height} }`).join(`
45
+ ${a.map(E=>`{ id: ${E.id}, quality: ${E.quality}, bitrate: ${E.bitrate}, size: ${E.size?.width}:${E.size?.height} }`).join(`
46
46
  `)}
47
47
 
48
48
  [tuning]
49
- ${(0,Ni.default)(i??{}).map(([A,re])=>`${A}: ${re}`).join(`
49
+ ${(0,bi.default)(i??{}).map(([E,W])=>`${E}: ${W}`).join(`
50
50
  `)}
51
51
 
52
52
  [limit params]
@@ -54,74 +54,74 @@ var xx=Object.create;var xp=Object.defineProperty;var Ex=Object.getOwnPropertyDe
54
54
  containerSizeLimit: ${S?.width??0} x ${S?.height??0},
55
55
  estimatedThroughput: ${t},
56
56
  stallsPredictedThroughput: ${h},
57
- reserve: ${a},
58
- playbackRate: ${o},
59
- playbackRateFactor: ${T},
57
+ reserve: ${s},
58
+ playbackRate: ${u},
59
+ playbackRateFactor: ${I},
60
60
  forwardBufferHealth: ${n},
61
- bitrateFactor: ${O},
61
+ bitrateFactor: ${$},
62
62
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
63
- droppedVideoMaxQualityLimit: ${c},
64
- stallsVideoMaxQualityLimit: ${p},
65
- limitsAreInvalid: ${L},
63
+ droppedVideoMaxQualityLimit: ${p},
64
+ stallsVideoMaxQualityLimit: ${d},
65
+ limitsAreInvalid: ${R},
66
66
  maxQualityLimit: ${r?.max},
67
67
  minQualityLimit: ${r?.min},
68
68
 
69
69
  [limited video tracks]
70
- ${(0,Ni.default)(P).map(([A,re])=>`${A}: ${re}`).join(`
70
+ ${(0,bi.default)(w).map(([E,W])=>`${E}: ${W}`).join(`
71
71
  `)||"All tracks are available"}
72
72
 
73
- [best video track] ${v?.quality}
74
- [selected video track] ${x?.quality}
75
- `}),x},go=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{po(t,fo);let d=r.considerPlaybackRate&&J(a)?a:1,c=[...t].sort(xr(-1)),p=s.bitrate;fv(p);let h=d*ho(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,b=Es(s,e,t,r.minVideoAudioRatio),g=l||i;J(g)&&isFinite(g)&&(f=c.find(y=>J(y.bitrate)&&J(b?.bitrate)?g-p>=y.bitrate*h&&y.bitrate>=b.bitrate:!1)),f||(f=b);let S=o?.last,T=f&&mo(r,u,f,o);return J(o)&&T?.bitrate!==S?.bitrate&&u({message:`
73
+ [best video track] ${T?.quality}
74
+ [selected video track] ${v?.quality}
75
+ `}),v},Cn=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{Rn(t,$n);let c=r.considerPlaybackRate&&K(s)?s:1,p=[...t].sort(nr(-1)),d=a.bitrate;ES(d);let h=c*Ln(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,b=la(a,e,t,r.minVideoAudioRatio),g=l||i;K(g)&&isFinite(g)&&(f=p.find(y=>K(y.bitrate)&&K(b?.bitrate)?g-d>=y.bitrate*h&&y.bitrate>=b.bitrate:!1)),f||(f=b);let S=u?.last,I=f&&Mn(r,o,f,u);return K(u)&&I?.bitrate!==S?.bitrate&&o({message:`
76
76
  [AUDIO TRACKS ABR]
77
77
  [available audio tracks]
78
78
  ${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
79
79
  `)}
80
80
 
81
81
  [tuning]
82
- ${(0,Ni.default)(r??{}).map(([y,E])=>`${y}: ${E}`).join(`
82
+ ${(0,bi.default)(r??{}).map(([y,x])=>`${y}: ${x}`).join(`
83
83
  `)}
84
84
 
85
85
  [limit params]
86
86
  estimatedThroughput: ${i},
87
87
  stallsPredictedThroughput: ${l},
88
- reserve: ${p},
89
- playbackRate: ${a},
90
- playbackRateFactor: ${d},
88
+ reserve: ${d},
89
+ playbackRate: ${s},
90
+ playbackRateFactor: ${c},
91
91
  forwardBufferHealth: ${n},
92
92
  bitrateFactor: ${h},
93
93
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
94
94
 
95
- [selected audio track] ${T?.id}
96
- `}),T},So=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{po(t,fo);let d=r.considerPlaybackRate&&J(a)?a:1,c=uv.get(t);c||(c=[...t].sort(xr(-1)),uv.set(t,c));let p=s.bitrate;fv(p);let h=d*ho(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,b=ws(s,e,t,r.minVideoAudioRatio),g=l||i;J(g)&&isFinite(g)&&(f=c.find(y=>J(y.bitrate)&&J(b?.bitrate)?g-p>=y.bitrate*h&&y.bitrate>=b.bitrate:!1)),f||(f=b);let S=o?.last,T=f&&mo(r,u,f,o);return J(o)&&T?.bitrate!==S?.bitrate&&u({message:`
95
+ [selected audio track] ${I?.id}
96
+ `}),I},Bn=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{Rn(t,$n);let c=r.considerPlaybackRate&&K(s)?s:1,p=gS.get(t);p||(p=[...t].sort(nr(-1)),gS.set(t,p));let d=a.bitrate;ES(d);let h=c*Ln(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,b=ca(a,e,t,r.minVideoAudioRatio),g=l||i;K(g)&&isFinite(g)&&(f=p.find(y=>K(y.bitrate)&&K(b?.bitrate)?g-d>=y.bitrate*h&&y.bitrate>=b.bitrate:!1)),f||(f=b);let S=u?.last,I=f&&Mn(r,o,f,u);return K(u)&&I?.bitrate!==S?.bitrate&&o({message:`
97
97
  [AUDIO TRACKS ABR]
98
98
  [available audio tracks]
99
99
  ${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
100
100
  `)}
101
101
 
102
102
  [tuning]
103
- ${(0,Ni.default)(r??{}).map(([y,E])=>`${y}: ${E}`).join(`
103
+ ${(0,bi.default)(r??{}).map(([y,x])=>`${y}: ${x}`).join(`
104
104
  `)}
105
105
 
106
106
  [limit params]
107
107
  estimatedThroughput: ${i},
108
108
  stallsPredictedThroughput: ${l},
109
- reserve: ${p},
110
- playbackRate: ${a},
111
- playbackRateFactor: ${d},
109
+ reserve: ${d},
110
+ playbackRate: ${s},
111
+ playbackRateFactor: ${c},
112
112
  forwardBufferHealth: ${n},
113
113
  bitrateFactor: ${h},
114
114
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
115
115
 
116
- [selected audio track] ${T?.id}
117
- `}),T};var $e=s=>new URL(s).hostname;import{assertNever as kv,assertNonNullable as Av,combine as kB,debounce as AB,ErrorCategory as Rv,filter as Mv,filterChanged as RB,isNonNullable as _c,map as Io,merge as Lv,observableFrom as MB,once as LB,Subscription as BB,ValueSubject as Fc,videoQualityToHeight as Bv,videoSizeToQuality as $B}from"@vkontakte/videoplayer-shared";var xv=C(kt(),1);var Sv=C(dt(),1),gv=s=>{if(s instanceof DOMException&&(0,Sv.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"))},Xe=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!gv(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return gv(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as yo,isNullable as lB,assertNonNullable as As}from"@vkontakte/videoplayer-shared";var yv=C(_i(),1);import{isNonNullable as vv,assertNonNullable as vo,now as oB}from"@vkontakte/videoplayer-shared";function Ae(){return oB()}function Dc(s){return Ae()-s}function Cc(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 Tv(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Er(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,g=()=>{if(u)return;vo(d);let I=Dc(d),x;if(I<b){x=b-I,setTimeout(g,x);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new r,L()},S=I=>(a=I,D),T=I=>(c=I,D),y=()=>(h="json",D),E=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},w=I=>(p=I,D),L=()=>{d=Ae(),n=new r,n.open("get",s);let I=0,x,A=0,re=()=>(vo(d),Math.max(d,Math.max(x||0,A||0)));if(a&&n.addEventListener("progress",$=>{let q=Ae();a.updateChunk&&$.loaded>I&&(a.updateChunk(re(),$.loaded-I),I=$.loaded,x=q)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;vo(n);let $=n.status;if($>=200&&$<300){let{response:q,responseType:X}=n,ne=q?.byteLength;if(typeof ne=="number"&&a){let ge=ne-I;ge&&a.updateChunk&&a.updateChunk(re(),ge)}X==="json"&&(!q||!(0,yv.default)(q).length)?E():(c&&c(),e(q))}else E()}),n.addEventListener("error",()=>{E()}),p){let $=()=>{vo(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(A=Ae(),n.removeEventListener("readystatechange",$))};n.addEventListener("readystatechange",$)}return n.responseType=h,n.send(),D},D={withBitrateReporting:S,withParallel:w,withJSONResponse:y,withRetryCount:I=>(l=I,D),withRetryInterval:(I,x)=>(vv(I)&&(b=I),vv(x)&&(f=x),D),withTimeout:I=>(o=I,D),withFinally:T,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return D}var Ps=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 Iv=C(_i(),1);var ks=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=Ae(),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=Ae()-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=Er(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=Ae()}_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=Ae();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,Iv.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}};import{Subject as cB}from"@vkontakte/videoplayer-shared";var To=1e4,Vc=3;var dB=6e4,pB=10,hB=1,fB=500,Rs=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 cB,this.chunkRateEstimator=new Ps(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Cc(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(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",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=Cc(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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),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*(F.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||{};!ov({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,xv.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||yo(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=()=>{Tv(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 ks(Vc,To,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 E=a&&(!d||d===this.rep);return E||t("Not running!"),E},p=(E,w,L)=>{u&&u.abort(),u=Er(this.urlResolver.resolve(E,!1),w,L,()=>this._retryCallback()).withTimeout(To).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Vc).withFinally(()=>{u=null}).send()},h=(E,w,L)=>{As(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),w,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=E=>{let w=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${w}=>${E}`),i.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let L=Ae()-1e4,O=0;for(let k=0;k<this.bufferStates.length;k++){let v=this.bufferStates[k];E=Math.min(E,v.buf),v.ts<L&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${E} drop=${O} jitter=${this.sourceJitter}`);let P=E-hB;this.sourceJitter>=0?P-=this.sourceJitter/2:this.sourceJitter-=1,P>3?f(1.15):P>1?f(1.1):P>.3?f(1.05):f(1)}},S=E=>{let w,L=()=>w&&w.start?w.start.length:0,O=$=>w.start[$]/1e3,P=$=>w.dur[$]/1e3,k=$=>w.fragIndex+$,v=($,q)=>({chunkIdx:k($),startTS:O($),dur:P($),discontinuity:q}),D=()=>{let $=0;if(w&&w.dur){let q=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,X=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ne=q;this.sourceJitter>1&&(ne+=this.sourceJitter-1);let ge=w.dur.length-1;for(;ge>=0&&(ne-=w.dur[ge],!(ne<=0));--ge);$=Math.min(ge,w.dur.length-1-X),$=Math.max($,0)}return v($,!0)},I=$=>{let q=L();if(!(q<=0)){if(yo($)){for(let X=0;X<q;X++)if(O(X)>$)return v(X)}return D()}},x=$=>{let q=L(),X=$?$.chunkIdx+1:0,ne=X-w.fragIndex;if(!(q<=0)){if(!$||ne<0||ne-q>pB)return t(`Resync: offset=${ne} bChunks=${q} chunk=`+JSON.stringify($)),D();if(!(ne>=q))return v(X-w.fragIndex,!1)}},A=($,q,X)=>{l&&l.abort(),l=Er(this.urlResolver.resolve($,!0,this.lowLatency),q,X,()=>this._retryCallback()).withTimeout(To).withRetryCount(Vc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:($,q)=>{A(E,X=>{if(!c())return;w=X;let ne=!!w.lowLatency;ne!==this.lowLatency&&b(ne);let ge=0;for(let oe=0;oe<w.dur.length;++oe)ge+=w.dur[oe];ge>0&&(As(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ge/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,$(I(q))},()=>this._handleNetworkError())},nextChunk:x}},T=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),As(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:E=>{let{videoElement:w,logger:L}=this.params,O=S(e.jidxUrl),P,k,v,D,I=0,x,A,re,$=()=>{x&&(clearTimeout(x),x=void 0);let V=Math.max(fB,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=I+V,Se=Ae(),te=Math.min(1e4,Ee-Se);I=Se;let ye=()=>{l||c()&&O.seek(()=>{c()&&(I=Ae(),q(),$())})};te>0?x=window.setTimeout(()=>{this.paused?$():ye()},te):ye()},q=()=>{let V;for(;V=O.nextChunk(D);)D=V,Z(V);let Ee=O.nextChunk(v);if(Ee){if(v&&Ee.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?$():(T(),this._initPlayerWith(e));return}oe(Ee)}else $()},X=(V,Ee)=>{if(!c()||!this.sourceBuffer)return;let Se,te,ye,et=Oe=>{window.setTimeout(()=>{c()&&X(V,Ee)},Oe)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),et(100);else{let Oe=Ae(),ce=w.currentTime;!this.paused&&w.buffered.length>1&&A===ce&&Oe-re>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),A!==ce&&(A=ce,re=Oe);let tt=this._getBufferSizeSec();if(tt>30)L(`Buffered ${tt} seconds; delaying appendBuffer`),et(2e3);else try{this.sourceBuffer.appendBuffer(V),this.videoPlayStarted?(this.bufferStates.push({ts:Oe,buf:tt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(xe){if(xe.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),ye=this.sourceBuffer.buffered.length,ye!==0&&(Se=this.sourceBuffer.buffered.start(0),te=ce,te-Se>4&&this.sourceBuffer.remove(Se,te-3)),et(1e3);else throw xe}}},ne=()=>{k&&P&&(L([`Appending chunk, sz=${k.byteLength}:`,JSON.stringify(v)]),X(k,function(){k=null,q()}))},ge=V=>e.fragUrlTemplate.replace("%%id%%",V.chunkIdx),oe=V=>{c()&&h(ge(V),(Ee,Se)=>{if(c()){if(Se/=1e3,k=Ee,v=V,n=V.startTS,Se){let te=Math.min(10,V.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*te:te}ne()}},()=>this._handleNetworkError())},Z=V=>{c()&&(As(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ge(V),!1)))},M=V=>{c()&&(e.cachedHeader=V,X(V,()=>{P=!0,ne()}))};a=!0,O.seek(V=>{if(c()){if(I=Ae(),!V){$();return}D=V,!lB(E)||V.startTS>E?oe(V):(v=V,q())}},E),e.cachedHeader?M(e.cachedHeader):p(e.headerUrl,M,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),yo(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,As(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return yo(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=Ae();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!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&&Dc(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=Ae();c<o&&(n=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Er(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(To).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;Xe(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?.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=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))},dB))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Pv=C(Mi(),1);import{debounce as mB,filter as Ev,fromEvent as bB,interval as gB,isHigher as SB,isInvariantQuality as vB,isLower as yB,merge as TB,Subject as wv,Subscription as IB}from"@vkontakte/videoplayer-shared";var Oc=class{constructor(){this.onDroopedVideoFramesLimit$=new wv;this.subscription=new IB;this.playing=!1;this.tracks=[];this.forceChecker$=new wv;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!vB(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{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&&SB(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??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(bB(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=gB(this.droppedFramesChecker.checkTime).pipe(Ev(()=>this.playing),Ev(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(mB(this.droppedFramesChecker.checkTime)),i=TB(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){let t=(0,Pv.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>yB(i,r)?-1:1)?.[0]?.[0];return 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}},wr=Oc;import{map as xB,Observable as EB}from"@vkontakte/videoplayer-shared";import{fromEvent as wB}from"@vkontakte/videoplayer-shared";var Ms=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var PB=(s,e)=>new EB(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ms()))},{...i,...e});r.observe(s);let a=wB(document,"visibilitychange").pipe(xB(n=>!document.hidden||Ms())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),gt=PB;var DB=["paused","playing","ready"],CB=["paused","playing","ready"],Ls=class{constructor(e){this.subscription=new BB;this.videoState=new U("stopped");this.representations$=new Fc([]);this.droppedFramesManager=new wr;this.maxSeekBackTime$=new Fc(1/0);this.zeroTime$=new Fc(void 0);this.liveOffset=new Fi;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Rv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let a=r.name??r.index.toString(10),n=hi(r.name)??$B(r.video),o=r.bitrate/1e3,u={...r.video};if(!n)continue;let l={id:a,quality:n,bitrate:o,size:u};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),_c(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);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,Nc.default)(CB,e)&&(n||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&(0,Nc.default)(DB,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(be(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?.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(be(this.params.source.url,u))}return;default:return kv(e)}};this.textTracksManager=new bt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Rv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Lv(this.videoState.stateChangeStarted$.pipe(Io(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Io(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=Ge(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($e(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=Ke(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Io(r=>r.map(({track:a})=>a)),Mv(r=>!!r.length),LB()).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(()=>{this.videoState.getTransition()?.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(RB(),Io(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(kB({zeroTime:this.zeroTime$.pipe(Mv(_c)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Dt(this.video,this.params.desiredState.isLooped,t)).add(Ye(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(mt(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(gt(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&Bv(r),min:a&&Bv(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{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":this.params.desiredState.playbackState.getTransition()?.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 kv(r.to)}},t)).add(Lv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,MB(["init"])).pipe(AB(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),We(this.video)}createLiveDashPlayer(){let e=new Rs({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,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(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&_c(t)?t:Ot(e.map(({track:l})=>l),{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?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let l=e.find(({track:d})=>d.id===a)?.representation;Av(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Av(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(be(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var $v=Ls;var QT=C(dt(),1);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)};import{assertNever as g0,assertNonNullable as S0,debounce as v0,ErrorCategory as HT,filter as Pd,filterChanged as Yo,fromEvent as y0,isNonNullable as jT,isNullable as T0,map as kd,merge as Ko,observableFrom as Ad,once as zT,Subscription as I0}from"@vkontakte/videoplayer-shared";var xo=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}},Pr=class extends xo{constructor(){super(),this.listeners||xo.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)}},Bs=class{constructor(){Object.defineProperty(this,"signal",{value:new Pr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?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>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Bs.prototype[Symbol.toStringTag]="AbortController",Pr.prototype[Symbol.toStringTag]="AbortSignal");function Eo(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 Uc(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Eo({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{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 VB=()=>"fetch"in window,$s=VB()&&Eo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Dv=$s?Uc({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,St=$s?Dv.fetch:window.fetch,A1=$s?Dv.Request:window.Request,ee=$s?Bs:window.AbortController,R1=$s?Pr:window.AbortSignal;var yd=C(Ds(),1);var yy=C(vy(),1);import{ErrorCategory as Vs}from"@vkontakte/videoplayer-shared";var wo=s=>{if(!s)return{id:"EmptyResponse",category:Vs.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Vs.NETWORK,message:`UV Error ${s}`};let e=(0,yy.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Vs.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:Vs.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Vs.PARSER,message:"Response is valid XML, but parser failed"}};var De=(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};import{abortable as gd,assertNonNullable as Vr,combine as Or,ErrorCategory as Rt,filter as Uo,filterChanged as ma,flattenObject as ba,fromEvent as si,getTraceSubscriptionMethod as ZD,interval as Sd,isNonNullable as ga,isNullable as OT,map as _r,merge as ji,now as vd,Subject as qo,Subscription as _T,tap as e0,throttle as t0,ValueSubject as de}from"@vkontakte/videoplayer-shared";var Ao=C(dt(),1),$r=C(kt(),1),Ro=C(Ds(),1);var T$=(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)},I$=s=>window.clearTimeout(s),Ty=s=>typeof s=="function"&&s?.toString().endsWith("{ [native code] }"),Iy=!Ty(window.requestIdleCallback)||!Ty(window.cancelIdleCallback),kr=Iy?T$:window.requestIdleCallback,_t=Iy?I$:window.cancelIdleCallback;var kT=C(Wn(),1);import{assertNever as x$,ErrorCategory as xy,Subject as Ey}from"@vkontakte/videoplayer-shared";var E$=18,wy=!1;try{wy=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=E$}catch(s){console.error(s)}var Gc=class{constructor(e){this.bufferFull$=new Ey;this.error$=new Ey;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:xy.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};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)};wy&&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(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:xy.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:x$(t)}}},Py=Gc;var Ar=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as bi,assertNonNullable as Je,ErrorCategory as ti,fromEvent as dd,getExponentialDelay as pd,isNonNullable as Br,isNullable as Ce,now as ko,once as UD,Subject as qD,Subscription as HD,ValueSubject as Hi}from"@vkontakte/videoplayer-shared";var z=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 Rr=class extends z{};var Os=class extends z{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 _s=class extends z{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 Fs=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var se=class extends z{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Ns=class extends se{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 Us=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qs=class extends z{constructor(e,t){super(e,t),this.data=this.content}};var Ui=class extends se{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 Hs=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var js=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zs=class extends se{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 Qs=class extends se{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Gs=class extends se{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Ws=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ys=class extends se{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 Ks=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xs=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Js=class extends se{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zs=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ea=class extends se{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ta=class extends se{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ia=class extends se{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 ra=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var sa=class extends se{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 aa=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var P$={ftyp:_s,moov:Fs,mvhd:Ns,moof:Us,mdat:qs,sidx:Ui,trak:Hs,mdia:Ws,mfhd:Js,tkhd:Ys,traf:Zs,tfhd:ea,tfdt:ta,trun:ia,minf:Ks,sv3d:js,st3d:zs,prhd:Qs,proj:Xs,equi:Gs,uuid:Os,stbl:ra,stsd:sa,avc1:aa,unknown:Rr},Zt=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{break}return t}createBox(e,t){let i=P$[e];return i?new i(t,new s):new Rr(t,new s)}};var mi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var A$=new TextDecoder("ascii"),R$=s=>A$.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",M$=s=>{let e=new Ui(s,new Zt),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 Zt().parse(s),r=new mi(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)},B$=s=>{let t=new Zt().parse(s),i=new mi(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},$$=s=>{let t=new Zt().parse(s);return new mi(t).find("sidx")?.timescale},D$=(s,e)=>{let i=new Zt().parse(s),a=new mi(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},C$=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 Zt().parse(s),r=new mi(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},ky={validateData:R$,parseInit:C$,getIndexRange:()=>{},parseSegments:M$,parseFeedableSegmentChunk:L$,getChunkEndTime:D$,getServerLatencyTimestamps:B$,getTimescaleFromIndex:$$};var oa=C(dt(),1);import{assertNonNullable as Yc,isNonNullable as Ly,isNullable as O$}from"@vkontakte/videoplayer-shared";import{assertNever as V$}from"@vkontakte/videoplayer-shared";var Ay={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"}},Ry=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=na(s,t),r=i in Ay,a=r?Ay[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=na(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}},na=(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},At=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return na(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:V$(e)}},qi=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Ry(i);if(!e(r))return;r.type==="master"&&qi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},My=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Ry(s);return qi(r.value,({tag:a,type:n,value:o})=>(a===17143?e=At(o,n):a===17026?t=At(o,n):a===17029&&(i=At(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var By=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],_$=[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 qi(s,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=At(f,h);l=na(g)}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=At(f,h):p===17545?r=At(f,h):p===21420&&l===475249515?u=At(f,h):p===374648427?qi(f,({tag:g,type:S,value:T})=>g===30321?(d=At(T,S)===1,!1):!0):a&&n&&(0,oa.default)(By,p)&&(o=!0),!o}),Yc(e,"Failed to parse webm Segment start"),Yc(t,"Failed to parse webm Segment end"),Yc(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},N$=s=>{if(O$(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},U$=(s,e)=>{let t=!1,i=!1,r=o=>Ly(o.time)&&Ly(o.position),a=[],n;return qi(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=At(l,u));break;case 183:break;case 241:n&&(n.position=At(l,u));break;default:t&&(0,oa.default)(By,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}}})},q$=s=>{let e=0,t=!1;try{qi(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,oa.default)(_$,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||=(0,oa.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},$y={validateData:My,parseInit:F$,getIndexRange:N$,parseSegments:U$,parseFeedableSegmentChunk:q$};var ua=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return $y;case"mp4":return ky}}throw new ReferenceError(`Unsupported mime type ${s}`)};var ud=C(td(),1),IT=C(Mi(),1),xT=C(id(),1),ET=C(kt(),1),ld=C(_i(),1);var fT=C(dt(),1),Lr=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,fT.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as FD,isNullable as yT}from"@vkontakte/videoplayer-shared";var Po=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var mT=s=>{try{let e=OD(),t=s.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let a=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:a};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function OD(){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})`})
116
+ [selected audio track] ${I?.id}
117
+ `}),I};var ge=a=>new URL(a).hostname;import{assertNever as VS,assertNonNullable as _S,combine as V$,debounce as _$,ErrorCategory as OS,filter as FS,filterChanged as O$,isNonNullable as tc,map as Fn,merge as NS,observableFrom as F$,once as N$,Subscription as U$,ValueSubject as ic,videoQualityToHeight as US,videoSizeToQuality as q$}from"@vkontakte/videoplayer-shared";var MS=C(at(),1);var kS=C(We(),1),AS=a=>{if(a instanceof DOMException&&(0,kS.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"))},Ce=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!AS(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return AS(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as _n,isNullable as S$,assertNonNullable as ha}from"@vkontakte/videoplayer-shared";var RS=C(er(),1);import{isNonNullable as PS,assertNonNullable as Vn,now as b$}from"@vkontakte/videoplayer-shared";function de(){return b$()}function Xl(a){return de()-a}function Jl(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,u,o=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return o&&(n+=l+"lowLat=1",l="&"),u&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function LS(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function or(a,e,t,i){let r=window.XMLHttpRequest,s,n,u,o=!1,l=0,c,p,d=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(o)return;Vn(c);let M=Xl(c),v;if(M<b){v=b-M,setTimeout(g,v);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new r,R()},S=M=>(s=M,F),I=M=>(p=M,F),y=()=>(h="json",F),x=()=>{if(!o){if(--l>=0){g(),i&&i();return}o=!0,p&&p(),t&&t()}},A=M=>(d=M,F),R=()=>{c=de(),n=new r,n.open("get",a);let M=0,v,E=0,W=()=>(Vn(c),Math.max(c,Math.max(v||0,E||0)));if(s&&n.addEventListener("progress",D=>{let q=de();s.updateChunk&&D.loaded>M&&(s.updateChunk(W(),D.loaded-M),M=D.loaded,v=q)}),u&&(n.timeout=u,n.addEventListener("timeout",()=>x())),n.addEventListener("load",()=>{if(o)return;Vn(n);let D=n.status;if(D>=200&&D<300){let{response:q,responseType:J}=n,ie=q?.byteLength;if(typeof ie=="number"&&s){let oe=ie-M;oe&&s.updateChunk&&s.updateChunk(W(),oe)}J==="json"&&(!q||!(0,RS.default)(q).length)?x():(p&&p(),e(q))}else x()}),n.addEventListener("error",()=>{x()}),d){let D=()=>{Vn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(E=de(),n.removeEventListener("readystatechange",D))};n.addEventListener("readystatechange",D)}return n.responseType=h,n.send(),F},F={withBitrateReporting:S,withParallel:A,withJSONResponse:y,withRetryCount:M=>(l=M,F),withRetryInterval:(M,v)=>(PS(M)&&(b=M),PS(v)&&(f=v),F),withTimeout:M=>(u=M,F),withFinally:I,send:R,abort:()=>{n&&(n.abort(),n=void 0),o=!0,p&&p()}};return F}var da=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,u=s.end-s.start;i+=n;let o=s.bytes*n/u;r+=o,s.start=t,s.bytes-=o}}}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 $S=C(er(),1);var pa=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=de(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=de()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=or(t,s,()=>r("error"),u),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=de()}_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=de();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,$S.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 u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-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}};import{Subject as v$}from"@vkontakte/videoplayer-shared";var On=1e4,Zl=3;var y$=6e4,T$=10,I$=1,E$=500,fa=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 v$,this.chunkRateEstimator=new da(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Jl(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(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",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=Jl(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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),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*(V.display.pixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u){s=this.manifest[u];let{max:o,min:l}=this.autoQualityLimits||{};!bS({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,MS.default)(this.manifest,-1).video.height})&&(o&&s.video.height>o||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||_n(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=()=>{LS(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 pa(Zl,On,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,u=null,o=null,l=null,c=!1,p=()=>{let x=s&&(!c||c===this.rep);return x||t("Not running!"),x},d=(x,A,R)=>{o&&o.abort(),o=or(this.urlResolver.resolve(x,!1),A,R,()=>this._retryCallback()).withTimeout(On).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Zl).withFinally(()=>{o=null}).send()},h=(x,A,R)=>{ha(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(x,!1),A,R,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},f=x=>{let A=i.playbackRate;i.playbackRate!==x&&(t(`Playback rate switch: ${A}=>${x}`),i.playbackRate=x)},b=x=>{this.lowLatency=x,t(`lowLatency changed to ${x}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let x=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=de()-1e4,$=0;for(let L=0;L<this.bufferStates.length;L++){let T=this.bufferStates[L];x=Math.min(x,T.buf),T.ts<R&&$++}this.bufferStates.splice(0,$),t(`update playback rate; minBuffer=${x} drop=${$} jitter=${this.sourceJitter}`);let w=x-I$;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)}},S=x=>{let A,R=()=>A&&A.start?A.start.length:0,$=D=>A.start[D]/1e3,w=D=>A.dur[D]/1e3,L=D=>A.fragIndex+D,T=(D,q)=>({chunkIdx:L(D),startTS:$(D),dur:w(D),discontinuity:q}),F=()=>{let D=0;if(A&&A.dur){let q=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,J=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ie=q;this.sourceJitter>1&&(ie+=this.sourceJitter-1);let oe=A.dur.length-1;for(;oe>=0&&(ie-=A.dur[oe],!(ie<=0));--oe);D=Math.min(oe,A.dur.length-1-J),D=Math.max(D,0)}return T(D,!0)},M=D=>{let q=R();if(!(q<=0)){if(_n(D)){for(let J=0;J<q;J++)if($(J)>D)return T(J)}return F()}},v=D=>{let q=R(),J=D?D.chunkIdx+1:0,ie=J-A.fragIndex;if(!(q<=0)){if(!D||ie<0||ie-q>T$)return t(`Resync: offset=${ie} bChunks=${q} chunk=`+JSON.stringify(D)),F();if(!(ie>=q))return T(J-A.fragIndex,!1)}},E=(D,q,J)=>{l&&l.abort(),l=or(this.urlResolver.resolve(D,!0,this.lowLatency),q,J,()=>this._retryCallback()).withTimeout(On).withRetryCount(Zl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(D,q)=>{E(x,J=>{if(!p())return;A=J;let ie=!!A.lowLatency;ie!==this.lowLatency&&b(ie);let oe=0;for(let fe=0;fe<A.dur.length;++fe)oe+=A.dur[fe];oe>0&&(ha(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(oe/A.dur.length)),r({name:"index",zeroTime:A.zeroTime,shiftDuration:A.shiftDuration}),this.sourceJitter=A.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,A.jitter/1e3)):1,D(M(q))},()=>this._handleNetworkError())},nextChunk:v}},I=()=>{s=!1,u&&u.abort(),o&&o.abort(),l&&l.abort(),ha(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:x=>{let{videoElement:A,logger:R}=this.params,$=S(e.jidxUrl),w,L,T,F,M=0,v,E,W,D=()=>{v&&(clearTimeout(v),v=void 0);let N=Math.max(E$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ke=M+N,Te=de(),ue=Math.min(1e4,ke-Te);M=Te;let Qe=()=>{l||p()&&$.seek(()=>{p()&&(M=de(),q(),D())})};ue>0?v=window.setTimeout(()=>{this.paused?D():Qe()},ue):Qe()},q=()=>{let N;for(;N=$.nextChunk(F);)F=N,me(N);let ke=$.nextChunk(T);if(ke){if(T&&ke.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?D():(I(),this._initPlayerWith(e));return}fe(ke)}else D()},J=(N,ke)=>{if(!p()||!this.sourceBuffer)return;let Te,ue,Qe,Bt=lt=>{window.setTimeout(()=>{p()&&J(N,ke)},lt)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),Bt(100);else{let lt=de(),_e=A.currentTime;!this.paused&&A.buffered.length>1&&E===_e&&lt-W>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),E!==_e&&(E=_e,W=lt);let Vt=this._getBufferSizeSec();if(Vt>30)R(`Buffered ${Vt} seconds; delaying appendBuffer`),Bt(2e3);else try{this.sourceBuffer.appendBuffer(N),this.videoPlayStarted?(this.bufferStates.push({ts:lt,buf:Vt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ke&&ke()}catch(ct){if(ct.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),Qe=this.sourceBuffer.buffered.length,Qe!==0&&(Te=this.sourceBuffer.buffered.start(0),ue=_e,ue-Te>4&&this.sourceBuffer.remove(Te,ue-3)),Bt(1e3);else throw ct}}},ie=()=>{L&&w&&(R([`Appending chunk, sz=${L.byteLength}:`,JSON.stringify(T)]),J(L,function(){L=null,q()}))},oe=N=>e.fragUrlTemplate.replace("%%id%%",N.chunkIdx),fe=N=>{p()&&h(oe(N),(ke,Te)=>{if(p()){if(Te/=1e3,L=ke,T=N,n=N.startTS,Te){let ue=Math.min(10,N.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ue:ue}ie()}},()=>this._handleNetworkError())},me=N=>{p()&&(ha(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(oe(N),!1)))},j=N=>{p()&&(e.cachedHeader=N,J(N,()=>{w=!0,ie()}))};s=!0,$.seek(N=>{if(p()){if(M=de(),!N){D();return}F=N,!S$(x)||N.startTS>x?fe(N):(T=N,q())}},x),e.cachedHeader?j(e.cachedHeader):d(e.headerUrl,j,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),_n(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,ha(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return _n(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=p=>{if(!this.autoQuality)return;let d,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&p<this.bitrate&&(h=this._getBufferSizeSec(),f=p/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(p)}`);return}d=this._selectQuality(p),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${p}`)},s={updateChunk:(d,h)=>{let f=de();if(this.chunkRateEstimator.addInterval(d,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-d,speed:g}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},n=-1/0,u,o=!0,l=()=>{let p=s.get();if(p&&u&&this.autoQuality){if(o&&p>u&&Xl(n)<3e4)return;i(p)}o=this.autoQuality};return{updateChunk:(p,d)=>{let h=s.updateChunk(p,d);return h&&l(),h},notifySwitch:p=>{let d=de();p<u&&(n=d),u=p}}}_fetchManifest(e,t,i){this.manifestRequest=or(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(On).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;Ce(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 u=[];return n?.length?(n.forEach((o,l)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=l,u.push(o))}),u.sort(function(o,l){return o.video&&l.video?l.video.height-o.video.height:l.bitrate-o.bitrate}),u):(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))},y$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var BS=C(Hi(),1);import{debounce as x$,filter as DS,fromEvent as w$,interval as A$,isHigher as k$,isInvariantQuality as P$,isLower as R$,merge as L$,Subject as CS,Subscription as $$}from"@vkontakte/videoplayer-shared";var ec=class{constructor(){this.onDroopedVideoFramesLimit$=new CS;this.subscription=new $$;this.playing=!1;this.tracks=[];this.forceChecker$=new CS;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!P$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{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&&k$(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??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(w$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=A$(this.droppedFramesChecker.checkTime).pipe(DS(()=>this.playing),DS(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(x$(this.droppedFramesChecker.checkTime)),i=L$(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){let t=(0,BS.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>R$(i,r)?-1:1)?.[0]?.[0];return 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}},ur=ec;import{map as M$,Observable as D$}from"@vkontakte/videoplayer-shared";import{fromEvent as C$}from"@vkontakte/videoplayer-shared";var ma=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var B$=(a,e)=>new D$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,u)=>{n.forEach(o=>t.next(o.isIntersecting||ma()))},{...i,...e});r.observe(a);let s=C$(document,"visibilitychange").pipe(M$(n=>!document.hidden||ma())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Ke=B$;var H$=["paused","playing","ready"],j$=["paused","playing","ready"],ba=class{constructor(e){this.subscription=new U$;this.videoState=new O("stopped");this.representations$=new ic([]);this.droppedFramesManager=new ur;this.maxSeekBackTime$=new ic(1/0);this.zeroTime$=new ic(void 0);this.liveOffset=new mi;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:OS.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),n=jt(r.name)??q$(r.video),u=r.bitrate/1e3,o={...r.video};if(!n)continue;let l={id:s,quality:n,bitrate:u,size:o};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),tc(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);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(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,rc.default)(j$,e)&&(n||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&(0,rc.default)(H$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="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 o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(se(this.params.source.url,o))}return;default:return VS(e)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:OS.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(NS(this.videoState.stateChangeStarted$.pipe(Fn(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Fn(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Le(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=De(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Fn(r=>r.map(({track:s})=>s)),FS(r=>!!r.length),N$()).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(()=>{this.videoState.getTransition()?.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(O$(),Fn(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(V$({zeroTime:this.zeroTime$.pipe(FS(tc)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(mt(this.video,this.params.desiredState.isLooped,t)).add(Me(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(Ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&US(r),min:s&&US(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{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":this.params.desiredState.playbackState.getTransition()?.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 VS(r.to)}},t)).add(NS(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,F$(["init"])).pipe(_$(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),$e(this.video)}createLiveDashPlayer(){let e=new fa({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,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(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&tc(t)?t:St(e.map(({track:l})=>l),{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?.id,n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==u)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),n||o||s!==u){let l=e.find(({track:c})=>c.id===s)?.representation;_S(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;_S(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(se(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var qS=ba;var lT=C(We(),1);var pe=(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)};import{assertNever as $C,assertNonNullable as MC,debounce as DC,ErrorCategory as nT,filter as Fc,filterChanged as fo,fromEvent as CC,isNonNullable as oT,isNullable as BC,map as Nc,merge as mo,observableFrom as Uc,once as uT,Subscription as VC}from"@vkontakte/videoplayer-shared";var{NativeAbortSignal:fq,NativeAbortController:mq}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self<"u"?self:global);function HS(a){let e;try{e=new Event("abort")}catch{typeof document<"u"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function jS(a){if(a===void 0)if(typeof document>"u")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch{a=new Error("This operation was aborted"),a.name="AbortError"}return a}var Nn=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(u){Promise.resolve().then(()=>{throw u})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},lr=class extends Nn{constructor(){super(),this.listeners||Nn.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)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new gi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new gi;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},gi=class{constructor(){Object.defineProperty(this,"signal",{value:new lr,writable:!0,configurable:!0})}abort(e){let t=jS(e),i=HS(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(gi.prototype[Symbol.toStringTag]="AbortController",lr.prototype[Symbol.toStringTag]="AbortSignal");function Un(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 ac(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Un({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 p;c&&c.signal&&(p=c.signal,delete c.signal);let d=new t(l,c);return p&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:p}),d},s.prototype=t.prototype);let n=e;return{fetch:(o,l)=>{let c=s&&s.prototype.isPrototypeOf(o)?o.signal:l?l.signal:void 0;if(c){let p;try{p=new DOMException("Aborted","AbortError")}catch{p=new Error("Aborted"),p.name="AbortError"}if(c.aborted)return Promise.reject(p);let d=new Promise((h,f)=>{c.addEventListener("abort",()=>f(p),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(o,l)])}return n(o,l)},Request:s}}var Q$=()=>"fetch"in window,ga=Q$()&&Un({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),QS=ga?ac({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Xe=ga?QS.fetch:window.fetch,wq=ga?QS.Request:window.Request,X=ga?gi:window.AbortController,Aq=ga?lr:window.AbortSignal;var Dc=C(Sa(),1);var $v=C(Lv(),1);import{ErrorCategory as ya}from"@vkontakte/videoplayer-shared";var qn=a=>{if(!a)return{id:"EmptyResponse",category:ya.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ya.NETWORK,message:`UV Error ${a}`};let e=(0,$v.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ya.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:ya.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ya.PARSER,message:"Response is valid XML, but parser failed"}};var Se=(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};import{abortable as Lc,assertNonNullable as vr,combine as yr,ErrorCategory as ot,filter as so,filterChanged as Ja,flattenObject as Za,fromEvent as Dt,getTraceSubscriptionMethod as hC,interval as $c,isNonNullable as es,isNullable as eT,map as Tr,merge as Ii,now as Mc,Subject as no,Subscription as tT,tap as fC,throttle as mC,ValueSubject as ee}from"@vkontakte/videoplayer-shared";var Gn=C(We(),1),Ti=C(at(),1),Wn=C(Sa(),1);var LM=(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)},$M=a=>window.clearTimeout(a),Mv=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),Dv=!Mv(window.requestIdleCallback)||!Mv(window.cancelIdleCallback),cr=Dv?LM:window.requestIdleCallback,vt=Dv?$M:window.cancelIdleCallback;var jy=C(pn(),1);import{assertNever as MM,ErrorCategory as Cv,Subject as Bv}from"@vkontakte/videoplayer-shared";var DM=18,Vv=!1;try{Vv=V.browser.isSafari&&!!V.browser.safariVersion&&V.browser.safariVersion<=DM}catch(a){console.error(a)}var cc=class{constructor(e){this.bufferFull$=new Bv;this.error$=new Bv;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Cv.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};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)};Vv&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Cv.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:MM(t)}}},_v=cc;var dr=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Wt,assertNonNullable as Be,ErrorCategory as Lt,fromEvent as xc,getExponentialDelay as wc,isNonNullable as br,isNullable as ve,now as Qn,once as tC,Subject as iC,Subscription as rC,ValueSubject as yi}from"@vkontakte/videoplayer-shared";var Ov=C(at(),1);var Hn=a=>a.valid,Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var pr=class extends Q{};import{assertNever as CM}from"@vkontakte/videoplayer-shared";var Ta=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:CM(e)}}};var Ia=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var Ea=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Z=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var xa=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var wa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Aa=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var Si=class extends Z{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,u=this.readUint32();r=this.readUint32();let o=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:u,SAPType:o,SAPDeltaTime:l})}}}};var ka=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ra=class extends Z{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var La=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var $a=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Ma=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Da=class extends Z{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 Ca=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ba=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Va=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var _a=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Oa=class extends Z{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 Fa=class extends Z{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 Na=class extends Z{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 Ua=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qa=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Ha=class extends Q{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var VM={ftyp:Ia,moov:Ea,mvhd:xa,moof:wa,mdat:Aa,sidx:Si,trak:ka,mdia:Ma,mfhd:Va,tkhd:Da,traf:_a,tfhd:Oa,tfdt:Fa,trun:Na,minf:Ca,sv3d:Pa,st3d:Ra,prhd:La,proj:Ba,equi:$a,uuid:Ta,stbl:Ua,stsd:qa,avc1:Ha,unknown:pr},Rt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(u){if(!(u instanceof RangeError))throw u}if(!n||!Hn(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=VM[e];return i?new i(t,new a):new pr(t,new a)}};var Gt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{Hn(t)&&(this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var OM=new TextDecoder("ascii"),FM=a=>OM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",NM=a=>{let e=new Si(a,new Rt),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,u={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,u})},UM=(a,e)=>{let i=new Rt().parse(a),r=new Gt(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let u=s[0],o=n[n.length-1],l=u.source.byteOffset,p=o.source.byteOffset-u.source.byteOffset+o.size;return new DataView(a.buffer,l,p)},qM=a=>{let t=new Rt().parse(a),i=new Gt(t),r={},s=i.findAll("uuid"),n=(0,Ov.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},HM=a=>{let t=new Rt().parse(a);return new Gt(t).find("sidx")?.timescale},jM=(a,e)=>{let i=new Rt().parse(a),s=new Gt(i).findAll("traf"),n=s[s.length-1].children.find(p=>p.type==="tfhd"),u=s[s.length-1].children.find(p=>p.type==="tfdt"),o=s[s.length-1].children.find(p=>p.type==="trun"),l=0;return o.sampleDuration.length?l=o.sampleDuration.reduce((p,d)=>p+d,0):l=n.defaultSampleDuration*o.sampleCount,(Number(u.baseMediaDecodeTime)+l)/e*1e3},QM=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 Rt().parse(a),r=new Gt(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let u=r.find("prhd");u&&(e.projectionData.pose.yaw=u.poseYawDegrees,e.projectionData.pose.pitch=u.posePitchDegrees,e.projectionData.pose.roll=u.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},Fv={validateData:FM,parseInit:QM,getIndexRange:()=>{},parseSegments:NM,parseFeedableSegmentChunk:UM,getChunkEndTime:jM,getServerLatencyTimestamps:qM,getTimescaleFromIndex:HM};var Ga=C(We(),1);import{assertNonNullable as dc,isNonNullable as Hv,isNullable as WM}from"@vkontakte/videoplayer-shared";import{assertNever as GM}from"@vkontakte/videoplayer-shared";var Nv={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"}},Uv=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=Qa(a,t),r=i in Nv,s=r?Nv[i].type:"binary",n=a.getUint8(t),u=0;n&128?u=1:n&64?u=2:n&32?u=3:n&16?u=4:n&8?u=5:n&4?u=6:n&2?u=7:n&1&&(u=8);let o=new DataView(a.buffer,a.byteOffset+t+1,u-1),l=n&255>>u,c=Qa(o),p=l*2**((u-1)*8)+c,d=t+u,h;return d+p>a.byteLength?h=new DataView(a.buffer,a.byteOffset+d):h=new DataView(a.buffer,a.byteOffset+d,p),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+p,value:h,valueSize:p}},Qa=(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},st=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Qa(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:GM(e)}},vi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Uv(i);if(!e(r))return;r.type==="master"&&vi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},qv=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Uv(a);return vi(r.value,({tag:s,type:n,value:u})=>(s===17143?e=st(u,n):s===17026?t=st(u,n):s===17029&&(i=st(u,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var jv=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],zM=[231,22612,22743,167,171,163,160,175],YM=a=>{let e,t,i,r,s=!1,n=!1,u=!1,o,l,c=!1,p=0;return vi(a,({tag:d,type:h,value:f,valueSize:b})=>{if(d===21419){let g=st(f,h);l=Qa(g)}else d!==21420&&(l=void 0);return d===408125543?(e=f.byteOffset,t=f.byteOffset+b):d===357149030?s=!0:d===290298740?n=!0:d===2807729?i=st(f,h):d===17545?r=st(f,h):d===21420&&l===475249515?o=st(f,h):d===374648427?vi(f,({tag:g,type:S,value:I})=>g===30321?(c=st(I,S)===1,!1):!0):s&&n&&(0,Ga.default)(jv,d)&&(u=!0),!u}),dc(e,"Failed to parse webm Segment start"),dc(t,"Failed to parse webm Segment end"),dc(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:c,stereoMode:p,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},KM=a=>{if(WM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},XM=(a,e)=>{let t=!1,i=!1,r=u=>Hv(u.time)&&Hv(u.position),s=[],n;return vi(a,({tag:u,type:o,value:l})=>{switch(u){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=st(l,o));break;case 183:break;case 241:n&&(n.position=st(l,o));break;default:t&&(0,Ga.default)(jv,u)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((u,o)=>{let{time:l,position:c}=u,p=s[o+1];return{status:"none",time:{from:l,to:p?p.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:p?e.segmentStart+p.position-1:e.segmentEnd-1}}})},JM=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,Ga.default)(zM,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,Ga.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Qv={validateData:qv,parseInit:YM,getIndexRange:KM,parseSegments:XM,parseFeedableSegmentChunk:JM};var yt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Qv;case"mp4":return Fv}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Tt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Sc=C(fy(),1),Vy=C(Hi(),1),_y=C(Ly(),1),Oy=C(at(),1),vc=C(er(),1);var $y=C(We(),1),gc=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(),u=s+n;return(0,$y.default)(["6E","7A","F4"],u)}}return!1};import{isNonNullable as JD,isNullable as Cy}from"@vkontakte/videoplayer-shared";var My=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Dy=a=>{try{let e=XD(),t=a.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(o=>{r[o[0]]=o.slice(2)})}let s=i.variants?.split(/-/).filter(u=>u!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(n).forEach(u=>{let o=n[u];(typeof o>"u"||o==="")&&delete n[u]}),n}return null}catch{return null}};function XD(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
118
+ (?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
119
119
  (-(?<script>[a-z]{4}))?
120
120
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
121
121
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
122
122
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
123
123
  (?:-(?<privateuse>(?:${e})))?
124
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var sd=C(kt(),1);import{videoSizeToQuality as _D}from"@vkontakte/videoplayer-shared";var bT=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?hi(a):void 0)??_D({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},gT=({id:s,bitrate:e})=>({id:s,bitrate:e}),ST=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),vT=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),ad=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,sd.default)(i.split("."),0),isDefault:r}),nd=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,sd.default)(r.split("."),0)}),od=s=>"url"in s,je=s=>s.type==="template",la=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var TT=s=>{if(!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?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},ei=(s,e)=>{let t=s;t=(0,ud.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,IT.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,ud.default)(t,n,(o,u)=>yT(a)?o:yT(u)?a:(0,xT.default)(a,parseInt(u,10),"0"))}return t},wT=(s,e)=>{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(k=>k.textContent?.trim()??""),o=(0,ET.default)(n,0)??"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],p=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={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 S,T=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],E=y.reduce((k,v)=>({...k,[v.id]:v.children}),{}),w=y.reduce((k,v)=>({...k,[v.id]:v.getAttribute("duration")}),{});T?S=TT(T):(0,ld.default)(w).filter(k=>k).length&&!u?S=(0,ld.default)(w).reduce((k,v)=>k+(TT(v)??0),0):b&&(S=parseInt(b,10));let L=0,O=a.getAttribute("profiles")?.split(",")??[];for(let k of y.map(v=>v.id))for(let v of E[k]){let D=v.getAttribute("id")??"id"+(L++).toString(10),I=v.getAttribute("mimeType")??"",x=v.getAttribute("codecs")??"",A=v.getAttribute("contentType")??I?.split("/")[0],re=v.getAttribute("profiles")?.split(",")??[],$=mT(v.getAttribute("lang")??"")??{},q=v.querySelector("Label")?.textContent?.trim()??void 0,X=v.querySelectorAll("Representation"),ne=v.querySelector("SegmentTemplate"),ge=v.querySelector("Role")?.getAttribute("value")??void 0,oe=A,Z={id:D,language:$.language,isDefault:ge==="main",label:q,codecs:x,hdr:oe==="video"&&Lr(x),mime:I,representations:[]};for(let M of X){let V=M.getAttribute("lang")??void 0,Ee=q??v.getAttribute("label")??M.getAttribute("label")??void 0,Se=M.querySelector("BaseURL")?.textContent?.trim()??"",te=new URL(Se||o,e).toString(),ye=M.getAttribute("mimeType")??I,et=M.getAttribute("codecs")??x??"",Oe;if(A==="text"){let ce=M.getAttribute("id")||"",tt=$.privateuse?.includes("x-auto")||ce.includes("_auto"),xe=M.querySelector("SegmentTemplate");if(xe){let vt={representationId:M.getAttribute("id")??void 0,bandwidth:M.getAttribute("bandwidth")??void 0},Nt=parseInt(M.getAttribute("bandwidth")??"",10)/1e3,Ut=parseInt(xe.getAttribute("startNumber")??"",10)??1,it=parseInt(xe.getAttribute("timescale")??"",10),Ei=xe.querySelectorAll("SegmentTimeline S")??[],rt=xe.getAttribute("media");if(!rt)continue;let qt=[],Ht=0,jt="",st=0,yt=Ut,W=0;for(let ue of Ei){let _e=parseInt(ue.getAttribute("d")??"",10),ie=parseInt(ue.getAttribute("r")??"",10)||0,we=parseInt(ue.getAttribute("t")??"",10);W=Number.isFinite(we)?we:W;let Fe=_e/it*1e3,at=W/it*1e3;for(let he=0;he<ie+1;he++){let Pe=ei(rt,{...vt,segmentNumber:yt.toString(10),segmentTime:(W+he*_e).toString(10)}),nt=(at??0)+he*Fe,It=nt+Fe;yt++,qt.push({time:{from:nt,to:It},url:Pe})}W+=(ie+1)*_e,Ht+=(ie+1)*Fe}st=W/it*1e3,jt=ei(rt,{...vt,segmentNumber:yt.toString(10),segmentTime:W.toString(10)});let Tt={time:{from:st,to:1/0},url:jt},Te={type:"template",baseUrl:te,segmentTemplateUrl:rt,initUrl:"",totalSegmentsDurationMs:Ht,segments:qt,nextSegmentBeyondManifest:Tt,timescale:it};Oe={id:ce,kind:"text",segmentReference:Te,profiles:[],duration:S,bitrate:Nt,mime:"",codecs:"",width:0,height:0,isAuto:tt}}else Oe={id:ce,isAuto:tt,kind:"text",url:te}}else{let ce=M.getAttribute("contentType")??ye?.split("/")[0]??A,tt=v.getAttribute("profiles")?.split(",")??[],xe=parseInt(M.getAttribute("width")??"",10),vt=parseInt(M.getAttribute("height")??"",10),Nt=parseInt(M.getAttribute("bandwidth")??"",10)/1e3,Ut=M.getAttribute("frameRate")??"",it=M.getAttribute("quality")??void 0,Ei=Ut?Po(Ut):void 0,rt=M.getAttribute("id")??"id"+(L++).toString(10),qt=ce==="video"?`${vt}p`:ce==="audio"?`${Nt}Kbps`:et,Ht=`${rt}@${qt}`,jt=[...O,...re,...tt],st,yt=M.querySelector("SegmentBase"),W=M.querySelector("SegmentTemplate")??ne;if(yt){let Te=M.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ue,_e]=Te.split("-").map(Pe=>parseInt(Pe,10)),ie={from:ue,to:_e},we=M.querySelector("SegmentBase")?.getAttribute("indexRange"),[Fe,at]=we?we.split("-").map(Pe=>parseInt(Pe,10)):[],he=we?{from:Fe,to:at}:void 0;st={type:"byteRange",url:te,initRange:ie,indexRange:he}}else if(W){let Te={representationId:M.getAttribute("id")??void 0,bandwidth:M.getAttribute("bandwidth")??void 0},ue=parseInt(W.getAttribute("timescale")??"",10),_e=W.getAttribute("initialization")??"",ie=W.getAttribute("media"),we=parseInt(W.getAttribute("startNumber")??"",10)??1,Fe=ei(_e,Te);if(!ie)throw new ReferenceError("No media attribute in SegmentTemplate");let at=W.querySelectorAll("SegmentTimeline S")??[],he=[],Pe=0,nt="",It=0;if(at.length){let zt=we,le=0;for(let ot of at){let fe=parseInt(ot.getAttribute("d")??"",10),Ne=parseInt(ot.getAttribute("r")??"",10)||0,Qt=parseInt(ot.getAttribute("t")??"",10);le=Number.isFinite(Qt)?Qt:le;let wi=fe/ue*1e3,Eu=le/ue*1e3;for(let Gt=0;Gt<Ne+1;Gt++){let wu=ei(ie,{...Te,segmentNumber:zt.toString(10),segmentTime:(le+Gt*fe).toString(10)}),Wr=(Eu??0)+Gt*wi,Pu=Wr+wi;zt++,he.push({time:{from:Wr,to:Pu},url:wu})}le+=(Ne+1)*fe,Pe+=(Ne+1)*wi}It=le/ue*1e3,nt=ei(ie,{...Te,segmentNumber:zt.toString(10),segmentTime:le.toString(10)})}else if(FD(S)){let le=parseInt(W.getAttribute("duration")??"",10)/ue*1e3,ot=Math.ceil(S/le),fe=0;for(let Ne=1;Ne<ot;Ne++){let Qt=ei(ie,{...Te,segmentNumber:Ne.toString(10),segmentTime:fe.toString(10)});he.push({time:{from:fe,to:fe+le},url:Qt}),fe+=le}It=fe,nt=ei(ie,{...Te,segmentNumber:ot.toString(10),segmentTime:fe.toString(10)})}let xu={time:{from:It,to:1/0},url:nt};st={type:"template",baseUrl:te,segmentTemplateUrl:ie,initUrl:Fe,totalSegmentsDurationMs:Pe,segments:he,nextSegmentBeyondManifest:xu,timescale:ue}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ce||!ye)continue;let Tt={video:"video",audio:"audio",text:"text"}[ce];if(!Tt)continue;oe||=Tt,Oe={id:Ht,kind:Tt,segmentReference:st,profiles:jt,duration:S,bitrate:Nt,mime:ye,codecs:et,width:xe,height:vt,fps:Ei,quality:it}}Z.language||=V,Z.label||=Ee,Z.mime||=ye,Z.codecs||=et,Z.hdr||=oe==="video"&&Lr(et),Z.representations.push(Oe)}if(oe){let M=r[oe].find(V=>V.id===Z.id);if(M&&Z.representations.every(V=>je(V.segmentReference)))for(let V of M.representations){let Se=Z.representations.find(ye=>ye.id===V.id)?.segmentReference,te=V.segmentReference;te.segments.push(...Se.segments),te.nextSegmentBeyondManifest=Se.nextSegmentBeyondManifest}else r[oe].push(Z)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as PT}from"@vkontakte/videoplayer-shared";var _=(s,e)=>PT(s)&&PT(e)&&s.readyState==="open"&&ND(s,e);function ND(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var ca=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Hi(0);this.currentLowLatencySegmentLength$=new Hi(0);this.currentSegmentLength$=new Hi(0);this.onLastSegment$=new Hi(!1);this.fullyBuffered$=new Hi(!1);this.playingRepresentation$=new Hi(void 0);this.playingRepresentationInit$=new Hi(void 0);this.error$=new qD;this.gaps=[];this.subscription=new HD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ee;this.switchAbortController=new ee;this.destroyAbortController=new ee;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=bi(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Py(this.sourceBuffer),this.subscription.add(dd(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:ti.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:ti.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(dd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ti.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!_(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(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);Je(i,"No init buffer for starting representation"),Je(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=bi(this.destroyAbortController.signal,async function*(e,t=!1){if(!_(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Je(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ce(a)||Ce(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Je(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!_(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();Br(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=bi(this.destroyAbortController.signal,async function*(e,t=!1){if(!_(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Je(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ce(a)||Ce(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Je(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!_(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();Br(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=bi(this.destroyAbortController.signal,async function*(e){let t=(0,Ro.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let d=this.representations.get(u);if(!d||!je(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Je(r);let a=this.segments.get(i);Je(a,"No segments for starting representation");let n=this.initData.get(i);if(Je(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));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!_(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ee,bi(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);Je(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Ce(o)||Ce(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Je(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!_(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();Br(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(){!Ce(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 ee,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ce(e)||Ce(this.downloadingRepresentationId)||Ce(this.playingRepresentationId)||Ce(this.sourceBuffer)||!_(this.mediaSource,this.sourceBuffer)||Br(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Je(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);Br(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(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)&&Ar(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(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=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Ao.default)(u,r))d="high";else{let c=(0,$r.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.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,$r.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 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;Br(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,Ro.default)(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?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,Ro.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!je(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,$r.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Je(e);let t=this.segments.get(e);if(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(!je(r))return;let a=this.segments.get(i.id)??[],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=ei(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&_t&&_t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&_t&&_t(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:p,time:{from:h,to:f}},b)=>{let g=h<=i&&f>=i,S=h>i||g||b===0&&i===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+T||r<T&&f-h>=T||f<=i+T;return(p==="none"||p==="partially_ejected"&&S&&y&&this.sourceBuffer&&_(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,f)))&&S&&y});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let p=a;p<n.length&&(o<=d||u<=c);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){je(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 bi(o,async function*(){let d=pd(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=ko(),!d)return;let c=new DataView(d),p=ua(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]),la(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())je(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 bi(n,async function*(){let u=pd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),dd(window,"online").pipe(UD()).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=ko(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),la(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(je(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,$r.default)(e,0).byte.from,to:(0,$r.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=ko(),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:ti.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!je(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=ko();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:ti.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,Ao.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!_(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=ua(n.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!_(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(a.aborted){await n();continue}let d=l.byte.from-i,c=l.byte.to-i,p=c-d+1,h=d<r,f=c<=r;if(!h)continue;let b=ua(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(g,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 g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);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(!(Ce(this.sourceBuffer)||!_(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(De(this.sourceBuffer.buffered,e.segment.time.from,100)&&De(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:ti.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",od(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=kr(()=>(0,kT.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?bi(this.destroyAbortController.signal,async function*(){let o=pd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ua(e.mime),r)).then(async 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&&je(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:ti.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||!_(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ce(e))return!1;let r=[],a=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,p):l.push(u[d])}return l},o=u=>{if(a>=t)return r;r.push({...u.time}),r=n(r);let l=od(u)?u.size??0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let h of p)(0,Ao.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!_(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||!_(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||!_(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ce(e)?0:Re(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!_(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 a=0;a<this.sourceBuffer.buffered.length;a++){let n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*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(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!_(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=kr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:ti.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ce(this.sourceBuffer)||!_(this.mediaSource,this.sourceBuffer)||Ce(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:ti.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var gi=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var Mo=s=>{let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as da,assertNever as AT,fromEvent as RT,merge as jD,now as pa,Subscription as zD,Subject as MT,ValueSubject as hd,flattenObject as Dr,ErrorCategory as ha}from"@vkontakte/videoplayer-shared";var Lo=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var $o=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new hd(void 0);this.lastConnectionReused$=new hd(void 0);this.lastRequestFirstBytes$=new hd(void 0);this.recoverableError$=new MT;this.error$=new MT;this.abortAllController=new ee;this.subscription=new zD;this.fetchManifest=da(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=gi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Lo(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Bo);return r?(t.log("success",Dr({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Dr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=da(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}={}){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 D=new URL(l,location.href);D.searchParams.append("bytes",`${i.from}-${i.to}`),l=D.toString();break}default:AT(t)}this.requestQuic&&(l=gi(l));let p=this.abortAllController.signal,h;if(n){let D=new ee;if(h=jD(RT(this.abortAllController.signal,"abort"),RT(n,"abort")).subscribe(()=>{try{D.abort()}catch(I){Bo(I)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{D.abort()}catch(I){Bo(I)}p=D.signal}let f=pa();c.log("startRequest",Dr({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let b=yield this.doFetch(l,{priority:a,headers:d,signal:p}),g=pa();if(!b)return c.error("error",{message:"No response in request"}),c.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){h?.unsubscribe();let D=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:D}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){h?.unsubscribe();let D=pa(),I={requestStartedAt:f,requestEndedAt:D,duration:D-f};return c.log("endRequest",Dr(I)),c.end(),b.arrayBuffer()}let[S,T]=b.body.tee(),y=S.getReader();o&&this.throughputEstimator?.trackStream(T,u);let E=0,w=new Uint8Array(0),L=!1,O=D=>{h?.unsubscribe(),L=!0,Bo(D)},P=da(p,async function*({done:D,value:I}){if(E===0&&this.lastRequestFirstBytes$.next(pa()-f),p.aborted){h?.unsubscribe();return}if(!D&&I){let x=new Uint8Array(w.length+I.length);x.set(w),x.set(I,w.length),w=x,E+=I.byteLength,r?.(new DataView(w.buffer),E),yield y?.read().then(P,O)}}.bind(this));yield y?.read().then(P,O),h?.unsubscribe();let k=pa(),v={failed:L,requestStartedAt:f,requestEndedAt:k,duration:k-f};return L?(c.error("endRequest",Dr(v)),c.end(),null):(c.log("endRequest",Dr(v)),c.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=da(this.abortAllController.signal,async function*(e,t,i){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=e.indexRange??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 S=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=da(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}=Mo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:AT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await St(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:ha.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ha.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ha.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ha.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:ha.FATAL})}}},Bo=s=>{if(!la(s))throw s};var ii=(s,e,t)=>t*e+(1-t)*s,fd=(s,e)=>s.reduce((t,i)=>t+i,0)/e,LT=(s,e,t,i)=>{let r=0,a=t,n=fd(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};import{isNullable as QD,ValueSubject as BT}from"@vkontakte/videoplayer-shared";var Si=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new BT(e.initial),this.debounced$=new BT(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new qe(`raw_${t}`),this.smoothedSeries$=new qe(`smoothed_${t}`),this.reportedSeries$=new qe(`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)&&(QD(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 Do=class extends Si{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ii(this.slow,e,this.params.emaAlphaSlow),this.fast=ii(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Co=class extends Si{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=fd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ii(this.emaSmoothed,e,this.params.emaAlpha);let i=LT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Vo=class extends Si{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?ii(this.smoothed,t,this.params.emaAlpha):t}};var ri=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Do({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Co({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 Vo({initial:e,label:"liveEdgeDelay",...t})}};var Cr=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as GD,ValueSubject as WD}from"@vkontakte/videoplayer-shared";var fa=class s{constructor(e,t){this.currentRepresentation$=new WD(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!GD(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&je(t.segmentReference))}};var _o=C(kt(),1);import{assertNever as Fo}from"@vkontakte/videoplayer-shared";var $T=(s,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:a,nativeHlsSupported:n}=F.video,o=(a.h264||a.h265)&&a.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return s.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&a.vp9&&a.opus;case"DASH_WEBM_AV1":return u&&i.webm&&a.av1&&a.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(a.vp9||a.av1)&&(a.opus||a.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&a.h264&&(i.mp4||i.webm);default:return Fo(l)}})},Oo=s=>{let{webmDecodingInfo:e}=F.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:Fo(s)}return[t,i]},DT=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Oo(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(F.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",...Oo(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Oo(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Oo(s),...r,"HLS","HLS_ONDEMAND"];default:Fo(e)}return F.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},CT=({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=F.device.isMac&&F.browser.isSafari;if(F.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:Fo(s)}else F.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"]},md=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],No=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,_o.default)(t.value.split("."),0)}for(let t of s){let i=(0,_o.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,_o.default)(e.value.split("."),0)};var i0=["timeupdate","progress","play","seeked","stalled","waiting"],r0=["timeupdate","progress","loadeddata","playing","seeked"];var Ho=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new _T;this.representationSubscription=new _T;this.state$=new U("none");this.currentVideoRepresentation$=new de(void 0);this.currentVideoRepresentationInit$=new de(void 0);this.currentAudioRepresentation$=new de(void 0);this.currentVideoSegmentLength$=new de(0);this.currentAudioSegmentLength$=new de(0);this.error$=new qo;this.lastConnectionType$=new de(void 0);this.lastConnectionReused$=new de(void 0);this.lastRequestFirstBytes$=new de(void 0);this.currentLiveTextRepresentation$=new de(null);this.isLive$=new de(!1);this.isActiveLive$=new de(!1);this.isLowLatency$=new de(!1);this.liveDuration$=new de(0);this.liveSeekableDuration$=new de(0);this.liveAvailabilityStartTime$=new de(0);this.liveStreamStatus$=new de(void 0);this.bufferLength$=new de(0);this.liveLatency$=new de(void 0);this.liveLoadBufferLength$=new de(0);this.livePositionFromPlayer$=new de(0);this.currentStallDuration$=new de(0);this.videoLastDataObtainedTimestamp$=new de(0);this.fetcherRecoverableError$=new qo;this.fetcherError$=new qo;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new qo;this.gapWatchdogActive=!1;this.destroyController=new ee;this.initManifest=gd(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=be(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Rt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=gd(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Rt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=wT(e??"",this.manifestUrlString)}catch(n){let o=wo(e)??{id:"ManifestParsing",category:Rt.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&ht()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((o-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let c="active";l||(c=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(c)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:c,codecs:p})=>i(n,c,p)),l=new Set(u.map(({codecs:c})=>c)),d=No(l);if(d&&(r[n]=u.filter(({codecs:c})=>c.startsWith(d))),n==="video"){let c=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),h=r.video.some(f=>!f.hdr);F.display.isHDR&&c&&p?r.video=r.video.filter(f=>f.hdr):h&&(r.video=r.video.filter(f=>!f.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",ba(a)),a}.bind(this));this.initRepresentations=gd(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",ba({initialVideo:e,initialAudio:t,sourceHls:i})),Vr(this.manifest),Vr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(si(p,"error").pipe(Uo(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:Rt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?eo():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&vr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.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((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new ca("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],ga(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new ca("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}fa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new fa(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=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ji(...r0.map(p=>si(this.element,p))).pipe(_r(p=>this.element?Re(this.element.buffered,this.element.currentTime*1e3):0),ma(),e0(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ji(si(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ma()).subscribe(h=>this.liveStreamEndTimestamp=vd())),this.subscription.add(si(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Sd(1e3).subscribe(h=>{let f=di(this.manifestUrlString,2);this.manifestUrlString=be(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(si(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Or({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(_r(({isActiveLive:h,isLowLatency:f})=>h&&f),ma()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Cr(this.element,1)})),this.representationSubscription.add(Or({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Uo(({bufferLength:h,isActiveLive:f,isLowLatency:b})=>f&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Or({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Uo(({isLive:h})=>h),ma((h,f)=>f.bufferLength<h.bufferLength),_r(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=di(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Or({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=h-g;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(y)>S&&(E=1+Math.sign(y)*T),Cr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(Or({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(t0(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,g=di(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,w=isFinite(h)?h:f,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let P="none";if(L?P="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(k=>k.proceedLowLatencyLive()),P="active_low_latency"):g!==0&&w<T?P="live_forward_buffering":w<T+E&&(P="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),P==="live_forward_buffering"||P==="live_with_target_offset"){let k=p-(T+y),v=this.normolizeLiveOffset(Math.trunc(g+k/b)),D=Math.abs(v-g),I=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?I=g:v>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(I=v),this.manifestUrlString=be(this.manifestUrlString,I,2)}(P==="live_with_target_offset"||P==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:Rt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=ji(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(_r(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=ji(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(_r(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=Or({allBuffersFull:l,someBufferEnded:d}).pipe(ma(),_r(({allBuffersFull:p,someBufferEnded:h})=>p&&h),Uo(p=>p));if(this.representationSubscription.add(ji(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:Rt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(ji(...this.bufferManagers.map(p=>p.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 p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{p&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:Rt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[this.manifest.duration??0,...(0,yd.default)((0,yd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),je(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&ga(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Sd(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Rt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new $o({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=ri.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){Vr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?vd()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=be(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Vr(this.element),this.state$.setState("running"),this.subscription.add(ji(...i0.map(e=>si(this.element,e)),si(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Rt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(si(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(si(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&De(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=vd(),a=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,d=u<a&&r-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<a&&r-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||c)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:Rt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),i.position=p}this.tracer.log("stallIntervalCallback",ba(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Sd(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Rt.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),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?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Vr(this.element),Vr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),De(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(OT(this.element)||OT(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",ba({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){ga(this.element)&&ga(this.source)&&ga(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=ZD(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],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?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ba(i)))}}};var jo=class{constructor(e,t){this.fov=e,this.orientation=t}};var zo=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??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=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 NT=`attribute vec2 a_vertex;
124
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var By=a=>{if(!a?.startsWith("P"))return;let e=(n,u)=>{let o=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(o)?0:o)*u},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},nt=(a,e)=>{let t=a;t=(0,Sc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,Vy.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Sc.default)(t,n,(u,o)=>Cy(s)?u:Cy(o)?s:(0,_y.default)(s,parseInt(o,10),"0"))}return t},jn=(a,e)=>{let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(L=>L.textContent?.trim()??""),u=(0,Oy.default)(n,0)??"",o=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),p=s.getElementsByTagName("vk:Attrs")[0],d=p?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=p?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=p?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=p?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;o&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let S,I=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],x=y.reduce((L,T)=>({...L,[T.id]:T.children}),{}),A=y.reduce((L,T)=>({...L,[T.id]:T.getAttribute("duration")}),{});I?S=By(I):(0,vc.default)(A).filter(L=>L).length&&!o?S=(0,vc.default)(A).reduce((L,T)=>L+(By(T)??0),0):b&&(S=parseInt(b,10));let R=0,$=s.getAttribute("profiles")?.split(",")??[];for(let L of y.map(T=>T.id))for(let T of x[L]){let F=T.getAttribute("id")??"id"+(R++).toString(10),M=T.getAttribute("mimeType")??"",v=T.getAttribute("codecs")??"",E=T.getAttribute("contentType")??M?.split("/")[0],W=T.getAttribute("profiles")?.split(",")??[],D=Dy(T.getAttribute("lang")??"")??{},q=T.querySelector("Label")?.textContent?.trim()??void 0,J=T.querySelectorAll("Representation"),ie=T.querySelector("SegmentTemplate"),oe=T.querySelector("Role")?.getAttribute("value")??void 0,fe=E,me={id:F,language:D.language,isDefault:oe==="main",label:q,codecs:v,hdr:fe==="video"&&gc(v),mime:M,representations:[]};for(let j of J){let N=j.getAttribute("lang")??void 0,ke=q??T.getAttribute("label")??j.getAttribute("label")??void 0,Te=j.querySelector("BaseURL")?.textContent?.trim()??"",ue=new URL(Te||u,e).toString(),Qe=j.getAttribute("mimeType")??M,Bt=j.getAttribute("codecs")??v??"",lt;if(E==="text"){let _e=j.getAttribute("id")||"",Vt=D.privateuse?.includes("x-auto")||_e.includes("_auto"),ct=j.querySelector("SegmentTemplate");if(ct){let Rr={representationId:j.getAttribute("id")??void 0,bandwidth:j.getAttribute("bandwidth")??void 0},Is=parseInt(j.getAttribute("bandwidth")??"",10)/1e3,Es=parseInt(ct.getAttribute("startNumber")??"",10)??1,Li=parseInt(ct.getAttribute("timescale")??"",10),qo=ct.querySelectorAll("SegmentTimeline S")??[],$i=ct.getAttribute("media");if(!$i)continue;let xs=[],ws=0,As="",Mi=0,Lr=Es,Ie=0;for(let Je of qo){let ei=parseInt(Je.getAttribute("d")??"",10),Ge=parseInt(Je.getAttribute("r")??"",10)||0,_t=parseInt(Je.getAttribute("t")??"",10);Ie=Number.isFinite(_t)?_t:Ie;let ti=ei/Li*1e3,Di=Ie/Li*1e3;for(let dt=0;dt<Ge+1;dt++){let Ot=nt($i,{...Rr,segmentNumber:Lr.toString(10),segmentTime:(Ie+dt*ei).toString(10)}),Ci=(Di??0)+dt*ti,Mr=Ci+ti;Lr++,xs.push({time:{from:Ci,to:Mr},url:Ot})}Ie+=(Ge+1)*ei,ws+=(Ge+1)*ti}Mi=Ie/Li*1e3,As=nt($i,{...Rr,segmentNumber:Lr.toString(10),segmentTime:Ie.toString(10)});let $r={time:{from:Mi,to:1/0},url:As},Et={type:"template",baseUrl:ue,segmentTemplateUrl:$i,initUrl:"",totalSegmentsDurationMs:ws,segments:xs,nextSegmentBeyondManifest:$r,timescale:Li};lt={id:_e,kind:"text",segmentReference:Et,profiles:[],duration:S,bitrate:Is,mime:"",codecs:"",width:0,height:0,isAuto:Vt}}else lt={id:_e,isAuto:Vt,kind:"text",url:ue}}else{let _e=j.getAttribute("contentType")??Qe?.split("/")[0]??E,Vt=T.getAttribute("profiles")?.split(",")??[],ct=parseInt(j.getAttribute("width")??"",10),Rr=parseInt(j.getAttribute("height")??"",10),Is=parseInt(j.getAttribute("bandwidth")??"",10)/1e3,Es=j.getAttribute("frameRate")??"",Li=j.getAttribute("quality")??void 0,qo=Es?My(Es):void 0,$i=j.getAttribute("id")??"id"+(R++).toString(10),xs=_e==="video"?`${Rr}p`:_e==="audio"?`${Is}Kbps`:Bt,ws=`${$i}@${xs}`,As=[...$,...W,...Vt],Mi,Lr=j.querySelector("SegmentBase"),Ie=j.querySelector("SegmentTemplate")??ie;if(Lr){let Et=j.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Je,ei]=Et.split("-").map(Ot=>parseInt(Ot,10)),Ge={from:Je,to:ei},_t=j.querySelector("SegmentBase")?.getAttribute("indexRange"),[ti,Di]=_t?_t.split("-").map(Ot=>parseInt(Ot,10)):[],dt=_t?{from:ti,to:Di}:void 0;Mi={type:"byteRange",url:ue,initRange:Ge,indexRange:dt}}else if(Ie){let Et={representationId:j.getAttribute("id")??void 0,bandwidth:j.getAttribute("bandwidth")??void 0},Je=parseInt(Ie.getAttribute("timescale")??"",10),ei=Ie.getAttribute("initialization")??"",Ge=Ie.getAttribute("media"),_t=parseInt(Ie.getAttribute("startNumber")??"",10)??1,ti=nt(ei,Et);if(!Ge)throw new ReferenceError("No media attribute in SegmentTemplate");let Di=Ie.querySelectorAll("SegmentTimeline S")??[],dt=[],Ot=0,Ci="",Mr=0;if(Di.length){let ks=_t,Ze=0;for(let Bi of Di){let pt=parseInt(Bi.getAttribute("d")??"",10),ii=parseInt(Bi.getAttribute("r")??"",10)||0,Ps=parseInt(Bi.getAttribute("t")??"",10);Ze=Number.isFinite(Ps)?Ps:Ze;let Ho=pt/Je*1e3,RI=Ze/Je*1e3;for(let Rs=0;Rs<ii+1;Rs++){let LI=nt(Ge,{...Et,segmentNumber:ks.toString(10),segmentTime:(Ze+Rs*pt).toString(10)}),Ld=(RI??0)+Rs*Ho,$I=Ld+Ho;ks++,dt.push({time:{from:Ld,to:$I},url:LI})}Ze+=(ii+1)*pt,Ot+=(ii+1)*Ho}Mr=Ze/Je*1e3,Ci=nt(Ge,{...Et,segmentNumber:ks.toString(10),segmentTime:Ze.toString(10)})}else if(JD(S)){let Ze=parseInt(Ie.getAttribute("duration")??"",10)/Je*1e3,Bi=Math.ceil(S/Ze),pt=0;for(let ii=1;ii<Bi;ii++){let Ps=nt(Ge,{...Et,segmentNumber:ii.toString(10),segmentTime:pt.toString(10)});dt.push({time:{from:pt,to:pt+Ze},url:Ps}),pt+=Ze}Mr=pt,Ci=nt(Ge,{...Et,segmentNumber:Bi.toString(10),segmentTime:pt.toString(10)})}let PI={time:{from:Mr,to:1/0},url:Ci};Mi={type:"template",baseUrl:ue,segmentTemplateUrl:Ge,initUrl:ti,totalSegmentsDurationMs:Ot,segments:dt,nextSegmentBeyondManifest:PI,timescale:Je}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!_e||!Qe)continue;let $r={video:"video",audio:"audio",text:"text"}[_e];if(!$r)continue;fe||=$r,lt={id:ws,kind:$r,segmentReference:Mi,profiles:As,duration:S,bitrate:Is,mime:Qe,codecs:Bt,width:ct,height:Rr,fps:qo,quality:Li}}me.language||=N,me.label||=ke,me.mime||=Qe,me.codecs||=Bt,me.hdr||=fe==="video"&&gc(Bt),me.representations.push(lt)}if(fe){let j=r[fe].find(N=>N.id===me.id);if(j&&me.representations.every(N=>N.segmentReference.type==="template"))for(let N of j.representations){let Te=me.representations.find(Qe=>Qe.id===N.id)?.segmentReference,ue=N.segmentReference;ue.segments.push(...Te.segments),ue.nextSegmentBeyondManifest=Te.nextSegmentBeyondManifest}else r[fe].push(me)}}return{duration:S,streams:r,baseUrls:n,live:g}};var yc=C(at(),1);import{videoSizeToQuality as ZD}from"@vkontakte/videoplayer-shared";var Fy=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?jt(s):void 0)??ZD({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Ny=({id:a,bitrate:e})=>({id:a,bitrate:e}),Uy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),qy=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Tc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,yc.default)(i.split("."),0),isDefault:r}),Ic=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,yc.default)(r.split("."),0)}),Ec=a=>"url"in a,qe=a=>a.type==="template";import{isNonNullable as Hy}from"@vkontakte/videoplayer-shared";var B=(a,e)=>Hy(a)&&Hy(e)&&a.readyState==="open"&&eC(a,e);function eC(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var Wa=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new yi(0);this.currentLowLatencySegmentLength$=new yi(0);this.currentSegmentLength$=new yi(0);this.onLastSegment$=new yi(!1);this.fullyBuffered$=new yi(!1);this.playingRepresentation$=new yi(void 0);this.playingRepresentationInit$=new yi(void 0);this.error$=new iC;this.gaps=[];this.subscription=new rC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new X;this.switchAbortController=new X;this.destroyAbortController=new X;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=Wt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Be(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new _v(this.sourceBuffer),this.subscription.add(xc(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let u,o=this.mediaSource.readyState;o!=="open"&&(u={id:`SegmentEjection_source_${o}`,category:Lt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),u??={id:"SegmentEjection",category:Lt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(u)})),this.subscription.add(xc(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Lt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!B(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,dr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=this.getForwardBufferDuration(u),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<c).catch(p=>{this.handleAsyncError(p,"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);Be(i,"No init buffer for starting representation"),Be(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=Wt(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Be(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ve(s)||ve(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Be(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(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();br(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=Wt(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Be(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ve(s)||ve(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Be(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(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();br(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=Wt(this.destroyAbortController.signal,async function*(e){let t=(0,Wn.default)(e,o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let c=this.representations.get(o);if(!c||!qe(c.segmentReference))return;let p=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,p)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Be(r);let s=this.segments.get(i);Be(s,"No segments for starting representation");let n=this.initData.get(i);if(Be(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],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){!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new X,Wt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Be(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if(ve(u)||ve(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),Be(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();br(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ve(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 X,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ve(e)||ve(this.downloadingRepresentationId)||ve(this.playingRepresentationId)||ve(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||br(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Be(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);br(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),p=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=p)}if(isFinite(this.bufferLimit)&&dr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Gn.default)(o,r))c="high";else{let p=(0,Ti.default)(o,0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Ti.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;br(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,Wn.default)(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?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,Wn.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!qe(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],u=(0,Ti.default)(n,-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Be(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Ti.default)(e,-1)?.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!qe(r))return;let s=this.segments.get(i.id)??[],n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=nt(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&vt&&vt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&vt&&vt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:h,to:f}},b)=>{let g=h<=i&&f>=i,S=h>i||g||b===0&&i===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+I||r<I&&f-h>=I||f<=i+I;return(d==="none"||d==="partially_ejected"&&S&&y&&this.sourceBuffer&&B(this.mediaSource,this.sourceBuffer)&&!(Se(this.sourceBuffer.buffered,h)&&Se(this.sourceBuffer.buffered,f)))&&S&&y});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<n.length&&(u<=c||o<=p);d++){let h=n[d];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){qe(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:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await Wt(u,async function*(){let c=wc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(p=>setTimeout(p,c))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Qn(),!c)return;let p=new DataView(c),d=yt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(p,b)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(p,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(p);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Tt(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())qe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Wt(n,async function*(){let o=wc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),xc(window,"online").pipe(tC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Qn(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Tt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(qe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ti.default)(e,0).byte.from,to:(0,Ti.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Qn(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Lt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!qe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Qn();let p=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(p)}catch(p){this.error$.next({id:"SegmentFeeding",category:Lt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:p})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Gn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=yt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(o.status="partially_fed",u.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-i,p=l.byte.to-i,d=p-c+1,h=c<r,f=p<=r;if(!h)continue;let b=yt(u.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,d);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-c),o.loadedBytes>o.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+o.feedingBytes,o.loadedBytes-o.feedingBytes),S=o.loadedBytes===d?g:b.parseFeedableSegmentChunk(g);S?.byteLength&&(l.status="partially_fed",o.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(o.fedBytes+=S.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(ve(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer))){!this.isLive&&V.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Se(this.sourceBuffer.buffered,e.segment.time.from,100)&&Se(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Lt.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",Ec(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=cr(()=>(0,jy.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?Wt(this.destroyAbortController.signal,async function*(){let u=wc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,yt(e.mime),r)).then(async u=>{if(!u)return;let{init:o,dataView:l,segments:c}=u,p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,p);let d=c;this.isLive&&qe(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Lt.WTF,message:"loadInit threw",thrown:u})});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||!B(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ve(e))return!1;let r=[],s=0,n=o=>{o.sort((c,p)=>c.from-p.from);let l=[o[0]];for(let c=1;c<o.length;c++){let{from:p,to:d}=o[c],h=l[l.length-1];h.to>=p?h.to=Math.max(h.to,d):l.push(o[c])}return l},u=o=>{if(s>=t)return r;r.push({...o.time}),r=n(r);let l=Ec(o)?o.size??0:o.byte.to-o.byte.from;s+=l};for(let o of this.segments.values())for(let l of o){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||p)&&l.status==="fed"&&u(l)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let l=this.sourceBuffer.buffered.start(o)*1e3,c=this.sourceBuffer.buffered.end(o)*1e3,p=0;for(let d of this.segments.values())for(let h of d)(0,Gn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&p++;if(p===this.segments.size){let d={time:{from:l,to:c},url:"",status:"none"};u(d)}}if(r.length&&i){let o=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+o&&c.status==="fed"&&u(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||!B(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||!B(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||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ve(e)?0:pe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!B(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,u=this.sourceBuffer.buffered.end(s)*1e3;if(!(u<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),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||!B(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=cr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Lt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ve(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||ve(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),u=Math.ceil(r.time.to),o=e.some(c=>c.from-t<=n&&c.to+t>=u),l=e.filter(c=>n>=c.from&&n<c.to-t||u>c.from+t&&u<=c.to);o||(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:Lt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var zt=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var zn=a=>{let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as za,assertNever as Qy,fromEvent as Gy,merge as aC,now as Ya,Subscription as sC,Subject as Wy,ValueSubject as Ac,flattenObject as gr,ErrorCategory as Ka}from"@vkontakte/videoplayer-shared";var Yn=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Xn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Ac(void 0);this.lastConnectionReused$=new Ac(void 0);this.lastRequestFirstBytes$=new Ac(void 0);this.recoverableError$=new Wy;this.error$=new Wy;this.abortAllController=new X;this.subscription=new sC;this.fetchManifest=za(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=zt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Yn(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Kn);return r?(t.log("success",gr({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",gr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=za(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1}={}){let c=e,p=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let v=new URL(c,location.href);v.searchParams.append("bytes",`${i.from}-${i.to}`),c=v.toString();break}default:Qy(t)}this.requestQuic&&(c=zt(c));let h=this.abortAllController.signal,f;if(n){let v=new X;if(f=aC(Gy(this.abortAllController.signal,"abort"),Gy(n,"abort")).subscribe(()=>{try{v.abort()}catch(E){Kn(E)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(E){Kn(E)}h=v.signal}let b=Ya();d.log("startRequest",gr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:b}));let g=yield this.doFetch(c,{priority:s,headers:p,signal:h}),S=Ya();if(!g)return d.error("error",{message:"No response in request"}),d.end(),f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(S-b),!g.ok||!g.body){f?.unsubscribe();let v=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:v}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){f?.unsubscribe();let v=Ya(),E={requestStartedAt:b,requestEndedAt:v,duration:v-b};return d.log("endRequest",gr(E)),d.end(),g.arrayBuffer()}let I=g.body;if(u){let v;[I,v]=g.body.tee(),this.throughputEstimator?.trackStream(v,o)}let y=I.getReader(),x,A=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(A)&&(x=A),!x&&i&&(x=i.to-i.from+1);let R=0,$=x?new Uint8Array(x):new Uint8Array(0),w=!1,L=v=>{f?.unsubscribe(),w=!0,Kn(v)},T=za(h,async function*({done:v,value:E}){if(R===0&&this.lastRequestFirstBytes$.next(Ya()-b),h.aborted){f?.unsubscribe();return}if(!v&&E){if(l&&x)$.set(E,R),R+=E.byteLength;else{let W=new Uint8Array($.length+E.length);W.set($),W.set(E,$.length),$=W,R+=E.byteLength}r?.(new DataView($.buffer),R),yield y?.read().then(T,L)}}.bind(this));yield y?.read().then(T,L),f?.unsubscribe();let F=Ya(),M={failed:w,requestStartedAt:b,requestEndedAt:F,duration:F-b};return w?(d.error("endRequest",gr(M)),d.end(),null):(d.log("endRequest",gr(M)),d.end(),$.buffer)}.bind(this));this.fetchByteRangeRepresentation=za(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(c,s))),n=Math.min(n,0);let p=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!p)return null;let d=new DataView(p,r-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(p,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(p),segments:g}}.bind(this));this.fetchTemplateRepresentation=za(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}=zn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:Qy(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Xe(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:Ka.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ka.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ka.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ka.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ka.FATAL})}}},Kn=a=>{if(!Tt(a))throw a};var $t=(a,e,t)=>t*e+(1-t)*a,kc=(a,e)=>a.reduce((t,i)=>t+i,0)/e,zy=(a,e,t,i)=>{let r=0,s=t,n=kc(a,e),u=e<i?e:i;for(let o=0;o<u;o++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===u};import{isNullable as nC,ValueSubject as Yy}from"@vkontakte/videoplayer-shared";var Yt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Yy(e.initial),this.debounced$=new Yy(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new we(`raw_${t}`),this.smoothedSeries$=new we(`smoothed_${t}`),this.reportedSeries$=new we(`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 u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-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)&&(nC(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 Jn=class extends Yt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=$t(this.slow,e,this.params.emaAlphaSlow),this.fast=$t(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Zn=class extends Yt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=kc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=$t(this.emaSmoothed,e,this.params.emaAlpha);let i=zy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var eo=class extends Yt{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?$t(this.smoothed,t,this.params.emaAlpha):t}};var Mt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Jn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Zn({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 eo({initial:e,label:"liveEdgeDelay",...t})}};var Sr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as oC,ValueSubject as uC}from"@vkontakte/videoplayer-shared";var Xa=class a{constructor(e,t){this.currentRepresentation$=new uC(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!oC(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<n||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&qe(t.segmentReference))}};var io=C(at(),1);import{assertNever as ro}from"@vkontakte/videoplayer-shared";var Ky=(a,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:n}=V.video,u=(s.h264||s.h265)&&s.aac,o=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return a.filter(l=>{switch(l){case"DASH_SEP":return o&&i.mp4&&u;case"DASH_WEBM":return o&&i.webm&&s.vp9&&s.opus;case"DASH_WEBM_AV1":return o&&i.webm&&s.av1&&s.opus;case"DASH_STREAMS":return o&&(i.mp4&&u||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return o&&i.mp4&&u;case"DASH_LIVE_CMAF":return o&&i.mp4&&u&&i.cmaf;case"DASH_ONDEMAND":return o&&i.mp4&&u;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&s.h264&&(i.mp4||i.webm);default:return ro(l)}})},to=a=>{let{webmDecodingInfo:e}=V.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:ro(a)}return[t,i]},Xy=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...to(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(V.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",...to(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...to(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...to(a),...r,"HLS","HLS_ONDEMAND"];default:ro(e)}return V.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Jy=({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],u,o=V.device.isMac&&V.browser.isSafari;if(V.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{u=s;break}case"hls":case"mpeg":{u=n;break}default:ro(a)}else V.video.nativeHlsSupported&&!o?u=n:o?u=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:u=s;return t?["WEB_RTC_LIVE",...u]:[...u,"WEB_RTC_LIVE"]},Pc=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ao=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,io.default)(t.value.split("."),0)}for(let t of a){let i=(0,io.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,io.default)(e.value.split("."),0)};var bC=["timeupdate","progress","play","seeked","stalled","waiting"],gC=["timeupdate","progress","loadeddata","playing","seeked"];var oo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new tT;this.representationSubscription=new tT;this.state$=new O("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentAudioRepresentation$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new no;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.currentLiveTextRepresentation$=new ee(null);this.isLive$=new ee(!1);this.isActiveLive$=new ee(!1);this.isLowLatency$=new ee(!1);this.liveDuration$=new ee(0);this.liveSeekableDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(0);this.liveStreamStatus$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLatency$=new ee(void 0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.currentStallDuration$=new ee(0);this.videoLastDataObtainedTimestamp$=new ee(0);this.fetcherRecoverableError$=new no;this.fetcherError$=new no;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new no;this.gapWatchdogActive=!1;this.destroyController=new X;this.initManifest=Lc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ot.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Lc(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ot.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=jn(e??"",this.manifestUrlString)}catch(n){let u=qn(e)??{id:"ManifestParsing",category:ot.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(u)}if(!t)return null;let i=(n,u,o)=>!!(this.element?.canPlayType?.(u)&&Ue()?.isTypeSupported?.(`${u}; codecs="${o}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:u,streamIsUnpublished:o,streamIsAlive:l}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((u-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";l||(p=o?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let o=t.streams[n].filter(({mime:p,codecs:d})=>i(n,p,d)),l=new Set(o.map(({codecs:p})=>p)),c=ao(l);if(c&&(r[n]=o.filter(({codecs:p})=>p.startsWith(c))),n==="video"){let p=this.tuning.preferHDR,d=r.video.some(f=>f.hdr),h=r.video.some(f=>!f.hdr);V.display.isHDR&&p&&d?r.video=r.video.filter(f=>f.hdr):h&&(r.video=r.video.filter(f=>!f.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",Za(s)),s}.bind(this));this.initRepresentations=Lc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Za({initialVideo:e,initialAudio:t,sourceHls:i})),vr(this.manifest),vr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(Dt(d,"error").pipe(so(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:ot.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Sn():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ir())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}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},u=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new Wa("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],es(t)){let d=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Wa("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}Xa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Xa(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 o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ii(...gC.map(d=>Dt(this.element,d))).pipe(Tr(d=>this.element?pe(this.element.buffered,this.element.currentTime*1e3):0),Ja(),fC(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ii(Dt(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ja()).subscribe(h=>this.liveStreamEndTimestamp=Mc())),this.subscription.add(Dt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=$c(1e3).subscribe(h=>{let f=qt(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Dt(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(yr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Tr(({isActiveLive:h,isLowLatency:f})=>h&&f),Ja()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Sr(this.element,1)})),this.representationSubscription.add(yr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(so(({bufferLength:h,isActiveLive:f,isLowLatency:b})=>f&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(yr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(so(({isLive:h})=>h),Ja((h,f)=>f.bufferLength<h.bufferLength),Tr(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=qt(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(yr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=h-g;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(y)>S&&(x=1+Math.sign(y)*I),Sr(this.element,x)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add(yr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(mC(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,g=qt(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,A=isFinite(h)?h:f,R=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(R?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(L=>L.proceedLowLatencyLive()),w="active_low_latency"):g!==0&&A<I?w="live_forward_buffering":A<I+x&&(w="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),w==="live_forward_buffering"||w==="live_with_target_offset"){let L=d-(I+y),T=this.normolizeLiveOffset(Math.trunc(g+L/b)),F=Math.abs(T-g),M=0;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?M=g:T>0&&F>this.tuning.dashCmafLive.offsetCalculationError&&(M=T),this.manifestUrlString=se(this.manifestUrlString,M,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ot.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Ii(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Tr(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=Ii(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Tr(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),p=yr({allBuffersFull:l,someBufferEnded:c}).pipe(Ja(),Tr(({allBuffersFull:d,someBufferEnded:h})=>d&&h),so(d=>d));if(this.representationSubscription.add(Ii(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:ot.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(Ii(...this.bufferManagers.map(d=>d.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 d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ot.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,Dc.default)((0,Dc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),qe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&es(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=$c(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ot.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Xn({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=Mt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){vr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Mc()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=se(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){vr(this.element),this.state$.setState("running"),this.subscription.add(Ii(...bC.map(e=>Dt(this.element,e)),Dt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ot.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Dt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Dt(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Se(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=Mc(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=o<s&&r-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&l<s&&r-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||p)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let d=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(d).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:ot.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=d}else{let d=this.element.currentTime*1e3;this.videoBufferManager?.maintain(d),this.audioBufferManager?.maintain(d),i.position=d}this.tracer.log("stallIntervalCallback",Za(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=$c(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:ot.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),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?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){vr(this.element),vr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Se(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(eT(this.element)||eT(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Za({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){es(this.element)&&es(this.source)&&es(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=hC(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};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 u of this.bufferManagers)for(let o of u.gaps)u.playingRepresentation$.getValue()===o.representation&&o.from-n<=r&&o.to+n>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?s.push(1/0):s.push(o.to));if(s.length){let u=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:s,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Za(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var uo=class{constructor(e,t){this.fov=e,this.orientation=t}};var lo=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??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=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 rT=`attribute vec2 a_vertex;
125
125
  attribute vec2 a_texel;
126
126
 
127
127
  varying vec2 v_texel;
@@ -132,7 +132,7 @@ void main(void) {
132
132
  // save texel vector to pass to fragment shader
133
133
  v_texel = a_texel;
134
134
  }
135
- `;var UT=`#ifdef GL_ES
135
+ `;var aT=`#ifdef GL_ES
136
136
  precision highp float;
137
137
  precision highp int;
138
138
  #else
@@ -175,13 +175,6 @@ void main(void) {
175
175
  // sample using new coordinates
176
176
  gl_FragColor = texture2D(u_texture, tc);
177
177
  }
178
- `;var Fr=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 jo(this.params.fov,this.params.orientation),this.cameraRotationManager=new zo(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(NT,this.gl.VERTEX_SHADER),i=this.createShader(UT,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}};import{isNullable as n0,now as Sa,once as o0,Subscription as u0,ValueSubject as Td,isNonNullable as l0,safeStorage as Id,filterChanged as c0}from"@vkontakte/videoplayer-shared";var Qo="stalls_manager_metrics",xd="stalls_manager_abr_params",qT="stalls_manager_default_tuning_abr_params",Ed=class{constructor(){this.isSeeked$=new Td(!1);this.isBuffering$=new Td(!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 u0;this.severeStallOccurred$=new Td(!1)}init(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.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(xd):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Sa(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Sa()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(qT)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(xd),this.setStoredData(qT,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Qo,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,n)=>a+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(Qo,[]),this.setStoredData(xd,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),d=this.abrTuningParams;return e<i-r?d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(d={bitrateFactorAtEmptyBuffer:Math.min(d.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(d.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(d.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>a&&(d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor,this.abrParams.containerSizeFactor)}),d}getStoredData(e,t="{}"){return JSON.parse(Id.get(e)??t)}setStoredData(e,t){Id.set(e,JSON.stringify(t))}removeStoredData(e){Id.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Qo,"[]"),r=t/e,a=i.length?ii(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(Qo,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(o0()).subscribe(t=>this.providerStartWatchingTimestamp=Sa())),this.subscription.add(this.currentStallDuration$.pipe(c0()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(n0(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=Sa(),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,l0(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Sa()-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}))}},Go=Ed;import{combine as d0,map as p0,observeElementSize as h0,Subscription as f0,ValueSubject as wd,noop as m0}from"@vkontakte/videoplayer-shared";var Wo=class{constructor(){this.subscription=new f0;this.pipSize$=new wd(void 0);this.videoSize$=new wd(void 0);this.elementSize$=new wd(void 0);this.pictureInPictureWindowRemoveEventListener=m0}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(h0(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(d0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(p0(({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 zi=class{constructor(e){this.subscription=new I0;this.videoState=new U("stopped");this.observableVideo=null;this.droppedFramesManager=new wr;this.stallsManager=new Go;this.elementSizeManager=new Wo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new fi;this.audioTrackSwitchHistory=new fi;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.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?.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?.to==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return g0(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Fr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new bt(e.source.url),this.params=e,this.video=Ge(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($e(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 Ho({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;T0(this.observableVideo)&&(this.observableVideo=Ke(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:HT.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Pd(l=>!!l.length),zT()).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(kd(l=>l.to.state!=="none"),Yo());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),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(Pd(jT),zT()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(kd(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Dt(this.video,t.isLooped,r)),this.subscription.add(Ye(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(mt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(gt(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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(S0(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of d.audio){p.push(ad(h));let f=[];for(let b of h.representations){let g=gT(b);f.push(g),this.audioTracksMap.set(g,{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(nd(p));let h=[];for(let f of p.representations){let b=bT({...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=ST(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(Ko(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$,y0(this.video,"progress")).pipe(Pd(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,QT.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[p,h]=c,f=[...this.videoTracksMap.keys()].find(g=>this.videoTracksMap.get(g)?.representation.id===p.id);jT(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,g)}},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(Yo()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{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(nd(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Yo()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{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(ad(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(kd(({to:l})=>l==="ready"),Yo());this.subscription.add(Ko(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Ad(["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(Ko(o,this.player.state$.stateChangeEnded$,Ad(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Ko(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ad(["init"])).pipe(v0(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ws:Es,t=this.params.tuning.useNewAutoSelectVideoTrack?So:go,i=this.params.tuning.useNewAutoSelectVideoTrack?Ot:bo,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:v})=>v===o),d=a.currentVideoTrack$.getValue(),c=r.videoStream.getState()??(l&&this.videoTracksMap.get(l)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let p=[...this.videoStreamsMap.keys()].find(({id:v})=>v===c.id),h=p&&this.videoStreamsMap.get(p);if(!h)return;let f=Re(this.video.buffered,this.video.currentTime*1e3),b;this.player.isActiveLive$.getValue()?b=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?b=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:b=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(f/Math.min(b,g||1/0),1),T=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),y=[...this.audioStreamsMap.keys()].find(({id:v})=>v===T?.id)??this.audioStreamsMap.keys().next().value,E=0;if(y){if(l&&!n){let v=e(l,h,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);E=Math.max(E,v?.bitrate??-1/0)}if(d){let v=e(d,h,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);E=Math.max(E,v?.bitrate??-1/0)}}let w=i(h,{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:E,forwardBufferHealth:S,current:d,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}),L=n?w??l:l??w,O=y&&t(L,h,this.audioStreamsMap.get(y)??[],{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}),P=this.videoTracksMap.get(L)?.representation,k=O&&this.audioTracksMap.get(O)?.representation;if(P&&k)return[P,k];if(P&&!k&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Xe(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:HT.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),We(this.video),this.tracer.end()}};var va=class extends zi{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)}};import{combine as Rd,merge as GT,filter as WT,filterChanged as x0,isNullable as Md,map as YT,ValueSubject as Ld,isNonNullable as E0}from"@vkontakte/videoplayer-shared";var ya=class extends zi{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 Ld(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(YT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Rd({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(YT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(WT(o=>E0(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Rd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:GT(i.playbackRateState$,new Ld(1))}).pipe(WT(({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||Md(l)||(e=o-l)})).add(Rd({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:GT(i.playbackRateState$,new Ld(1))}).pipe(x0((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||Md(o)||Md(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=vT(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)})}};import{assertNever as bC,assertNonNullable as gC,debounce as SC,ErrorCategory as kI,filter as Zd,filterChanged as uu,fromEvent as vC,isNonNullable as AI,isNullable as yC,map as ep,merge as lu,observableFrom as tp,once as RI,Subscription as TC}from"@vkontakte/videoplayer-shared";var Xd=C(Ds(),1);import{abortable as Gd,assertNonNullable as jr,combine as zr,ErrorCategory as Lt,filter as su,filterChanged as Za,flattenObject as en,fromEvent as Ft,getTraceSubscriptionMethod as nC,interval as Wd,isNonNullable as tn,isNullable as wI,map as Qr,merge as Xi,now as Yd,Subject as au,Subscription as Kd,tap as oC,throttle as PI,ValueSubject as pe}from"@vkontakte/videoplayer-shared";var eu=C(dt(),1),qr=C(kt(),1),tu=C(Ds(),1);var yI=C(Wn(),1);import{assertNever as w0,ErrorCategory as KT,Subject as XT}from"@vkontakte/videoplayer-shared";var P0=18,JT=!1;try{JT=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=P0}catch(s){console.error(s)}var Bd=class{constructor(e){this.bufferFull$=new XT;this.error$=new XT;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:KT.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};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)};JT&&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(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:KT.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:w0(t)}}},ZT=Bd;import{abortable as yi,assertNonNullable as Ze,ErrorCategory as Yi,fromEvent as Hd,getExponentialDelay as jd,isNonNullable as Ur,isNullable as Ve,now as Zo,once as X0,Subject as J0,Subscription as Z0,ValueSubject as Ki}from"@vkontakte/videoplayer-shared";var Q=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 Nr=class extends Q{};var Ta=class extends Q{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 Ia=class extends Q{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 xa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ae=class extends Q{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Ea=class extends ae{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 wa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var Qi=class extends ae{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 ka=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Aa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ra=class extends ae{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 Ma=class extends ae{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var La=class extends ae{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Ba=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var $a=class extends ae{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 Da=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ca=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Va=class extends ae{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Oa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var _a=class extends ae{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 Fa=class extends ae{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 Na=class extends ae{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 Ua=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qa=class extends ae{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 Ha=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var A0={ftyp:Ia,moov:xa,mvhd:Ea,moof:wa,mdat:Pa,sidx:Qi,trak:ka,mdia:Ba,mfhd:Va,tkhd:$a,traf:Oa,tfhd:_a,tfdt:Fa,trun:Na,minf:Da,sv3d:Aa,st3d:Ra,prhd:Ma,proj:Ca,equi:La,uuid:Ta,stbl:Ua,stsd:qa,avc1:Ha,unknown:Nr},ai=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{break}return t}createBox(e,t){let i=A0[e];return i?new i(t,new s):new Nr(t,new s)}};var vi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var M0=new TextDecoder("ascii"),L0=s=>M0.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",B0=s=>{let e=new Qi(s,new ai),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})},$0=(s,e)=>{let i=new ai().parse(s),r=new vi(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)},D0=s=>{let t=new ai().parse(s),i=new vi(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},C0=s=>{let t=new ai().parse(s);return new vi(t).find("sidx")?.timescale},V0=(s,e)=>{let i=new ai().parse(s),a=new vi(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},O0=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 ai().parse(s),r=new vi(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},eI={validateData:L0,parseInit:O0,getIndexRange:()=>{},parseSegments:B0,parseFeedableSegmentChunk:$0,getChunkEndTime:V0,getServerLatencyTimestamps:D0,getTimescaleFromIndex:C0};var za=C(dt(),1);import{assertNonNullable as Dd,isNonNullable as sI,isNullable as F0}from"@vkontakte/videoplayer-shared";import{assertNever as _0}from"@vkontakte/videoplayer-shared";var tI={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"}},iI=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=ja(s,t),r=i in tI,a=r?tI[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=ja(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}},ja=(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},Mt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return ja(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(e)}},Gi=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=iI(i);if(!e(r))return;r.type==="master"&&Gi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},rI=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=iI(s);return Gi(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Mt(o,n):a===17026?t=Mt(o,n):a===17029&&(i=Mt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var aI=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],N0=[231,22612,22743,167,171,163,160,175],U0=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return Gi(s,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Mt(f,h);l=ja(g)}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=Mt(f,h):p===17545?r=Mt(f,h):p===21420&&l===475249515?u=Mt(f,h):p===374648427?Gi(f,({tag:g,type:S,value:T})=>g===30321?(d=Mt(T,S)===1,!1):!0):a&&n&&(0,za.default)(aI,p)&&(o=!0),!o}),Dd(e,"Failed to parse webm Segment start"),Dd(t,"Failed to parse webm Segment end"),Dd(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},q0=s=>{if(F0(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},H0=(s,e)=>{let t=!1,i=!1,r=o=>sI(o.time)&&sI(o.position),a=[],n;return Gi(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=Mt(l,u));break;case 183:break;case 241:n&&(n.position=Mt(l,u));break;default:t&&(0,za.default)(aI,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}}})},j0=s=>{let e=0,t=!1;try{Gi(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,za.default)(N0,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||=(0,za.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},nI={validateData:rI,parseInit:U0,getIndexRange:q0,parseSegments:H0,parseFeedableSegmentChunk:j0};var Qa=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return nI;case"mp4":return eI}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Nd=C(td(),1),bI=C(Mi(),1),gI=C(id(),1),SI=C(kt(),1),Ud=C(_i(),1);import{isNonNullable as W0,isNullable as fI}from"@vkontakte/videoplayer-shared";var oI=s=>{try{let e=z0(),t=s.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let a=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:a};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function z0(){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 Vd=C(kt(),1);import{videoSizeToQuality as Q0,throttleFn as G0}from"@vkontakte/videoplayer-shared";var uI=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?hi(a):void 0)??Q0({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},lI=({id:s,bitrate:e})=>({id:s,bitrate:e}),cI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),dI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Od=({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}),_d=({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)}),Fd=s=>"url"in s,ze=s=>s.type==="template",Ga=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var pI=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},Wi=(s,e)=>{for(let t of s)if(e(t))return t;return null},hI=s=>{let e=!1,t=G0(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var mI=s=>{if(!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?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},ni=(s,e)=>{let t=s;t=(0,Nd.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,bI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Nd.default)(t,n,(o,u)=>fI(a)?o:fI(u)?a:(0,gI.default)(a,parseInt(u,10),"0"))}return t},vI=(s,e)=>{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(k=>k.textContent?.trim()??""),o=(0,SI.default)(n,0)??"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],p=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={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 S,T=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],E=y.reduce((k,v)=>({...k,[v.id]:v.children}),{}),w=y.reduce((k,v)=>({...k,[v.id]:v.getAttribute("duration")}),{});T?S=mI(T):(0,Ud.default)(w).filter(k=>k).length&&!u?S=(0,Ud.default)(w).reduce((k,v)=>k+(mI(v)??0),0):b&&(S=parseInt(b,10));let L=0,O=a.getAttribute("profiles")?.split(",")??[];for(let k of y.map(v=>v.id))for(let v of E[k]){let D=v.getAttribute("id")??"id"+(L++).toString(10),I=v.getAttribute("mimeType")??"",x=v.getAttribute("codecs")??"",A=v.getAttribute("contentType")??I?.split("/")[0],re=v.getAttribute("profiles")?.split(",")??[],$=oI(v.getAttribute("lang")??"")??{},q=v.querySelector("Label")?.textContent?.trim()??void 0,X=v.querySelectorAll("Representation"),ne=v.querySelector("SegmentTemplate"),ge=v.querySelector("Role")?.getAttribute("value")??void 0,oe=A,Z={id:D,language:$.language,isDefault:ge==="main",label:q,codecs:x,hdr:oe==="video"&&Lr(x),mime:I,representations:[]};for(let M of X){let V=M.getAttribute("lang")??void 0,Ee=q??v.getAttribute("label")??M.getAttribute("label")??void 0,Se=M.querySelector("BaseURL")?.textContent?.trim()??"",te=new URL(Se||o,e).toString(),ye=M.getAttribute("mimeType")??I,et=M.getAttribute("codecs")??x??"",Oe;if(A==="text"){let ce=M.getAttribute("id")||"",tt=$.privateuse?.includes("x-auto")||ce.includes("_auto"),xe=M.querySelector("SegmentTemplate");if(xe){let vt={representationId:M.getAttribute("id")??void 0,bandwidth:M.getAttribute("bandwidth")??void 0},Nt=parseInt(M.getAttribute("bandwidth")??"",10)/1e3,Ut=parseInt(xe.getAttribute("startNumber")??"",10)??1,it=parseInt(xe.getAttribute("timescale")??"",10),Ei=xe.querySelectorAll("SegmentTimeline S")??[],rt=xe.getAttribute("media");if(!rt)continue;let qt=[],Ht=0,jt="",st=0,yt=Ut,W=0;for(let ue of Ei){let _e=parseInt(ue.getAttribute("d")??"",10),ie=parseInt(ue.getAttribute("r")??"",10)||0,we=parseInt(ue.getAttribute("t")??"",10);W=Number.isFinite(we)?we:W;let Fe=_e/it*1e3,at=W/it*1e3;for(let he=0;he<ie+1;he++){let Pe=ni(rt,{...vt,segmentNumber:yt.toString(10),segmentTime:(W+he*_e).toString(10)}),nt=(at??0)+he*Fe,It=nt+Fe;yt++,qt.push({time:{from:nt,to:It},url:Pe})}W+=(ie+1)*_e,Ht+=(ie+1)*Fe}st=W/it*1e3,jt=ni(rt,{...vt,segmentNumber:yt.toString(10),segmentTime:W.toString(10)});let Tt={time:{from:st,to:1/0},url:jt},Te={type:"template",baseUrl:te,segmentTemplateUrl:rt,initUrl:"",totalSegmentsDurationMs:Ht,segments:qt,nextSegmentBeyondManifest:Tt,timescale:it};Oe={id:ce,kind:"text",segmentReference:Te,profiles:[],duration:S,bitrate:Nt,mime:"",codecs:"",width:0,height:0,isAuto:tt}}else Oe={id:ce,isAuto:tt,kind:"text",url:te}}else{let ce=M.getAttribute("contentType")??ye?.split("/")[0]??A,tt=v.getAttribute("profiles")?.split(",")??[],xe=parseInt(M.getAttribute("width")??"",10),vt=parseInt(M.getAttribute("height")??"",10),Nt=parseInt(M.getAttribute("bandwidth")??"",10)/1e3,Ut=M.getAttribute("frameRate")??"",it=M.getAttribute("quality")??void 0,Ei=Ut?Po(Ut):void 0,rt=M.getAttribute("id")??"id"+(L++).toString(10),qt=ce==="video"?`${vt}p`:ce==="audio"?`${Nt}Kbps`:et,Ht=`${rt}@${qt}`,jt=[...O,...re,...tt],st,yt=M.querySelector("SegmentBase"),W=M.querySelector("SegmentTemplate")??ne;if(yt){let Te=M.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ue,_e]=Te.split("-").map(Pe=>parseInt(Pe,10)),ie={from:ue,to:_e},we=M.querySelector("SegmentBase")?.getAttribute("indexRange"),[Fe,at]=we?we.split("-").map(Pe=>parseInt(Pe,10)):[],he=we?{from:Fe,to:at}:void 0;st={type:"byteRange",url:te,initRange:ie,indexRange:he}}else if(W){let Te={representationId:M.getAttribute("id")??void 0,bandwidth:M.getAttribute("bandwidth")??void 0},ue=parseInt(W.getAttribute("timescale")??"",10),_e=W.getAttribute("initialization")??"",ie=W.getAttribute("media"),we=parseInt(W.getAttribute("startNumber")??"",10)??1,Fe=ni(_e,Te);if(!ie)throw new ReferenceError("No media attribute in SegmentTemplate");let at=W.querySelectorAll("SegmentTimeline S")??[],he=[],Pe=0,nt="",It=0;if(at.length){let zt=we,le=0;for(let ot of at){let fe=parseInt(ot.getAttribute("d")??"",10),Ne=parseInt(ot.getAttribute("r")??"",10)||0,Qt=parseInt(ot.getAttribute("t")??"",10);le=Number.isFinite(Qt)?Qt:le;let wi=fe/ue*1e3,Eu=le/ue*1e3;for(let Gt=0;Gt<Ne+1;Gt++){let wu=ni(ie,{...Te,segmentNumber:zt.toString(10),segmentTime:(le+Gt*fe).toString(10)}),Wr=(Eu??0)+Gt*wi,Pu=Wr+wi;zt++,he.push({time:{from:Wr,to:Pu},url:wu})}le+=(Ne+1)*fe,Pe+=(Ne+1)*wi}It=le/ue*1e3,nt=ni(ie,{...Te,segmentNumber:zt.toString(10),segmentTime:le.toString(10)})}else if(W0(S)){let le=parseInt(W.getAttribute("duration")??"",10)/ue*1e3,ot=Math.ceil(S/le),fe=0;for(let Ne=1;Ne<ot;Ne++){let Qt=ni(ie,{...Te,segmentNumber:Ne.toString(10),segmentTime:fe.toString(10)});he.push({time:{from:fe,to:fe+le},url:Qt}),fe+=le}It=fe,nt=ni(ie,{...Te,segmentNumber:ot.toString(10),segmentTime:fe.toString(10)})}let xu={time:{from:It,to:1/0},url:nt};st={type:"template",baseUrl:te,segmentTemplateUrl:ie,initUrl:Fe,totalSegmentsDurationMs:Pe,segments:he,nextSegmentBeyondManifest:xu,timescale:ue}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ce||!ye)continue;let Tt={video:"video",audio:"audio",text:"text"}[ce];if(!Tt)continue;oe||=Tt,Oe={id:Ht,kind:Tt,segmentReference:st,profiles:jt,duration:S,bitrate:Nt,mime:ye,codecs:et,width:xe,height:vt,fps:Ei,quality:it}}Z.language||=V,Z.label||=Ee,Z.mime||=ye,Z.codecs||=et,Z.hdr||=oe==="video"&&Lr(et),Z.representations.push(Oe)}if(oe){let M=r[oe].find(V=>V.id===Z.id);if(M&&Z.representations.every(V=>ze(V.segmentReference)))for(let V of M.representations){let Se=Z.representations.find(ye=>ye.id===V.id)?.segmentReference,te=V.segmentReference;te.segments.push(...Se.segments),te.nextSegmentBeyondManifest=Se.nextSegmentBeyondManifest}else r[oe].push(Z)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{fromEvent as Y0,Subscription as K0}from"@vkontakte/videoplayer-shared";var Xo=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 Jo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new K0;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(Y0(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!_(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Xo(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 Wa=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ki(0);this.currentLowLatencySegmentLength$=new Ki(0);this.currentSegmentLength$=new Ki(0);this.onLastSegment$=new Ki(!1);this.fullyBuffered$=new Ki(!1);this.playingRepresentation$=new Ki(void 0);this.playingRepresentationInit$=new Ki(void 0);this.error$=new J0;this.gaps=[];this.subscription=new Z0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ee;this.switchAbortController=new ee;this.destroyAbortController=new ee;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=yi(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ze(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new ZT(this.sourceBuffer),this.sourceBufferBufferedDiff=new Jo(this.mediaSource,this.sourceBuffer),this.subscription.add(Hd(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Hd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Yi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!_(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ar(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);Ze(i,"No init buffer for starting representation"),Ze(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=yi(this.destroyAbortController.signal,async function*(e,t=!1){if(!_(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ze(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ve(a)||Ve(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Ze(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!_(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();Ur(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=yi(this.destroyAbortController.signal,async function*(e,t=!1){if(!_(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ze(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ve(a)||Ve(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Ze(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!_(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();Ur(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=yi(this.destroyAbortController.signal,async function*(e){let t=(0,tu.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let d=this.representations.get(u);if(!d||!ze(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Ze(r);let a=this.segments.get(i);Ze(a,"No segments for starting representation");let n=this.initData.get(i);if(Ze(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));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!_(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ee,yi(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);Ze(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Ve(o)||Ve(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Ze(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!_(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();Ur(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(){!Ve(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 ee,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ve(e)||Ve(this.downloadingRepresentationId)||Ve(this.playingRepresentationId)||Ve(this.sourceBuffer)||!_(this.mediaSource,this.sourceBuffer)||Ur(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Ze(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);Ur(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(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)&&Ar(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?.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,eu.default)(u,r))d="high";else{let c=(0,qr.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?.length&&Re(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,qr.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;Ur(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,tu.default)(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?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,tu.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!ze(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,qr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ze(e);let t=this.segments.get(e);if(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(!ze(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=ni(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&_t&&_t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&_t&&_t(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.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=this.getForwardBufferDuration(i),a=e.findIndex(({status:p,time:{from:h,to:f}},b)=>{let g=h<=i&&f>=i,S=h>i||g||b===0&&i===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+T||r<T&&f-h>=T||f<=i+T;return(p==="none"||p==="partially_ejected"&&S&&y&&this.sourceBuffer&&_(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,f)))&&S&&y});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let p=a;p<n.length&&(o<=d||u<=c);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){ze(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 yi(o,async function*(){let d=jd(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=Zo(),!d)return;let c=new DataView(d),p=Qa(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]),Ga(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())ze(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 yi(n,async function*(){let u=jd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Hd(window,"online").pipe(X0()).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=Zo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ga(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ze(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,qr.default)(e,0).byte.from,to:(0,qr.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=Zo(),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:Yi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ze(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=Zo();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:Yi.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,eu.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!_(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=Qa(n.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!_(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),g=u.loadedBytes===p?b:Qa(o.mime).parseFeedableSegmentChunk(b);g?.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(Ve(this.sourceBuffer)||!_(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(De(this.sourceBuffer.buffered,e.segment.time.from,100)&&De(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Yi.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",Fd(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||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=kr(()=>(0,yI.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?yi(this.destroyAbortController.signal,async function*(){let o=jd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Qa(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&&ze(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:Yi.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||!_(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ve(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{if(a>=t)return;r.push({...o.time});let u=Fd(o)?o.size??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,eu.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=pI(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||!_(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||!_(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||!_(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||!_(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ve(e)?0:Re(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!_(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||!_(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=kr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Yi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ve(this.sourceBuffer)||!_(this.mediaSource,this.sourceBuffer)||Ve(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Xo(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:Yi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as Ya,assertNever as TI,fromEvent as II,merge as eC,now as Ka,Subject as xI,ValueSubject as zd,flattenObject as Hr,ErrorCategory as Xa,SubscriptionRemovable as tC}from"@vkontakte/videoplayer-shared";var ru=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new zd(void 0);this.lastConnectionReused$=new zd(void 0);this.lastRequestFirstBytes$=new zd(void 0);this.recoverableError$=new xI;this.error$=new xI;this.abortAllController=new ee;this.subscription=new tC;this.fetchManifest=Ya(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=gi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Lo(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(iu);return r?(t.log("success",Hr({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Hr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ya(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}={}){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 I=new URL(l,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),l=I.toString();break}default:TI(t)}this.requestQuic&&(l=gi(l));let p=this.abortAllController.signal,h;if(n){let I=new ee;if(h=eC(II(this.abortAllController.signal,"abort"),II(n,"abort")).subscribe(()=>{try{I.abort()}catch(x){iu(x)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(x){iu(x)}p=I.signal}let f=Ka();c.log("startRequest",Hr({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let b=yield this.doFetch(l,{priority:a,headers:d,signal:p}),g=Ka();if(!b)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(h),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){this.unsubscribeAbortSubscription(h);let I=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:I}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let I=Ka(),x={requestStartedAt:f,requestEndedAt:I,duration:I-f};return c.log("endRequest",Hr(x)),c.end(),b.arrayBuffer()}let S=b.body;if(o){let I;[S,I]=b.body.tee(),this.throughputEstimator?.trackStream(I,u)}let T=S.getReader(),y,E=parseInt(b.headers.get("content-length")??"",10);Number.isFinite(E)&&(y=E),!y&&i&&(y=i.to-i.from+1);let w=0,L=y?new Uint8Array(y):new Uint8Array(0),O=!1,P=I=>{this.unsubscribeAbortSubscription(h),O=!0,iu(I)},k=Ya(p,async function*({done:I,value:x}){if(w===0&&this.lastRequestFirstBytes$.next(Ka()-f),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!I&&x){if(y)L.set(x,w),w+=x.byteLength;else{let A=new Uint8Array(L.length+x.length);A.set(L),A.set(x,L.length),L=A,w+=x.byteLength}r?.(new DataView(L.buffer),w),yield T?.read().then(k,P)}}.bind(this));yield T?.read().then(k,P),this.unsubscribeAbortSubscription(h);let v=Ka(),D={failed:O,requestStartedAt:f,requestEndedAt:v,duration:v-f};return O?(c.error("endRequest",Hr(D)),c.end(),null):(c.log("endRequest",Hr(D)),c.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ya(this.abortAllController.signal,async function*(e,t,i){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=e.indexRange??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 S=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ya(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}=Mo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:TI(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await St(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:Xa.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Xa.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Xa.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Xa.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Xa.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},iu=s=>{if(!Ga(s))throw s};import{isNullable as iC,ValueSubject as rC}from"@vkontakte/videoplayer-shared";var Ja=class s{constructor(e,t){this.currentRepresentation$=new rC(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!iC(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&ze(t.segmentReference))}};var uC=["progress","play","seeked","stalled","waiting"],lC=["timeupdate","progress","loadeddata","playing","seeked"];var nu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Kd;this.representationSubscription=new Kd;this.state$=new U("none");this.currentVideoRepresentation$=new pe(void 0);this.currentVideoRepresentationInit$=new pe(void 0);this.currentAudioRepresentation$=new pe(void 0);this.currentVideoSegmentLength$=new pe(0);this.currentAudioSegmentLength$=new pe(0);this.error$=new au;this.lastConnectionType$=new pe(void 0);this.lastConnectionReused$=new pe(void 0);this.lastRequestFirstBytes$=new pe(void 0);this.currentLiveTextRepresentation$=new pe(null);this.isLive$=new pe(!1);this.isActiveLive$=new pe(!1);this.isLowLatency$=new pe(!1);this.liveDuration$=new pe(0);this.liveSeekableDuration$=new pe(0);this.liveAvailabilityStartTime$=new pe(0);this.liveStreamStatus$=new pe(void 0);this.bufferLength$=new pe(0);this.liveLatency$=new pe(void 0);this.liveLoadBufferLength$=new pe(0);this.livePositionFromPlayer$=new pe(0);this.currentStallDuration$=new pe(0);this.videoLastDataObtainedTimestamp$=new pe(0);this.fetcherRecoverableError$=new au;this.fetcherError$=new au;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new au;this.gapWatchdogActive=!1;this.destroyController=new ee;this.initManifest=Gd(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=be(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Lt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Gd(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Lt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=vI(e??"",this.manifestUrlString)}catch(n){let o=wo(e)??{id:"ManifestParsing",category:Lt.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&ht()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((o-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let c="active";l||(c=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(c)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:c,codecs:p})=>i(n,c,p)),l=new Set(u.map(({codecs:c})=>c)),d=No(l);if(d&&(r[n]=u.filter(({codecs:c})=>c.startsWith(d))),n==="video"){let c=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),h=r.video.some(f=>!f.hdr);F.display.isHDR&&c&&p?r.video=r.video.filter(f=>f.hdr):h&&(r.video=r.video.filter(f=>!f.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",en(a)),a}.bind(this));this.initRepresentations=Gd(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",en({initialVideo:e,initialAudio:t,sourceHls:i})),jr(this.manifest),jr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Kd,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Ft(p,"error").pipe(su(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:Lt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?eo():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&vr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.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((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Wa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],tn(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Wa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ja.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ja(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=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Xi(...lC.map(p=>Ft(this.element,p))).pipe(Qr(p=>this.element?Re(this.element.buffered,this.element.currentTime*1e3):0),Za(),oC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Xi(Ft(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Za()).subscribe(h=>this.liveStreamEndTimestamp=Yd())),this.subscription.add(Ft(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Wd(1e3).subscribe(h=>{let f=di(this.manifestUrlString,2);this.manifestUrlString=be(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ft(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(zr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Qr(({isActiveLive:h,isLowLatency:f})=>h&&f),Za()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Cr(this.element,1)})),this.representationSubscription.add(zr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(su(({bufferLength:h,isActiveLive:f,isLowLatency:b})=>f&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(zr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(su(({isLive:h})=>h),Za((h,f)=>f.bufferLength<h.bufferLength),Qr(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=di(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(zr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=h-g;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(y)>S&&(E=1+Math.sign(y)*T),Cr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(zr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(PI(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,g=di(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,w=isFinite(h)?h:f,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let P="none";if(L?P="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(k=>k.proceedLowLatencyLive()),P="active_low_latency"):g!==0&&w<T?P="live_forward_buffering":w<T+E&&(P="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),P==="live_forward_buffering"||P==="live_with_target_offset"){let k=p-(T+y),v=this.normolizeLiveOffset(Math.trunc(g+k/b)),D=Math.abs(v-g),I=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?I=g:v>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(I=v),this.manifestUrlString=be(this.manifestUrlString,I,2)}(P==="live_with_target_offset"||P==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:Lt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Xi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Qr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Xi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Qr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=zr({allBuffersFull:l,someBufferEnded:d}).pipe(Za(),Qr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),su(p=>p));if(this.representationSubscription.add(Xi(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:Lt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(Xi(...this.bufferManagers.map(p=>p.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 p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{p&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:Lt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[this.manifest.duration??0,...(0,Xd.default)((0,Xd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),ze(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&tn(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Wd(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Lt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ru({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=ri.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){jr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Yd()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=be(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){jr(this.element),this.state$.setState("running");let e=Ft(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(PI(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Xi(...uC.map(t=>Ft(this.element,t)),Ft(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Lt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Ft(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(Ft(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&De(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=Yd(),n=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,d=this.audioBufferManager?.getForwardBufferDuration()??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 h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(f=>{this.error$.next({id:"stallIntervalCallback",category:Lt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:f})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",en(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Wd(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:Lt.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?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){jr(this.element),jr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),De(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(wI(this.element)||wI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",en({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){tn(this.element)&&tn(this.source)&&tn(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=nC(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(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.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",en({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};import{combine as cC,map as dC,observeElementSize as pC,Subscription as hC,ValueSubject as Jd,noop as fC}from"@vkontakte/videoplayer-shared";var ou=class{constructor(){this.subscription=new hC;this.pipSize$=new Jd(void 0);this.videoSize$=new Jd(void 0);this.elementSize$=new Jd(void 0);this.pictureInPictureWindowRemoveEventListener=fC}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(pC(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(cC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(dC(({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 Ji=class{constructor(e){this.subscription=new TC;this.videoState=new U("stopped");this.observableVideo=null;this.droppedFramesManager=new wr;this.stallsManager=new Go;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 fi;this.audioTrackSwitchHistory=new fi;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?.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?.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?.to==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return bC(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Fr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new bt(e.source.url),this.params=e,this.video=Ge(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($e(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 nu({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;yC(this.observableVideo)&&(this.observableVideo=Ke(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:kI.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Zd(c=>!!c.length),RI()).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(ep(c=>c.to.state!=="none"),uu());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),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(Zd(AI),RI()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(ep(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Dt(this.video,t.isLooped,r)),this.subscription.add(Ye(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(mt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(gt(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:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams();if(gC(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of p.audio){f.push(Od(b));let g=[];for(let S of b.representations){let T=lI(S);g.push(T),this.audioTracksMap.set(T,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let h=[];for(let f of p.video){h.push(_d(f));let b=[];for(let g of f.representations){let S=uI({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(h);for(let f of p.text)for(let b of f.representations){let g=cI(f,b);this.textTracksMap.set(g,{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&&hI(o)||null;this.subscription.add(lu(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$,vC(this.video,"progress")).pipe(Zd(()=>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=Wi(this.videoTracksMap.keys(),S=>this.videoTracksMap.get(S)?.representation.id===h.id);AI(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")await this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},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(uu()).subscribe(c=>{let p=Wi(this.videoTracksMap.entries(),([,{representation:g}])=>g.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(_d(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(uu()).subscribe(c=>{let p=Wi(this.audioTracksMap.entries(),([,{representation:g}])=>g.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(Od(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(ep(({to:c})=>c==="ready"),uu());this.subscription.add(lu(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,tp(["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(lu(l,this.player.state$.stateChangeEnded$,tp(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=lu(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,tp(["init"])).pipe(SC(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ws:Es,t=this.params.tuning.useNewAutoSelectVideoTrack?So:go,i=this.params.tuning.useNewAutoSelectVideoTrack?Ot:bo,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=Wi(this.videoTracksMap.keys(),P=>P.id===o),l=a.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=Wi(this.videoStreamsMap.keys(),P=>P.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,g=Math.min(h/Math.min(f,b||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),T=S?.id&&Wi(this.audioStreamsMap.keys(),P=>P.id===S.id)||this.audioStreamsMap.keys().next().value,y=0;if(T){if(u&&!n){let P=e(u,p,this.audioStreamsMap.get(T)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,P?.bitrate??-1/0)}if(l){let P=e(l,p,this.audioStreamsMap.get(T)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,P?.bitrate??-1/0)}}let E=u;(n||!E)&&(E=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:y,forwardBufferHealth:g,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=T&&t(E,p,this.audioStreamsMap.get(T)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),L=this.videoTracksMap.get(E)?.representation,O=w&&this.audioTracksMap.get(w)?.representation;L&&O?(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=O):L&&!O&&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(){Xe(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:kI.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),We(this.video),this.tracer.end()}};var rn=class extends Ji{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)}};import{combine as ip,merge as MI,filter as LI,filterChanged as IC,isNullable as rp,map as BI,ValueSubject as sp,isNonNullable as xC}from"@vkontakte/videoplayer-shared";var sn=class extends Ji{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 sp(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(BI(o=>o.to)).subscribe(this.player.isLowLatency$)).add(ip({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(BI(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(LI(o=>xC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(ip({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:MI(i.playbackRateState$,new sp(1))}).pipe(LI(({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||rp(l)||(e=o-l)})).add(ip({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:MI(i.playbackRateState$,new sp(1))}).pipe(IC((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||rp(o)||rp(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=dI(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 $I="X-Playback-Duration",ap=async s=>{let e=await St(s),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has($I)?parseInt(e.headers.get($I),10):void 0};import{assertNever as DC,combine as CC,debounce as VC,ErrorCategory as pu,filter as OC,filterChanged as _C,isNonNullable as VI,isNullable as hu,map as OI,merge as FC,observableFrom as NC,Subscription as UC,ValueSubject as up,VideoQuality as qC}from"@vkontakte/videoplayer-shared";var op=C(Dl(),1);import{videoSizeToQuality as EC,getExponentialDelay as wC}from"@vkontakte/videoplayer-shared";var PC=s=>{let e=null;if(s.QUALITY&&(e=hi(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=EC({width:t,height:i})}return e??null},kC=(s,e)=>{let t=s.split(`
186
- `),i=[],r=[];for(let a=0;a<t.length;a++){let n=t[a],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,op.default)(o[1].split(",").map(g=>g.split("="))),d=l.QUALITY??`stream-${l.BANDWIDTH}`,c=PC(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[g,S]=l.RESOLUTION.split("x").map(T=>parseInt(T,10));g&&S&&(f={width:g,height:S})}let b=new URL(t[++a],e).toString();c&&i.push({id:d,quality:c,url:b,bandwidth:p,size:f,fps:h})}if(u){let l=(0,op.default)(u[1].split(",").map(h=>{let f=h.indexOf("=");return[h.substring(0,f),h.substring(f+1)]}).map(([h,f])=>[h,f.replace(/^"|"$/g,"")])),d=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,p=l.NAME;d&&c&&r.push({type:"internal",id:c,label:p,language:c,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},AC=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),np=0,DI=async(s,e=s,t,i)=>{let a=await(await St(s,i)).text();np+=1;try{let{qualityManifests:n,textTracks:o}=kC(a,e);return{qualityManifests:n,textTracks:o}}catch{if(np<=t.manifestRetryMaxCount)return await AC(wC(np-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),DI(s,e,t)}return{qualityManifests:[],textTracks:[]}},cu=DI;import{isNonNullable as RC,Subscription as MC,throttle as LC,ValueSubject as CI,Subject as BC,ErrorCategory as $C}from"@vkontakte/videoplayer-shared";var du=class{constructor(e,t,i,r,a){this.subscription=new MC;this.abortControllers={destroy:new ee,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new CI(null);this.getCurrentTime$=new CI(null);this.error$=new BC;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(LC(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 St(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(RC(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 ee;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:$C.WTF,thrown:t,message:e})}};var an=class{constructor(e){this.subscription=new UC;this.videoState=new U("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new up([]);this.liveOffset=new Fi;this.manifestStartTime$=new up(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"),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(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?.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?.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 d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else r?.to==="paused"&&(R(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return DC(t)}};this.params=e,this.video=Ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:qC.INVARIANT,url:this.params.source.url};let t=(i,r)=>cu(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new du(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new bt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:pu.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:pu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next($e(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new up(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:pu.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ke(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(Ye(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(mt(this.video,t.playbackRate,r.playbackRateState$,i)),a(gt(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"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(_C(),OI(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&&VI(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($e(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(CC({startTime:this.manifestStartTime$.pipe(OC(VI)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(OI(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=FC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,NC(["init"])).pipe(VC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),We(this.video)}prepare(){let e=this.selectManifest();if(hu(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=be(r.toString(),this.liveOffset.getTotalOffset(),a);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),ap(n).then(o=>{if(!hu(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(hu(u)||!isFinite(u))&&St(n).then(l=>l.text()).then(l=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(d){let c=new URL(d,n).toString();ap(c).then(p=>{hu(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){Xe(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:pu.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=be(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}};import{assertNever as HC,debounce as jC,ErrorCategory as lp,fromEvent as cp,isNonNullable as zC,isNullable as QC,map as _I,merge as FI,observableFrom as NI,Subscription as GC,ValueSubject as WC,VideoQuality as YC}from"@vkontakte/videoplayer-shared";var nn=class{constructor(e){this.subscription=new GC;this.videoState=new U("stopped");this.manifests$=new WC([]);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"),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(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?.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?.to==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&R(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return HC(t)}};this.textTracksManager=new bt(e.source.url),this.params=e,this.video=Ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:YC.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($e(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),cu(be(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:lp.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"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(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:lp.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ke(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(_I(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Dt(this.video,t.isLooped,i)),this.subscription.add(Ye(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(mt(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(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&zC(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next($e(f.url)))}let c=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(c!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(_I(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)),!F.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(FI(cp(o,"addtrack"),cp(o,"removetrack"),cp(o,"change"),NI(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=FI(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,NI(["init"])).pipe(jC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),We(this.video)}prepare(){let e=this.selectManifest();if(QC(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:a,min:n}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Xe(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:lp.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var HI=C(Mi(),1),dp=C(_i(),1),jI=C(kt(),1);import{assertNever as KC,assertNonNullable as UI,debounce as XC,ErrorCategory as qI,isHigherOrEqual as JC,isLowerOrEqual as ZC,isNonNullable as eV,merge as tV,observableFrom as iV,Subscription as rV,map as sV}from"@vkontakte/videoplayer-shared";var on=class{constructor(e){this.subscription=new rV;this.videoState=new U("stopped");this.trackUrls={};this.textTracksManager=new bt;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 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?.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?.to==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return KC(e)}};this.params=e,this.video=Ge(e.container,e.tuning),this.params.output.element$.next(this.video),(0,HI.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,dp.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:qI.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ke(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(sV(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Dt(this.video,t.isLooped,i)),this.subscription.add(Ye(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(mt(this.video,t.playbackRate,r.playbackRateState$,i)),a(gt(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(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&eV(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=tV(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,iV(["init"])).pipe(XC(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),We(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;UI(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];UI(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=gi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next($e(t))}playIfAllowed(){Xe(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:qI.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let d=Ot(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(d)},r=this.params.output.currentVideoTrack$.getValue()?.quality,a=!!(e.max||e.min),n=(0,dp.default)(this.trackUrls).map(l=>l.track);if(!r||!a||yr(e,n[0].quality,(0,jI.default)(n,-1)?.quality)){i();return}let o=e.max?ZC(r,e.max):!0,u=e.min?JC(r,e.min):!0;o&&u||i(e)}};import{assertNever as QI,debounce as uV,merge as GI,observableFrom as lV,Subscription as cV,map as WI,ValueSubject as dV,ErrorCategory as hp,VideoQuality as pV}from"@vkontakte/videoplayer-shared";import{ErrorCategory as aV}from"@vkontakte/videoplayer-shared";var zI=["stun:videostun.mycdn.me:80"],nV=1e3,oV=3,pp=()=>null,fu=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=pp;this.externalStopCallback=pp;this.externalErrorCallback=pp;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:zI}]};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:aV.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),nV)}normalizeOptions(e={}){let t={stunServerList:zI,maxRetryNumber:oV,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var un=class{constructor(e){this.videoState=new U("stopped");this.maxSeekBackTime$=new dV(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 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"),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?.to==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return QI(e)}};this.subscription=new cV,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ge(e.container,e.tuning),this.liveStreamClient=new fu(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),We(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:hp.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(GI(this.videoState.stateChangeStarted$.pipe(WI(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(WI(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Ke(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(gt(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ye(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 QI(n.to)}},i)).add(GI(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,lV(["init"])).pipe(uV(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($e(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:pV.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:hp.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Xe(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:hp.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ln=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}};import{assertNever as cn,assertNonNullable as Ti,ErrorCategory as mu,filter as ex,isNonNullable as tx,isNullable as vV,map as yV,merge as TV,once as IV,Subject as Me,Subscription as ix,ValueSubject as H,flattenObject as fp}from"@vkontakte/videoplayer-shared";import{Observable as hV,map as YI,Subscription as fV,Subject as mV}from"@vkontakte/videoplayer-shared";var KI=s=>new hV(e=>{let t=new fV,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(YI(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(YI(({type:l})=>l!==void 0)),n=new mV,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()}});import{ErrorCategory as bV,Subscription as gV,combine as SV,filter as JI,once as ZI}from"@vkontakte/videoplayer-shared";function XI(){return new(window.AudioContext||window.webkitAudioContext)}var Gr=class s{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ee;this.subscriptions=new gV;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(JI(a=>!!a.type),ZI()).subscribe(({type:a})=>this.subscribe(a)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){F.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(SV({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(JI(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),ZI()).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=XI();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){this.volumeMultiplierError$.next({id:s.errorId,category:bV.VIDEO_PIPELINE,message:e?.message??`${s.errorId} exception`,thrown:e})}};var xV={chunkDuration:5e3,maxParallelRequests:5},dn=class{constructor(e){this.current$=new H({type:void 0});this.providerError$=new Me;this.noAvailableProvidersError$=new Me;this.volumeMultiplierError$=new Me;this.providerOutput={position$:new H(0),duration$:new H(1/0),volume$:new H({muted:!1,volume:1}),availableVideoStreams$:new H([]),currentVideoStream$:new H(void 0),availableVideoTracks$:new H([]),currentVideoTrack$:new H(void 0),availableAudioStreams$:new H([]),currentAudioStream$:new H(void 0),availableAudioTracks$:new H([]),currentVideoSegmentLength$:new H(0),currentAudioSegmentLength$:new H(0),isAudioAvailable$:new H(!0),autoVideoTrackLimitingAvailable$:new H(!1),autoVideoTrackLimits$:new H(void 0),currentBuffer$:new H(void 0),isBuffering$:new H(!0),error$:new Me,fetcherError$:new Me,fetcherRecoverableError$:new Me,warning$:new Me,willSeekEvent$:new Me,soundProhibitedEvent$:new Me,seekedEvent$:new Me,loopedEvent$:new Me,endedEvent$:new Me,firstBytesEvent$:new Me,loadedMetadataEvent$:new Me,firstFrameEvent$:new Me,canplay$:new Me,isLive$:new H(void 0),isLiveEnded$:new H(null),isLowLatency$:new H(!1),canChangePlaybackSpeed$:new H(!0),liveTime$:new H(void 0),liveBufferTime$:new H(void 0),liveLatency$:new H(void 0),severeStallOccurred$:new Me,availableTextTracks$:new H([]),currentTextTrack$:new H(void 0),hostname$:new H(void 0),httpConnectionType$:new H(void 0),httpConnectionReused$:new H(void 0),inPiP$:new H(!1),inFullscreen$:new H(!1),element$:new H(void 0),elementVisible$:new H(!0),availableSources$:new H(void 0),is3DVideo$:new H(!1),playbackState$:new H(""),getCurrentTime$:new H(null)};this.subscription=new ix;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=$T([...CT(this.params.tuning),...DT(this.params.tuning)],this.params.tuning).filter(l=>tx(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,mp.default)(r,l)),...t.filter(l=>(0,mp.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",fp(a)),this.screenFormatsIterator=new ln(a);let n=[...md(!0),...md(!1)];this.chromecastFormatsIterator=new ln(n.filter(l=>tx(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Gr.isSupported()&&(this.volumeMultiplierManager=new Gr(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(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(vV(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:mu.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 cn(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 Ti(u),this.params.tuning.useNewDashProvider?new rn({...o,source:u,sourceHls:l}):new va({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Ti(u),this.params.tuning.useNewDashProvider?new sn({...o,source:u}):new ya({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Ti(u),new nn({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Ti(u),new an({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Ti(u),new on({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Ti(u),new $v({...o,source:u,config:{...xV,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Ti(u),new un({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 cn(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 Ti(o),new Ss({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 cn(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return cn(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 cn(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,sx.default)((0,rx.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new ix,t=!1,i=0;return e.add(TV(this.providerOutput.error$.pipe(ex(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),KI({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(yV(r=>({id:`ProviderHangup:${r}`,category:mu.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(ex(({to:a})=>a==="playing"),IV()).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===mu.NETWORK,u=r.category===mu.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??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",fp(n)):this.tracer.error("providerError",fp(n))})),e}};import{fromEvent as bu,once as EV,combine as wV,Subscription as ax,ValueSubject as bp,map as PV,filter as kV,isNonNullable as gu,now as ft,safeStorage as gp}from"@vkontakte/videoplayer-shared";var AV=5e3,nx="one_video_throughput",ox="one_video_rtt",pn=window.navigator.connection,ux=()=>{let s=pn?.downlink;if(gu(s)&&s!==10)return s*1e3},lx=()=>{let s=pn?.rtt;if(gu(s)&&s!==3e3)return s},cx=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Sp=class s{constructor(e){this.subscription=new ax;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=s.load(nx)||(e.useBrowserEstimation?ux():void 0)||AV,i=s.load(ox)??(e.useBrowserEstimation?lx():void 0)??0;if(this.throughput$=new bp(t),this.rtt$=new bp(i),this.rttAdjustedThroughput$=new bp(cx(t,i,e.rttPenaltyRequestSize)),this.throughput=ri.getSmoothedValue(t,-1,e),this.rtt=ri.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=ux();n&&this.throughput.next(n);let o=lx();gu(o)&&this.rtt.next(o)};pn&&"onchange"in pn&&this.subscription.add(bu(pn,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{gp.set(nx,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{gp.set(ox,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(wV({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(PV(({throughput:r,rtt:a})=>cx(r,a,e.rttPenaltyRequestSize)),kV(r=>{let a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=ft(),r=new ax;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(bu(e,"progress").pipe(EV()).subscribe(a=>{t=a.loaded,i=ft()}));break;case 1:case 0:r.add(bu(e,"loadstart").subscribe(()=>{t=0,i=ft()}));break}r.add(bu(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=ft(),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=ft(),n=0,o=ft(),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,ft()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=ft();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=ft()}else n+=c.byteLength;o=ft()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ft()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ft()-o,this.concurrentDownloads.size),n=0,o=ft());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),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){let t=gp.get(e);if(gu(t))return parseInt(t,10)??void 0}},dx=Sp;import{fillWithDefault as RV,VideoQuality as Su}from"@vkontakte/videoplayer-shared";var px={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:Su.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Su.Q_720P,trafficSavingLimit:Su.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,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:Su.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,vktvAbrThrottle:0,timeupdateEventTickThrottle:300},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,changePlaybackStateToPausedWhenEnded:!1},hx=s=>({...RV(s,px),configName:[...s.configName??[],...px.configName]});import{assertNonNullable as vu,combine as oi,ErrorCategory as yu,filter as N,filterChanged as Y,fromEvent as yp,isNonNullable as gx,isNullable as VV,Logger as OV,map as G,mapTo as Sx,merge as Ii,now as Tu,once as j,Subject as K,Subscription as vx,tap as Tp,ValueSubject as B,isHigher as _V,isInvariantQuality as yx,flattenObject as xi,throttle as Ip,getTraceSubscriptionMethod as Tx,TracerFactory as FV,InternalsExposure as NV}from"@vkontakte/videoplayer-shared";import{merge as MV,map as LV,filter as fx,isNonNullable as BV}from"@vkontakte/videoplayer-shared";var vp=({seekState:s,position$:e})=>MV(s.stateChangeEnded$.pipe(LV(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),fx(BV)),e.pipe(fx(()=>s.getState().state==="none")));import{assertNonNullable as $V}from"@vkontakte/videoplayer-shared";var mx=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return $V(e,`Wrong container or containerId {${s.container}}`),e};import{filter as DV,once as CV}from"@vkontakte/videoplayer-shared";var bx=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(DV(r=>r.length>0),CV()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t?.getValue().find(i))&&e.startTransitionTo(s)};var Iu=class{constructor(e={configName:[]},t=FV.createRootTracer(!1)){this.subscription=new vx;this.logger=new OV;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new B(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new B(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new U("stopped"),seekState:new U({state:"none"}),volume:new U({volume:1,muted:!1}),videoTrack:new U(void 0),videoStream:new U(void 0),audioStream:new U(void 0),autoVideoTrackSwitching:new U(!0),autoVideoTrackLimits:new U({}),isLooped:new U(!1),isLowLatency:new U(!1),playbackRate:new U(1),externalTextTracks:new U([]),internalTextTracks:new U([]),currentTextTrack:new U(void 0),textTrackCuesSettings:new U({}),cameraOrientation:new U({x:0,y:0})};this.info={playbackState$:new B(void 0),position$:new B(0),duration$:new B(1/0),muted$:new B(!1),volume$:new B(1),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableQualities$:new B([]),availableQualitiesFps$:new B({}),currentQuality$:new B(void 0),isAutoQualityEnabled$:new B(!0),autoQualityLimitingAvailable$:new B(!1),autoQualityLimits$:new B({}),predefinedQualityLimitType$:new B("unknown"),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),isAudioAvailable$:new B(!0),currentPlaybackRate$:new B(1),currentBuffer$:new B({start:0,end:0}),isBuffering$:new B(!0),isStalled$:new B(!1),isEnded$:new B(!1),isLooped$:new B(!1),isLive$:new B(void 0),isLiveEnded$:new B(null),canChangePlaybackSpeed$:new B(void 0),atLiveEdge$:new B(void 0),atLiveDurationEdge$:new B(void 0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),currentFormat$:new B(void 0),availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),throughputEstimation$:new B(void 0),rttEstimation$:new B(void 0),videoBitrate$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),surface$:new B("none"),chromecastState$:new B("NOT_AVAILABLE"),chromecastDeviceName$:new B(void 0),intrinsicVideoSize$:new B(void 0),availableSources$:new B(void 0),is3DVideo$:new B(!1),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0)};this.events={inited$:new K,ready$:new K,started$:new K,playing$:new K,paused$:new K,stopped$:new K,willReady$:new K,willStart$:new K,willResume$:new K,willPause$:new K,willStop$:new K,willDestruct$:new K,watchCoverageRecord$:new K,watchCoverageLive$:new K,managedError$:new K,fatalError$:new K,fetcherRecoverableError$:new K,ended$:new K,looped$:new K,seeked$:new K,willSeek$:new K,autoplaySoundProhibited$:new K,firstBytes$:new K,loadedMetadata$:new K,firstFrame$:new K,canplay$:new K,log$:new K,fetcherError$:new K,severeStallOccured$:new K};this.experimental={element$:new B(void 0),tuningConfigName$:new B([]),enableDebugTelemetry$:new B(!1),dumpTelemetry:av,getCurrentTime$:new B(null)};if(this.initLogs(),this.tuning=hx(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new yn({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new dx(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new NV("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,Ix.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:yu.WTF,message:c,thrown:u}),u}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:a,...n}=e;this.tracer.log("initVideo",xi(n)),this.domContainer=mx(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new dn({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],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.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?F.isInited$.pipe(N(a=>!!a),j()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),yp(document,"visibilitychange").pipe(j()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(N(e=>!!e),j()).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(N(e=>!!e),j()).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(N(e=>!!e),j()).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(N(e=>!!e),j()).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(N(i=>!!i),j()).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(N(t=>!!t),j()).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(N(i=>!!i),j()).subscribe(()=>{let i=this.desiredState.volume,a=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=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,t=!1){return this.subscription.add(this.playerInited.pipe(N(i=>!!i),j()).subscribe(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,n=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(N(t=>!!t),j()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(N(t=>!!t),j()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(N(t=>!!t),j()).subscribe(()=>{vu(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(N(i=>i.length>0),j()).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(N(t=>!!t),j()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(N(t=>!!t),j()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",xi(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(N(t=>!!t),j()).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(N(t=>!!t),j()).subscribe(()=>{vu(this.providerContainer);let t=this.providerContainer?.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(N(t=>!!t),j()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",xi(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(N(t=>!!t),j()).subscribe(()=>{bx(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(N(t=>!!t),j()).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(N(t=>!!t),j()).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(N(i=>!!i),j()).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(N(t=>!!t),j()).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(N(i=>!!i),j()).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(N(e=>e),j()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(N(e=>!!e),j()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(VV(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return gx(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.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(Ii(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Bc(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(N(({from:e})=>e==="stopped"),j()).subscribe(()=>{this.initedAt=Tu(),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"ready":this.events.willReady$.next();break;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",xi(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:yu.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(j()).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",xi(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),Y()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(oi({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>yx(u)?1:yx(l)?-1:_V(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(Y()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(N(n=>gx(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Y()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Y()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Y()).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??{})})).add(e.providerOutput.currentBuffer$.pipe(G(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(Tp(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(oi({hasLiveOffsetByPaused:Ii(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),Y(),G(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(oi({atLiveEdge:oi({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:vp({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),Y(),Tp(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(oi({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Y(),Tp(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),Y()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),Y()).subscribe(this.info.volume$)).add(vp({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ii(e.providerOutput.endedEvent$.pipe(Sx(!0)),e.providerOutput.seekedEvent$.pipe(Sx(!1))).pipe(Y()).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(G(n=>({id:n?`No${n}`:"NoProviders",category:yu.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(j(),G(n=>n??Tu()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(j(),G(()=>Tu()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(j(),G(()=>Tu()-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 B(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new B(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(N(({to:n})=>n==="playing"),j()).subscribe(()=>i.next(!1)));let r=0,a=Ii(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),Y());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(Ii(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ii(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(G(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new vx;this.subscription.add(t),this.subscription.add(e.current$.pipe(Y((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(N(i=>i.length>0),j()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Ot(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(Ii(this.desiredState.videoTrack.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(G(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(){let e=this.providerContainer?.providerOutput;vu(this.providerContainer),vu(e),sv(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>rv(t)),this.providerContainer.current$.subscribe(({type:t})=>xs("provider",t)),e.duration$.subscribe(t=>xs("duration",t)),e.availableVideoTracks$.pipe(N(t=>!!t.length),j()).subscribe(t=>xs("tracks",t)),this.events.fatalError$.subscribe(new qe("fatalError")),this.events.managedError$.subscribe(new qe("managedError")),e.position$.subscribe(new qe("position")),e.currentVideoTrack$.pipe(G(t=>t?.quality)).subscribe(new qe("quality")),this.info.currentBuffer$.subscribe(new qe("buffer")),e.isBuffering$.subscribe(new qe("isBuffering"))].forEach(t=>this.subscription.add(t)),xs("codecs",F.video.supportedCodecs)}initTracerSubscription(){let e=Tx(this.tracer.log.bind(this.tracer)),t=Tx(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(Y()).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(oi({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(N(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Y((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(N(i=>i>0),Y()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(N(i=>i>0),Y()).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(oi({currentBuffer:this.info.currentBuffer$.pipe(N(i=>i.end>0),Y((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Y())}).pipe(Ip(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Y()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Y()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Y()).subscribe(e("canChangePlaybackSpeed"))).add(oi({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(N(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Ip(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Y(),N(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Y(),N(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Y()).subscribe(e("muted"))).add(this.info.volume$.pipe(Y()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Y(),N(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(oi({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(N(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Ip(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Y(),N(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?.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:yu.DOM,message:String(r)})})};this.subscription.add(Ii(yp(document,"visibilitychange"),yp(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!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",xi({quality:t,availableTracks:xi(e),track:xi(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&&!Ms()}};import{Subscription as pZ,Observable as hZ,Subject as fZ,ValueSubject as mZ,VideoQuality as bZ}from"@vkontakte/videoplayer-shared";var gZ=`@vkontakte/videoplayer-core@${Ep}`;export{hn as ChromecastState,ku as HttpConnectionType,hZ as Observable,Qe as PlaybackState,Iu as Player,fn as PredefinedQualityLimits,gZ as SDK_VERSION,fZ as Subject,pZ as Subscription,Au as Surface,Ep as VERSION,mZ as ValueSubject,Wt as VideoFormat,bZ as VideoQuality,F as clientChecker,Is as isMobile};
178
+ `;var Ir=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 uo(this.params.fov,this.params.orientation),this.cameraRotationManager=new lo(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(rT,this.gl.VERTEX_SHADER),i=this.createShader(aT,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,u=e+i,o=t-r,l=e+i,c=t+r,p=e-i,d=t+r;return[s,n,u,o,l,c,p,d]}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}};import{isNullable as yC,now as ts,once as TC,Subscription as IC,ValueSubject as Cc,isNonNullable as EC,safeStorage as Bc,filterChanged as xC}from"@vkontakte/videoplayer-shared";var co="stalls_manager_metrics",Vc="stalls_manager_abr_params",sT="stalls_manager_default_tuning_abr_params",_c=class{constructor(){this.isSeeked$=new Cc(!1);this.isBuffering$=new Cc(!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 IC;this.severeStallOccurred$=new Cc(!1)}init(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.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(Vc):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=ts(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(ts()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(sT)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(Vc),this.setStoredData(sT,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(co,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((u,o)=>u+o.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,u)=>n+u.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(co,[]),this.setStoredData(Vc,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:u,stallsMetricsHistoryLength:o}=this.tuning,l=n*Math.min(t/(u*o),1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){return JSON.parse(Bc.get(e)??t)}setStoredData(e,t){Bc.set(e,JSON.stringify(t))}removeStoredData(e){Bc.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(co,"[]"),r=t/e,s=i.length?$t(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(co,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(TC()).subscribe(t=>this.providerStartWatchingTimestamp=ts())),this.subscription.add(this.currentStallDuration$.pipe(xC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(yC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),o=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=ts(),p=r&&this.currentStallsCount>=r,d=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&c-l>=i+u&&t>=i;(p||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,EC(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&ts()-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},s)),this.lastStallDuration=t}))}},po=_c;import{combine as wC,map as AC,observeElementSize as kC,Subscription as PC,ValueSubject as Oc,noop as RC}from"@vkontakte/videoplayer-shared";var ho=class{constructor(){this.subscription=new PC;this.pipSize$=new Oc(void 0);this.videoSize$=new Oc(void 0);this.elementSize$=new Oc(void 0);this.pictureInPictureWindowRemoveEventListener=RC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(kC(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(wC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(AC(({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 Ei=class{constructor(e){this.subscription=new VC;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ur;this.stallsManager=new po;this.elementSizeManager=new ho;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Qt;this.audioTrackSwitchHistory=new Qt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return $C(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ir(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Le(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new oo({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;BC(this.observableVideo)&&(this.observableVideo=De(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:nT.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,u)=>this.subscription.add(n.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Fc(l=>!!l.length),uT()).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(Nc(l=>l.to.state!=="none"),fo());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),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(Fc(oT),uT()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Nc(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(Me(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(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(MC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let d=[];for(let h of c.audio){d.push(Tc(h));let f=[];for(let b of h.representations){let g=Ny(b);f.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(d)}let p=[];for(let d of c.video){p.push(Ic(d));let h=[];for(let f of d.representations){let b=Fy({...f,streamId:d.id});b&&(h.push(b),this.videoTracksMap.set(b,{stream:d,representation:f}))}this.videoStreamsMap.set(d,h)}this.params.output.availableVideoStreams$.next(p);for(let d of c.text)for(let h of d.representations){let f=Uy(d,h);this.textTracksMap.set(f,{stream:d,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(mo(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$,CC(this.video,"progress")).pipe(Fc(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,lT.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[d,h]=p,f=[...this.videoTracksMap.keys()].find(g=>this.videoTracksMap.get(g)?.representation.id===d.id);oT(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(d.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",d.id),h){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,g)}},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(fo()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:d}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Ic(d));let f=this.player.calculateDurationFromSegments();f&&this.params.output.duration$.next(f/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(fo()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:d}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Tc(d))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(Nc(({to:l})=>l==="ready"),fo());this.subscription.add(mo(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Uc(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(mo(u,this.player.state$.stateChangeEnded$,Uc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let o=mo(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Uc(["init"])).pipe(DC(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ca:la,t=this.params.tuning.useNewAutoSelectVideoTrack?Bn:Cn,i=this.params.tuning.useNewAutoSelectVideoTrack?St:Dn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:T})=>T===u),c=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(l&&this.videoTracksMap.get(l)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let d=[...this.videoStreamsMap.keys()].find(({id:T})=>T===p.id),h=d&&this.videoStreamsMap.get(d);if(!h)return;let f=pe(this.video.buffered,this.video.currentTime*1e3),b;this.player.isActiveLive$.getValue()?b=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?b=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:b=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(f/Math.min(b,g||1/0),1),I=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),y=[...this.audioStreamsMap.keys()].find(({id:T})=>T===I?.id)??this.audioStreamsMap.keys().next().value,x=0;if(y){if(l&&!n){let T=e(l,h,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,T?.bitrate??-1/0)}if(c){let T=e(c,h,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,T?.bitrate??-1/0)}}let A=i(h,{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:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),R=n?A??l:l??A,$=y&&t(R,h,this.audioStreamsMap.get(y)??[],{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}),w=this.videoTracksMap.get(R)?.representation,L=$&&this.audioTracksMap.get($)?.representation;if(w&&L)return[w,L];if(w&&!L&&this.audioTracksMap.size===0)return[w,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ce(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:nT.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),$e(this.video),this.tracer.end()}};var is=class extends Ei{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)}};import{combine as qc,merge as cT,filter as dT,filterChanged as pT,isNullable as Hc,map as hT,ValueSubject as jc,isNonNullable as _C}from"@vkontakte/videoplayer-shared";var rs=class extends Ei{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new jc(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(pT()).subscribe(o=>{let l=i.position$.getValue(),c=i.volume$.getValue(),p=!c.volume||c.muted;!o&&!l&&p?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(hT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(qc({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(hT(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(dT(o=>_C(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(qc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:cT(r.playbackRateState$,new jc(1))}).pipe(dT(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;p||l<1-d||this.video.paused||Hc(c)||(t=o-c)})).add(qc({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:cT(r.playbackRateState$,new jc(1))}).pipe(pT((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:c})=>{let p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&c>=1-d||Hc(o)||Hc(l))return;let h=-1*(l-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=qy(o);this.params.output.availableTextTracks$.next([l])}}))}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)})}};import{assertNever as lB,assertNonNullable as cB,debounce as dB,ErrorCategory as $T,filter as nd,filterChanged as ko,fromEvent as pB,isNonNullable as MT,isNullable as hB,map as od,merge as Po,observableFrom as ud,once as DT,Subscription as fB}from"@vkontakte/videoplayer-shared";var ad=C(Sa(),1);import{abortable as ed,assertNonNullable as wr,combine as Ar,ErrorCategory as ut,filter as Eo,filterChanged as ls,flattenObject as cs,fromEvent as It,getTraceSubscriptionMethod as ZC,interval as td,isNonNullable as ds,isNullable as RT,map as kr,merge as Pi,now as id,Subject as xo,Subscription as rd,tap as eB,throttle as LT,ValueSubject as te}from"@vkontakte/videoplayer-shared";var vo=C(We(),1),ki=C(at(),1),yo=C(Sa(),1);var xT=C(pn(),1);import{assertNever as OC,ErrorCategory as fT,Subject as mT}from"@vkontakte/videoplayer-shared";var FC=18,bT=!1;try{bT=V.browser.isSafari&&!!V.browser.safariVersion&&V.browser.safariVersion<=FC}catch(a){console.error(a)}var Qc=class{constructor(e){this.bufferFull$=new mT;this.error$=new mT;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:fT.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};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)};bT&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:fT.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:OC(t)}}},gT=Qc;import{abortable as Kt,assertNonNullable as Ve,ErrorCategory as wi,fromEvent as Kc,getExponentialDelay as Xc,isNonNullable as Er,isNullable as ye,now as So,once as jC,Subject as QC,Subscription as GC,ValueSubject as Ai}from"@vkontakte/videoplayer-shared";var Gc=C(at(),1);import{videoSizeToQuality as NC,throttleFn as UC}from"@vkontakte/videoplayer-shared";var ST=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?jt(s):void 0)??NC({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},vT=({id:a,bitrate:e})=>({id:a,bitrate:e}),yT=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),TT=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Wc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Gc.default)(i.split("."),0),isDefault:r}),zc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Gc.default)(r.split("."),0)}),Yc=a=>"url"in a,He=a=>a.type==="template";var IT=a=>{a.sort((t,i)=>t.from-i.from);let e=[a[0]];for(let t=1;t<a.length;t++){let{from:i,to:r}=a[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(a[t])}return e},xi=(a,e)=>{for(let t of a)if(e(t))return t;return null},ET=a=>{let e=!1,t=UC(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as qC,Subscription as HC}from"@vkontakte/videoplayer-shared";var bo=a=>{let e=[];for(let t=0;t<a.length;t++){let i=Math.floor(a.start(t)*1e3),r=Math.ceil(a.end(t)*1e3);e.push(i,r)}return e};var go=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new HC;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(qC(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!B(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=bo(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],s=e[i+1],n=t[i],u=t[i+1];if(n>r||u<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var as=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ai(0);this.currentLowLatencySegmentLength$=new Ai(0);this.currentSegmentLength$=new Ai(0);this.onLastSegment$=new Ai(!1);this.fullyBuffered$=new Ai(!1);this.playingRepresentation$=new Ai(void 0);this.playingRepresentationInit$=new Ai(void 0);this.error$=new QC;this.gaps=[];this.subscription=new GC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new X;this.switchAbortController=new X;this.destroyAbortController=new X;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=Kt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ve(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new gT(this.sourceBuffer),this.sourceBufferBufferedDiff=new go(this.mediaSource,this.sourceBuffer),this.subscription.add(Kc(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Kc(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:wi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!B(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,dr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=pe(this.sourceBuffer.buffered,u),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<c).catch(p=>{this.handleAsyncError(p,"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);Ve(i,"No init buffer for starting representation"),Ve(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=Kt(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ye(s)||ye(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ve(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(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();Er(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=Kt(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ye(s)||ye(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ve(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(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();Er(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=Kt(this.destroyAbortController.signal,async function*(e){let t=(0,yo.default)(e,o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let c=this.representations.get(o);if(!c||!He(c.segmentReference))return;let p=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,p)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Ve(r);let s=this.segments.get(i);Ve(s,"No segments for starting representation");let n=this.initData.get(i);if(Ve(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],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){!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new X,Kt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Ve(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if(ye(u)||ye(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),Ve(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();Er(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ye(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 X,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ye(e)||ye(this.downloadingRepresentationId)||ye(this.playingRepresentationId)||ye(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||Er(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Ve(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Er(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=pe(this.sourceBuffer.buffered,e),p=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=p)}if(isFinite(this.bufferLimit)&&dr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=pe(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=null;if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o?.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,vo.default)(o,r))c="high";else{let p=(0,ki.default)(o,0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o?.length&&pe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,ki.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-pe(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 s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Er(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,yo.default)(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?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,yo.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!He(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],u=(0,ki.default)(n,-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ve(e);let t=this.segments.get(e);if(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(!He(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=nt(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&vt&&vt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&vt&&vt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.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=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:h,to:f}},b)=>{let g=h<=i&&f>=i,S=h>i||g||b===0&&i===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+I||r<I&&f-h>=I||f<=i+I;return(d==="none"||d==="partially_ejected"&&S&&y&&this.sourceBuffer&&B(this.mediaSource,this.sourceBuffer)&&!(Se(this.sourceBuffer.buffered,h)&&Se(this.sourceBuffer.buffered,f)))&&S&&y});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<n.length&&(u<=c||o<=p);d++){let h=n[d];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){He(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:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await Kt(u,async function*(){let c=Xc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(p=>setTimeout(p,c))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=So(),!c)return;let p=new DataView(c),d=yt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(p,b)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(p,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(p);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Tt(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())He(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Kt(n,async function*(){let o=Xc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),Kc(window,"online").pipe(jC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=So(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Tt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(He(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,ki.default)(e,0).byte.from,to:(0,ki.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=So(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:wi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!He(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=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=So();let p=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(p)}catch(p){this.error$.next({id:"SegmentFeeding",category:wi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:p})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,vo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=yt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(o.status="partially_fed",u.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){if(o.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=o,c=l.byte.from-i,p=l.byte.to-i,d=p-c+1,h=c<r,f=p<=r;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,d);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-c),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+o.feedingBytes,o.loadedBytes-o.feedingBytes),g=o.loadedBytes===d?b:yt(u.mime).parseFeedableSegmentChunk(b);g?.byteLength&&(l.status="partially_fed",o.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(o.fedBytes+=g.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(ye(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer))){!this.isLive&&V.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Se(this.sourceBuffer.buffered,e.segment.time.from,100)&&Se(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:wi.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",Yc(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 s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}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,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=cr(()=>(0,xT.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?Kt(this.destroyAbortController.signal,async function*(){let u=Xc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,yt(e.mime),r)).then(u=>{if(!u)return;let{init:o,dataView:l,segments:c}=u,p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,p);let d=c;this.isLive&&He(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:wi.WTF,message:"loadInit threw",thrown:u})});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||!B(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ye(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=u=>{if(s>=t)return;r.push({...u.time});let o=Yc(u)?u.size??0:u.byte.to-u.byte.from;s+=o};for(let u of this.segments.values())for(let o of u){let l=o.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=o.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&o.status==="fed"&&n(o)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let o=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let d of p)(0,vo.default)(["none","partially_ejected"],d.status)&&Math.round(d.time.from)<=Math.round(o)&&Math.round(d.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let p={time:{from:o,to:l},url:"",status:"none"};n(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let o of this.segments.values())for(let l of o)l.time.from>=e+u&&l.status==="fed"&&n(l)}return r.length?(r=IT(r),(await Promise.all(r.map(o=>this.sourceBufferTaskQueue.remove(o.from,o.to)))).reduce((o,l)=>o||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!B(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||!B(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||!B(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||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ye(e)?0:pe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let n=Math.round(s.from),u=Math.round(s.to);for(let o=0;o<i.length;o++)if(n>=Math.round(i.start(o)*1e3)&&u<=Math.round(i.end(o)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let n=i.start(s)*1e3,u=i.end(s)*1e3;if(!(u<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&u>=t.time.to){r=void 0;break}u>t.time.from&&u<t.time.to&&(r.from=u),n<t.time.to&&n>t.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||!B(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=cr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:wi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ye(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||ye(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=bo(this.sourceBuffer.buffered),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),u=Math.ceil(r.time.to),o=!1,l=0;for(let c=0;c<e.length;c+=2){let p=e[c],d=e[c+1];o||(o=p-t<=n&&d+t>=u),(n>=p&&n<d-t||u>p+t&&u<=d)&&(l+=1)}o||(l===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:wi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,ki.default)(e,-1)?.time.to:0)||0}};import{abortable as ss,assertNever as wT,fromEvent as AT,merge as WC,now as ns,Subject as kT,ValueSubject as Jc,flattenObject as xr,ErrorCategory as os,SubscriptionRemovable as zC}from"@vkontakte/videoplayer-shared";var Io=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Jc(void 0);this.lastConnectionReused$=new Jc(void 0);this.lastRequestFirstBytes$=new Jc(void 0);this.recoverableError$=new kT;this.error$=new kT;this.abortAllController=new X;this.subscription=new zC;this.fetchManifest=ss(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=zt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Yn(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(To);return r?(t.log("success",xr({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",xr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ss(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1}={}){let c=e,p=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let v=new URL(c,location.href);v.searchParams.append("bytes",`${i.from}-${i.to}`),c=v.toString();break}default:wT(t)}this.requestQuic&&(c=zt(c));let h=this.abortAllController.signal,f;if(n){let v=new X;if(f=WC(AT(this.abortAllController.signal,"abort"),AT(n,"abort")).subscribe(()=>{try{v.abort()}catch(E){To(E)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(E){To(E)}h=v.signal}let b=ns();d.log("startRequest",xr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:b}));let g=yield this.doFetch(c,{priority:s,headers:p,signal:h}),S=ns();if(!g)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(S-b),!g.ok||!g.body){this.unsubscribeAbortSubscription(f);let v=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:v}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){this.unsubscribeAbortSubscription(f);let v=ns(),E={requestStartedAt:b,requestEndedAt:v,duration:v-b};return d.log("endRequest",xr(E)),d.end(),g.arrayBuffer()}let I=g.body;if(u){let v;[I,v]=g.body.tee(),this.throughputEstimator?.trackStream(v,o)}let y=I.getReader(),x,A=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(A)&&(x=A),!x&&i&&(x=i.to-i.from+1);let R=0,$=x?new Uint8Array(x):new Uint8Array(0),w=!1,L=v=>{this.unsubscribeAbortSubscription(f),w=!0,To(v)},T=ss(h,async function*({done:v,value:E}){if(R===0&&this.lastRequestFirstBytes$.next(ns()-b),h.aborted){this.unsubscribeAbortSubscription(f);return}if(!v&&E){if(l&&x)$.set(E,R),R+=E.byteLength;else{let W=new Uint8Array($.length+E.length);W.set($),W.set(E,$.length),$=W,R+=E.byteLength}r?.(new DataView($.buffer),R),yield y?.read().then(T,L)}}.bind(this));yield y?.read().then(T,L),this.unsubscribeAbortSubscription(f);let F=ns(),M={failed:w,requestStartedAt:b,requestEndedAt:F,duration:F-b};return w?(d.error("endRequest",xr(M)),d.end(),null):(d.log("endRequest",xr(M)),d.end(),$.buffer)}.bind(this));this.fetchByteRangeRepresentation=ss(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(c,s))),n=Math.min(n,0);let p=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!p)return null;let d=new DataView(p,r-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(p,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(p),segments:g}}.bind(this));this.fetchTemplateRepresentation=ss(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}=zn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:wT(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Xe(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:os.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:os.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:os.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:os.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:os.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},To=a=>{if(!Tt(a))throw a};import{isNullable as YC,ValueSubject as KC}from"@vkontakte/videoplayer-shared";var us=class a{constructor(e,t){this.currentRepresentation$=new KC(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!YC(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<n||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&He(t.segmentReference))}};var tB=["progress","play","seeked","stalled","waiting"],iB=["timeupdate","progress","loadeddata","playing","seeked"];var wo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new rd;this.representationSubscription=new rd;this.state$=new O("none");this.currentVideoRepresentation$=new te(void 0);this.currentVideoRepresentationInit$=new te(void 0);this.currentAudioRepresentation$=new te(void 0);this.currentVideoSegmentLength$=new te(0);this.currentAudioSegmentLength$=new te(0);this.error$=new xo;this.lastConnectionType$=new te(void 0);this.lastConnectionReused$=new te(void 0);this.lastRequestFirstBytes$=new te(void 0);this.currentLiveTextRepresentation$=new te(null);this.isLive$=new te(!1);this.isActiveLive$=new te(!1);this.isLowLatency$=new te(!1);this.liveDuration$=new te(0);this.liveSeekableDuration$=new te(0);this.liveAvailabilityStartTime$=new te(0);this.liveStreamStatus$=new te(void 0);this.bufferLength$=new te(0);this.liveLatency$=new te(void 0);this.liveLoadBufferLength$=new te(0);this.livePositionFromPlayer$=new te(0);this.currentStallDuration$=new te(0);this.videoLastDataObtainedTimestamp$=new te(0);this.fetcherRecoverableError$=new xo;this.fetcherError$=new xo;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new xo;this.gapWatchdogActive=!1;this.destroyController=new X;this.initManifest=ed(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ut.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=ed(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ut.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=jn(e??"",this.manifestUrlString)}catch(n){let u=qn(e)??{id:"ManifestParsing",category:ut.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(u)}if(!t)return null;let i=(n,u,o)=>!!(this.element?.canPlayType?.(u)&&Ue()?.isTypeSupported?.(`${u}; codecs="${o}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:u,streamIsUnpublished:o,streamIsAlive:l}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((u-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";l||(p=o?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let o=t.streams[n].filter(({mime:p,codecs:d})=>i(n,p,d)),l=new Set(o.map(({codecs:p})=>p)),c=ao(l);if(c&&(r[n]=o.filter(({codecs:p})=>p.startsWith(c))),n==="video"){let p=this.tuning.preferHDR,d=r.video.some(f=>f.hdr),h=r.video.some(f=>!f.hdr);V.display.isHDR&&p&&d?r.video=r.video.filter(f=>f.hdr):h&&(r.video=r.video.filter(f=>!f.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",cs(s)),s}.bind(this));this.initRepresentations=ed(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",cs({initialVideo:e,initialAudio:t,sourceHls:i})),wr(this.manifest),wr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new rd,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(It(d,"error").pipe(Eo(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Sn():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ir())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}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},u=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new as("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],ds(t)){let d=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new as("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}us.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new us(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 o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Pi(...iB.map(d=>It(this.element,d))).pipe(kr(d=>this.element?pe(this.element.buffered,this.element.currentTime*1e3):0),ls(),eB(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Pi(It(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ls()).subscribe(h=>this.liveStreamEndTimestamp=id())),this.subscription.add(It(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=td(1e3).subscribe(h=>{let f=qt(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(It(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Ar({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(kr(({isActiveLive:h,isLowLatency:f})=>h&&f),ls()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Sr(this.element,1)})),this.representationSubscription.add(Ar({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Eo(({bufferLength:h,isActiveLive:f,isLowLatency:b})=>f&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Ar({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Eo(({isLive:h})=>h),ls((h,f)=>f.bufferLength<h.bufferLength),kr(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=qt(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ar({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=h-g;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(y)>S&&(x=1+Math.sign(y)*I),Sr(this.element,x)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add(Ar({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(LT(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,g=qt(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,A=isFinite(h)?h:f,R=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(R?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(L=>L.proceedLowLatencyLive()),w="active_low_latency"):g!==0&&A<I?w="live_forward_buffering":A<I+x&&(w="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),w==="live_forward_buffering"||w==="live_with_target_offset"){let L=d-(I+y),T=this.normolizeLiveOffset(Math.trunc(g+L/b)),F=Math.abs(T-g),M=0;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?M=g:T>0&&F>this.tuning.dashCmafLive.offsetCalculationError&&(M=T),this.manifestUrlString=se(this.manifestUrlString,M,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ut.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Pi(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(kr(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=Pi(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(kr(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),p=Ar({allBuffersFull:l,someBufferEnded:c}).pipe(ls(),kr(({allBuffersFull:d,someBufferEnded:h})=>d&&h),Eo(d=>d));if(this.representationSubscription.add(Pi(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(Pi(...this.bufferManagers.map(d=>d.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 d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,ad.default)((0,ad.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),He(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&ds(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=td(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ut.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Io({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=Mt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){wr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?id()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=se(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){wr(this.element),this.state$.setState("running");let e=It(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(LT(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Pi(...tB.map(t=>It(this.element,t)),It(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:ut.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(It(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(It(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Se(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=id(),n=100,u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,c=this.audioBufferManager?.getForwardBufferDuration()??0,p=l<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&c<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((p||d)&&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 h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(f=>{this.error$.next({id:"stallIntervalCallback",category:ut.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:f})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",cs(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=td(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:ut.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?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){wr(this.element),wr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Se(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(RT(this.element)||RT(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",cs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){ds(this.element)&&ds(this.source)&&ds(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=ZC(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(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.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 s=this.element.currentTime*1e3,n=null,u=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let l of o.gaps)(l.persistent||o.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let o=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,this.tracer.log("jumpGap",cs({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:o,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as rB,map as aB,observeElementSize as sB,Subscription as nB,ValueSubject as sd,noop as oB}from"@vkontakte/videoplayer-shared";var Ao=class{constructor(){this.subscription=new nB;this.pipSize$=new sd(void 0);this.videoSize$=new sd(void 0);this.elementSize$=new sd(void 0);this.pictureInPictureWindowRemoveEventListener=oB}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(sB(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(rB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(aB(({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 Ri=class{constructor(e){this.subscription=new fB;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ur;this.stallsManager=new po;this.elementSizeManager=new Ao;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Qt;this.audioTrackSwitchHistory=new Qt;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?.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"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return lB(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ir(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Le(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new wo({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;hB(this.observableVideo)&&(this.observableVideo=De(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:$T.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,u)=>this.subscription.add(n.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(nd(p=>!!p.length),DT()).subscribe(p=>{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:p})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(od(p=>p.to.state!=="none"),ko());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),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(nd(MT),DT()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(od(p=>p.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(Me(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(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:p})=>{if(p==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(cB(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of d.audio){f.push(Wc(b));let g=[];for(let S of b.representations){let I=vT(S);g.push(I),this.audioTracksMap.set(I,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let h=[];for(let f of d.video){h.push(zc(f));let b=[];for(let g of f.representations){let S=ST({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(h);for(let f of d.text)for(let b of f.representations){let g=yT(f,b);this.textTracksMap.set(g,{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 p==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,o=u&&ET(u)||null;this.subscription.add(Po(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$,pB(this.video,"progress")).pipe(nd(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let p=this.player.state$.getState(),d=this.player.state$.getTransition();if(p!=="manifest_ready"&&p!=="running"||d||p==="running"&&o&&!o())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:f}=this.selectedRepresentations;if(!h)return;let b=xi(this.videoTracksMap.keys(),S=>this.videoTracksMap.get(S)?.representation.id===h.id);MT(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),p==="manifest_ready")await this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:p})=>{this.scene3D&&p&&this.scene3D.pointCameraTo(p.x,p.y)})),this.subscription.add(this.elementSizeManager.subscribe(p=>{this.scene3D&&p&&this.scene3D.setViewportSize(p.width,p.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ko()).subscribe(p=>{let d=xi(this.videoTracksMap.entries(),([,{representation:S}])=>S.id===p);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=d,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(zc(f));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ko()).subscribe(p=>{let d=xi(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===p);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Wc(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(p=>{if(p?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(p),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(od(({to:p})=>p==="ready"),ko());this.subscription.add(Po(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,ud(["init"])).subscribe(()=>{let p=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:p?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(Po(l,this.player.state$.stateChangeEnded$,ud(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Po(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ud(["init"])).pipe(dB(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ca:la,t=this.params.tuning.useNewAutoSelectVideoTrack?Bn:Cn,i=this.params.tuning.useNewAutoSelectVideoTrack?St:Dn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=xi(this.videoTracksMap.keys(),w=>w.id===u),l=s.currentVideoTrack$.getValue(),c=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let p=xi(this.videoStreamsMap.keys(),w=>w.id===c.id),d=p&&this.videoStreamsMap.get(p);if(!d)return;let h=pe(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,g=Math.min(h/Math.min(f,b||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),I=S?.id&&xi(this.audioStreamsMap.keys(),w=>w.id===S.id)||this.audioStreamsMap.keys().next().value,y=0;if(I){if(o&&!n){let w=e(o,d,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,w?.bitrate??-1/0)}}let x=o;(n||!x)&&(x=i(d,{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:y,forwardBufferHealth:g,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 A=I&&t(x,d,this.audioStreamsMap.get(I)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),R=this.videoTracksMap.get(x)?.representation,$=A&&this.audioTracksMap.get(A)?.representation;R&&$?(this.selectedRepresentations.video=R,this.selectedRepresentations.audio=$):R&&!$&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=R,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ce(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:$T.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),$e(this.video),this.tracer.end()}};var ps=class extends Ri{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)}};import{combine as ld,merge as CT,filter as BT,filterChanged as VT,isNullable as cd,map as _T,ValueSubject as dd,isNonNullable as mB}from"@vkontakte/videoplayer-shared";var hs=class extends Ri{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new dd(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(VT()).subscribe(o=>{let l=i.position$.getValue(),c=i.volume$.getValue(),p=!c.volume||c.muted;!o&&!l&&p?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(_T(o=>o.to)).subscribe(this.player.isLowLatency$)).add(ld({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(_T(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(BT(o=>mB(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(ld({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:CT(r.playbackRateState$,new dd(1))}).pipe(BT(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;p||l<1-d||this.video.paused||cd(c)||(t=o-c)})).add(ld({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:CT(r.playbackRateState$,new dd(1))}).pipe(VT((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:c})=>{let p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&c>=1-d||cd(o)||cd(l))return;let h=-1*(l-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=TT(o);this.params.output.availableTextTracks$.next([l])}}))}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 OT="X-Playback-Duration",pd=async a=>{let e=await Xe(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(OT)?parseInt(e.headers.get(OT),10):void 0};import{assertNever as AB,combine as kB,debounce as PB,ErrorCategory as $o,filter as RB,filterChanged as LB,isNonNullable as UT,isNullable as Mo,map as qT,merge as $B,observableFrom as MB,Subscription as DB,ValueSubject as md,VideoQuality as CB}from"@vkontakte/videoplayer-shared";var fd=C(Xu(),1);import{videoSizeToQuality as bB,getExponentialDelay as gB}from"@vkontakte/videoplayer-shared";var SB=a=>{let e=null;if(a.QUALITY&&(e=jt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=bB({width:t,height:i})}return e??null},vB=(a,e)=>{let t=a.split(`
179
+ `),i=[],r=[];for(let s=0;s<t.length;s++){let n=t[s],u=n.match(/^#EXT-X-STREAM-INF:(.+)/),o=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!o)){if(u){let l=(0,fd.default)(u[1].split(",").map(g=>g.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,p=SB(l),d;l.BANDWIDTH&&(d=parseInt(l.BANDWIDTH,10)/1e3||void 0),!d&&l["AVERAGE-BANDWIDTH"]&&(d=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[g,S]=l.RESOLUTION.split("x").map(I=>parseInt(I,10));g&&S&&(f={width:g,height:S})}let b=new URL(t[++s],e).toString();p&&i.push({id:c,quality:p,url:b,bandwidth:d,size:f,fps:h})}if(o){let l=(0,fd.default)(o[1].split(",").map(h=>{let f=h.indexOf("=");return[h.substring(0,f),h.substring(f+1)]}).map(([h,f])=>[h,f.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),p=l.LANGUAGE,d=l.NAME;c&&p&&r.push({type:"internal",id:p,label:d,language:p,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},yB=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),hd=0,FT=async(a,e=a,t,i)=>{let s=await(await Xe(a,i)).text();hd+=1;try{let{qualityManifests:n,textTracks:u}=vB(s,e);return{qualityManifests:n,textTracks:u}}catch{if(hd<=t.manifestRetryMaxCount)return await yB(gB(hd-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),FT(a,e,t)}return{qualityManifests:[],textTracks:[]}},Ro=FT;import{isNonNullable as TB,Subscription as IB,throttle as EB,ValueSubject as NT,Subject as xB,ErrorCategory as wB}from"@vkontakte/videoplayer-shared";var Lo=class{constructor(e,t,i,r,s){this.subscription=new IB;this.abortControllers={destroy:new X,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new NT(null);this.getCurrentTime$=new NT(null);this.error$=new xB;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(EB(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 Xe(r,{signal:this.abortControllers.destroy.signal})).text(),u=this.parsePlaylist(n,r);return{textTrack:i,playlist:u}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
180
+ `),s=0;for(let n=0;n<r.length;++n){let u=r[n];switch(!0){case u.startsWith("#EXTINF:"):{let o=r[++n],l=new URL(o,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let p=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-p}break}case u.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",u));break;case u.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",u));break;case u.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",u));break;case u.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let o=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",u);i.programDateTime=o;let l=new Date(o);l.setMilliseconds(0),s=l.valueOf();break}case u.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",u);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(TB(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 X;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:wB.WTF,thrown:t,message:e})}};var fs=class{constructor(e){this.subscription=new DB;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new md([]);this.liveOffset=new mi;this.manifestStartTime$=new md(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(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||u){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(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"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else r?.to==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return AB(t)}};this.params=e,this.video=Le(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:CB.INVARIANT,url:this.params.source.url};let t=(i,r)=>Ro(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Lo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ye(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:$o.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:$o.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new md(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let u=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:$o.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=De(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,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(Me(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(Ke(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(u=>{u&&this.params.output.availableTextTracks$.next(u)})),this.subscription.add(this.maxSeekBackTime$.pipe(LB(),qT(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&UT(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===p);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(ge(d.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u&&u.state==="requested"&&this.seek(u.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add(kB({startTime:this.manifestStartTime$.pipe(RB(UT)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:o})=>this.params.output.liveTime$.next(u+o*1e3),i)),this.subscription.add(this.manifests$.pipe(qT(u=>u.map(({id:o,quality:l,size:c,bandwidth:p,fps:d})=>({id:o,quality:l,size:c,fps:d,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,i));let n=$B(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,MB(["init"])).pipe(PB(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),$e(this.video)}prepare(){let e=this.selectManifest();if(Mo(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:u,min:o}=t?.to??i??{};for(let[l,c]of[[u,"mq"],[o,"lq"]]){let p=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=se(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),pd(n).then(u=>{if(!Mo(u))this.maxSeekBackTime$.next(u);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Mo(o)||!isFinite(o))&&Xe(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let p=new URL(c,n).toString();pd(p).then(d=>{Mo(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){Ce(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:$o.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=se(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}};import{assertNever as BB,debounce as VB,ErrorCategory as bd,fromEvent as gd,isNonNullable as _B,isNullable as OB,map as HT,merge as jT,observableFrom as QT,Subscription as FB,ValueSubject as NB,VideoQuality as UB}from"@vkontakte/videoplayer-shared";var ms=class{constructor(e){this.subscription=new FB;this.videoState=new O("stopped");this.manifests$=new NB([]);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(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||u){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:p}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:p*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return BB(t)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Le(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:UB.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ro(se(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:bd.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let u=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:bd.WTF,message:"HlsProvider internal logic error",thrown:u})},r=De(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o));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(HT(u=>u.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,i)),this.subscription.add(Me(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&_B(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ge(f.url)))}let p=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(p!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(p),h.playbackRate=p)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u.state==="requested"&&this.seek(u.position)},i))),this.subscription.add(this.manifests$.pipe(HT(u=>u.map(({id:o,quality:l,size:c,bandwidth:p,fps:d})=>({id:o,quality:l,size:c,fps:d,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,i)),!V.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add(jT(gd(u,"addtrack"),gd(u,"removetrack"),gd(u,"change"),QT(["init"])).subscribe(()=>{for(let o=0;o<u.length;o++)u[o].mode="hidden"},i))}let n=jT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,QT(["init"])).pipe(VB(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),$e(this.video)}prepare(){let e=this.selectManifest();if(OB(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??i??{};for(let[u,o]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(u||""));o&&u&&r.searchParams.set(o,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ce(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bd.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var zT=C(Hi(),1),Sd=C(er(),1),YT=C(at(),1);import{assertNever as qB,assertNonNullable as GT,debounce as HB,ErrorCategory as WT,isHigherOrEqual as jB,isLowerOrEqual as QB,isNonNullable as GB,merge as WB,observableFrom as zB,Subscription as YB,map as KB}from"@vkontakte/videoplayer-shared";var bs=class{constructor(e){this.subscription=new YB;this.videoState=new O("stopped");this.trackUrls={};this.textTracksManager=new Ye;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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),u=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:o}=this.video;this.prepare(),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:o*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return qB(e)}};this.params=e,this.video=Le(e.container,e.tuning),this.params.output.element$.next(this.video),(0,zT.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,Sd.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=u=>{e.error$.next({id:"MpegProvider",category:WT.WTF,message:"MpegProvider internal logic error",thrown:u})},r=De(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,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(KB(u=>u.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,i)),this.subscription.add(Me(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(Ke(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let u=this.params.desiredState.videoTrack.getTransition();if(u&&GB(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);let o=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(o!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(o),c.playbackRate=o)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=WB(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,zB(["init"])).pipe(HB(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),$e(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;GT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];GT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=zt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ge(t))}playIfAllowed(){Ce(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:WT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let c=St(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(c)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,Sd.default)(this.trackUrls).map(l=>l.track);if(!r||!s||rr(e,n[0].quality,(0,YT.default)(n,-1)?.quality)){i();return}let u=e.max?QB(r,e.max):!0,o=e.min?jB(r,e.min):!0;u&&o||i(e)}};import{assertNever as XT,debounce as e0,merge as JT,observableFrom as t0,Subscription as i0,map as ZT,ValueSubject as r0,ErrorCategory as yd,VideoQuality as a0}from"@vkontakte/videoplayer-shared";import{ErrorCategory as XB}from"@vkontakte/videoplayer-shared";var KT=["stun:videostun.mycdn.me:80"],JB=1e3,ZB=3,vd=()=>null,Do=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=vd;this.externalStopCallback=vd;this.externalErrorCallback=vd;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:KT}]};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:XB.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),JB)}normalizeOptions(e={}){let t={stunServerList:KT,maxRetryNumber:ZB,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var gs=class{constructor(e){this.videoState=new O("stopped");this.maxSeekBackTime$=new r0(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return XT(e)}};this.subscription=new i0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Le(e.container,e.tuning),this.liveStreamClient=new Do(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),$e(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:yd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(JT(this.videoState.stateChangeStarted$.pipe(ZT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ZT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(n)}`})}));let r=De(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.subscribe(u,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Ke(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Me(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 XT(n.to)}},i)).add(JT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,t0(["init"])).pipe(e0(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:a0.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:yd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ce(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:yd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ss=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}};import{assertNever as vs,assertNonNullable as Xt,ErrorCategory as Co,filter as sI,isNonNullable as nI,isNullable as d0,map as p0,merge as h0,once as f0,Subject as he,Subscription as oI,ValueSubject as U,flattenObject as Td}from"@vkontakte/videoplayer-shared";import{Observable as s0,map as eI,Subscription as n0,Subject as o0}from"@vkontakte/videoplayer-shared";var tI=a=>new s0(e=>{let t=new n0,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(eI(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(eI(({type:l})=>l!==void 0)),n=new o0,u=0,o="unknown";return t.add(i.subscribe(l=>{u&&window.clearTimeout(u),o=l,u=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(u),o="unknown",u=0})),t.add(s.subscribe(l=>{u&&(window.clearTimeout(u),u=0,l&&(u=window.setTimeout(()=>n.next(o),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});import{ErrorCategory as u0,Subscription as l0,combine as c0,filter as rI,once as aI}from"@vkontakte/videoplayer-shared";function iI(){return new(window.AudioContext||window.webkitAudioContext)}var Pr=class a{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new X;this.subscriptions=new l0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(rI(s=>!!s.type),aI()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){V.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(c0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(rI(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),aI()).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=iI();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:a.errorId,category:u0.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var m0={chunkDuration:5e3,maxParallelRequests:5},ys=class{constructor(e){this.current$=new U({type:void 0});this.providerError$=new he;this.noAvailableProvidersError$=new he;this.volumeMultiplierError$=new he;this.providerOutput={position$:new U(0),duration$:new U(1/0),volume$:new U({muted:!1,volume:1}),availableVideoStreams$:new U([]),currentVideoStream$:new U(void 0),availableVideoTracks$:new U([]),currentVideoTrack$:new U(void 0),availableAudioStreams$:new U([]),currentAudioStream$:new U(void 0),availableAudioTracks$:new U([]),currentVideoSegmentLength$:new U(0),currentAudioSegmentLength$:new U(0),isAudioAvailable$:new U(!0),autoVideoTrackLimitingAvailable$:new U(!1),autoVideoTrackLimits$:new U(void 0),currentBuffer$:new U(void 0),isBuffering$:new U(!0),error$:new he,fetcherError$:new he,fetcherRecoverableError$:new he,warning$:new he,willSeekEvent$:new he,soundProhibitedEvent$:new he,seekedEvent$:new he,loopedEvent$:new he,endedEvent$:new he,firstBytesEvent$:new he,loadedMetadataEvent$:new he,firstFrameEvent$:new he,canplay$:new he,isLive$:new U(void 0),isLiveEnded$:new U(null),isLowLatency$:new U(!1),canChangePlaybackSpeed$:new U(!0),liveTime$:new U(void 0),liveBufferTime$:new U(void 0),liveLatency$:new U(void 0),severeStallOccurred$:new he,availableTextTracks$:new U([]),currentTextTrack$:new U(void 0),hostname$:new U(void 0),httpConnectionType$:new U(void 0),httpConnectionReused$:new U(void 0),inPiP$:new U(!1),inFullscreen$:new U(!1),element$:new U(void 0),elementVisible$:new U(!0),availableSources$:new U(void 0),is3DVideo$:new U(!1),playbackState$:new U(""),getCurrentTime$:new U(null)};this.subscription=new oI;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=Ky([...Jy(this.params.tuning),...Xy(this.params.tuning)],this.params.tuning).filter(l=>nI(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Id.default)(r,l)),...t.filter(l=>(0,Id.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Td(s)),this.screenFormatsIterator=new Ss(s);let n=[...Pc(!0),...Pc(!1)];this.chromecastFormatsIterator=new Ss(n.filter(l=>nI(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&u!==1&&Pr.isSupported()&&(this.volumeMultiplierManager=new Pr(this.providerOutput,this.current$,this.volumeMultiplierError$,u))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(d0(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Co.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 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 vs(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,u={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 o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Xt(o),this.params.tuning.useNewDashProvider?new ps({...u,source:o,sourceHls:l}):new is({...u,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Xt(o),this.params.tuning.useNewDashProvider?new hs({...u,source:o}):new rs({...u,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Xt(o),new ms({...u,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Xt(o),new fs({...u,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Xt(o),new bs({...u,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Xt(o),new qS({...u,source:o,config:{...m0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Xt(o),new gs({container:i,source:o,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 vs(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return Xt(u),new ra({connection:u,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 vs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return vs(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 vs(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,lI.default)((0,uI.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new oI,t=!1,i=0;return e.add(h0(this.providerOutput.error$.pipe(sI(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),tI({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(p0(r=>({id:`ProviderHangup:${r}`,category:Co.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(sI(({to:s})=>s==="playing"),f0()).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 u=r.category===Co.NETWORK,o=r.category===Co.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!o,p=l&&!o&&(u&&t||!c);n={...n,isNetworkError:u,isFatalError:o,haveFailoverHost:l,tryFailover:p,canReinitProvider:c},c?(i++,this.reinitProvider()):p?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Td(n)):this.tracer.error("providerError",Td(n))})),e}};import{fromEvent as Bo,once as b0,combine as g0,Subscription as cI,ValueSubject as Ed,map as S0,filter as v0,isNonNullable as Vo,now as je,safeStorage as xd}from"@vkontakte/videoplayer-shared";var y0=5e3,dI="one_video_throughput",pI="one_video_rtt",Ts=window.navigator.connection,hI=()=>{let a=Ts?.downlink;if(Vo(a)&&a!==10)return a*1e3},fI=()=>{let a=Ts?.rtt;if(Vo(a)&&a!==3e3)return a},mI=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},wd=class a{constructor(e){this.subscription=new cI;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(dI)||(e.useBrowserEstimation?hI():void 0)||y0,i=a.load(pI)??(e.useBrowserEstimation?fI():void 0)??0;if(this.throughput$=new Ed(t),this.rtt$=new Ed(i),this.rttAdjustedThroughput$=new Ed(mI(t,i,e.rttPenaltyRequestSize)),this.throughput=Mt.getSmoothedValue(t,-1,e),this.rtt=Mt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=hI();n&&this.throughput.next(n);let u=fI();Vo(u)&&this.rtt.next(u)};Ts&&"onchange"in Ts&&this.subscription.add(Bo(Ts,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{xd.set(dI,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{xd.set(pI,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(g0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(S0(({throughput:r,rtt:s})=>mI(r,s,e.rttPenaltyRequestSize)),v0(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=je(),r=new cI;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Bo(e,"progress").pipe(b0()).subscribe(s=>{t=s.loaded,i=je()}));break;case 1:case 0:r.add(Bo(e,"loadstart").subscribe(()=>{t=0,i=je()}));break}r.add(Bo(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,u=je(),o=n-t,l=u-i;this.addRawSpeed(o,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=je(),n=0,u=je(),o=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:p})=>{if(c)!t&&this.addRawSpeed(r,je()-s,1),this.concurrentDownloads.delete(e);else if(p){if(t){let d=je();if(d-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=u-s;f&&this.addRawSpeed(n,f,1,t),n=p.byteLength,s=je()}else n+=p.byteLength;u=je()}else r+=p.byteLength,n+=p.byteLength,n>=this.tuningConfig.streamMinSampleSize&&je()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,je()-u,this.concurrentDownloads.size),n=0,u=je());await i?.read().then(l,o)}};this.concurrentDownloads.add(e),i?.read().then(l,o)}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){let t=xd.get(e);if(Vo(t))return parseInt(t,10)??void 0}},bI=wd;import{fillWithDefault as T0,VideoQuality as _o}from"@vkontakte/videoplayer-shared";var gI={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:_o.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:_o.Q_720P,trafficSavingLimit:_o.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,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:_o.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,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,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},SI=a=>({...T0(a,gI),configName:[...a.configName??[],...gI.configName]});import{assertNonNullable as Oo,combine as Ct,ErrorCategory as Fo,filter as _,filterChanged as z,fromEvent as kd,isNonNullable as II,isNullable as P0,Logger as R0,map as G,mapTo as EI,merge as Jt,now as No,once as H,Subject as Y,Subscription as xI,tap as Pd,ValueSubject as P,isHigher as L0,isInvariantQuality as wI,flattenObject as Zt,throttle as Rd,getTraceSubscriptionMethod as AI,TracerFactory as $0,InternalsExposure as M0}from"@vkontakte/videoplayer-shared";import{merge as I0,map as E0,filter as vI,isNonNullable as x0}from"@vkontakte/videoplayer-shared";var Ad=({seekState:a,position$:e})=>I0(a.stateChangeEnded$.pipe(E0(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),vI(x0)),e.pipe(vI(()=>a.getState().state==="none")));import{assertNonNullable as w0}from"@vkontakte/videoplayer-shared";var yI=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return w0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as A0,once as k0}from"@vkontakte/videoplayer-shared";var TI=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(A0(r=>r.length>0),k0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var Uo=class{constructor(e={configName:[]},t=$0.createRootTracer(!1)){this.subscription=new xI;this.logger=new R0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new P(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new O("stopped"),seekState:new O({state:"none"}),volume:new O({volume:1,muted:!1}),videoTrack:new O(void 0),videoStream:new O(void 0),audioStream:new O(void 0),autoVideoTrackSwitching:new O(!0),autoVideoTrackLimits:new O({}),isLooped:new O(!1),isLowLatency:new O(!1),playbackRate:new O(1),externalTextTracks:new O([]),internalTextTracks:new O([]),currentTextTrack:new O(void 0),textTrackCuesSettings:new O({}),cameraOrientation:new O({x:0,y:0})};this.info={playbackState$:new P(void 0),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),predefinedQualityLimitType$:new P("unknown"),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),isLiveEnded$:new P(null),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),liveLatency$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new Y,ready$:new Y,started$:new Y,playing$:new Y,paused$:new Y,stopped$:new Y,willReady$:new Y,willStart$:new Y,willResume$:new Y,willPause$:new Y,willStop$:new Y,willDestruct$:new Y,watchCoverageRecord$:new Y,watchCoverageLive$:new Y,managedError$:new Y,fatalError$:new Y,fetcherRecoverableError$:new Y,ended$:new Y,looped$:new Y,seeked$:new Y,willSeek$:new Y,autoplaySoundProhibited$:new Y,firstBytes$:new Y,loadedMetadata$:new Y,firstFrame$:new Y,canplay$:new Y,log$:new Y,fetcherError$:new Y,severeStallOccured$:new Y};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:fS,getCurrentTime$:new P(null)};if(this.initLogs(),this.tuning=SI(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new _s({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new bI(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new M0("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:(...u)=>{try{return n.apply(i,u)}catch(o){let l=u.map(d=>JSON.stringify(d,(h,f)=>{let b=typeof f;return(0,kI.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(r)}`,p=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Fo.WTF,message:p,thrown:o}),o}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...n}=e;this.tracer.log("initVideo",Zt(n)),this.domContainer=yI(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ys({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],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.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?V.isInited$.pipe(_(s=>!!s),H()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),kd(document,"visibilitychange").pipe(H()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(_(e=>!!e),H()).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(_(e=>!!e),H()).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(_(e=>!!e),H()).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(_(e=>!!e),H()).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(_(i=>!!i),H()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),H()).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(_(i=>!!i),H()).subscribe(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=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,t=!1){return this.subscription.add(this.playerInited.pipe(_(i=>!!i),H()).subscribe(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,n=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),H()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),H()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),H()).subscribe(()=>{Oo(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(_(i=>i.length>0),H()).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(_(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Zt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),H()).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(_(t=>!!t),H()).subscribe(()=>{Oo(this.providerContainer);let t=this.providerContainer?.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(_(t=>!!t),H()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Zt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),H()).subscribe(()=>{TI(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),H()).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(_(t=>!!t),H()).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(_(i=>!!i),H()).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(_(t=>!!t),H()).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(_(i=>!!i),H()).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(_(e=>e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(_(e=>!!e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(P0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return II(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.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(Jt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Yl(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(_(({from:e})=>e==="stopped"),H()).subscribe(()=>{this.initedAt=No(),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"ready":this.events.willReady$.next();break;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",Zt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Fo.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(H()).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",Zt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),z()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Ct({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:u})=>n.filter(o=>u?u.id===o.streamId:!0).map(({quality:o})=>o).sort((o,l)=>wI(o)?1:wI(l)?-1:L0(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let u={};for(let o of n)o.fps&&(u[o.quality]=o.fps);this.info.availableQualitiesFps$.next(u)})).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(z()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(_(n=>II(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(z((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(z((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(z()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(z()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(z()).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??{})})).add(e.providerOutput.currentBuffer$.pipe(G(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(Pd(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(Ct({hasLiveOffsetByPaused:Jt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),z(),G(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:u})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(u));return}this.hasLiveOffsetByPaused.next(!1)})).add(Ct({atLiveEdge:Ct({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ad({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:u,isLowLatency:o})=>{let l=this.getActiveLiveDelay(o);return n&&Math.abs(u)<l/1e3}),z(),Pd(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:u})=>n&&!u)).subscribe(this.info.atLiveEdge$)).add(Ct({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:u,duration:o})=>n&&(Math.abs(o)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),z(),Pd(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),z()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),z()).subscribe(this.info.volume$)).add(Ad({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Jt(e.providerOutput.endedEvent$.pipe(EI(!0)),e.providerOutput.seekedEvent$.pipe(EI(!1))).pipe(z()).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(G(n=>({id:n?`No${n}`:"NoProviders",category:Fo.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(H(),G(n=>n??No()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(H(),G(()=>No()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(H(),G(()=>No()-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(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new P(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(_(({to:n})=>n==="playing"),H()).subscribe(()=>i.next(!1)));let r=0,s=Jt(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return n&&!u}),z());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(Jt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Jt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),o=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),p;c==="CONNECTED"?p="second_screen":o?l?n?p="pip":u?p="fullscreen":p="inline":p="invisible":p="none",this.info.surface$.getValue()!==p&&this.info.surface$.next(p)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(G(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new xI;this.subscription.add(t),this.subscription.add(e.current$.pipe(z((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(_(i=>i.length>0),H()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=St(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(Jt(this.desiredState.videoTrack.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(G(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(){let e=this.providerContainer?.providerOutput;Oo(this.providerContainer),Oo(e),hS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>pS(t)),this.providerContainer.current$.subscribe(({type:t})=>ua("provider",t)),e.duration$.subscribe(t=>ua("duration",t)),e.availableVideoTracks$.pipe(_(t=>!!t.length),H()).subscribe(t=>ua("tracks",t)),this.events.fatalError$.subscribe(new we("fatalError")),this.events.managedError$.subscribe(new we("managedError")),e.position$.subscribe(new we("position")),e.currentVideoTrack$.pipe(G(t=>t?.quality)).subscribe(new we("quality")),this.info.currentBuffer$.subscribe(new we("buffer")),e.isBuffering$.subscribe(new we("isBuffering"))].forEach(t=>this.subscription.add(t)),ua("codecs",V.video.supportedCodecs)}initTracerSubscription(){let e=AI(this.tracer.log.bind(this.tracer)),t=AI(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(z()).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(Ct({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(_(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),z((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(_(i=>i>0),z()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(_(i=>i>0),z()).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(Ct({currentBuffer:this.info.currentBuffer$.pipe(_(i=>i.end>0),z((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(z())}).pipe(Rd(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(z()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(z()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(z()).subscribe(e("canChangePlaybackSpeed"))).add(Ct({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(_(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Rd(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(z(),_(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(z(),_(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(z()).subscribe(e("muted"))).add(this.info.volume$.pipe(z()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(z(),_(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ct({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(_(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Rd(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(z(),_(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?.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:Fo.DOM,message:String(r)})})};this.subscription.add(Jt(kd(document,"visibilitychange"),kd(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!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",Zt({quality:t,availableTracks:Zt(e),track:Zt(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()}};import{Subscription as qX,Observable as HX,Subject as jX,ValueSubject as QX,VideoQuality as GX}from"@vkontakte/videoplayer-shared";var WX=`@vkontakte/videoplayer-core@${Md}`;export{Ls as ChromecastState,jo as HttpConnectionType,HX as Observable,Pe as PlaybackState,Uo as Player,$s as PredefinedQualityLimits,WX as SDK_VERSION,jX as Subject,qX as Subscription,Qo as Surface,Md as VERSION,QX as ValueSubject,xt as VideoFormat,GX as VideoQuality,V as clientChecker,oa as isMobile};