@vkontakte/videoplayer-core 2.0.135 → 2.0.136-dev.0bf6b475.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 (119) hide show
  1. package/es2015.cjs.js +49 -56
  2. package/es2015.esm.js +43 -50
  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/index.d.ts +1 -0
  12. package/types/player/Player.d.ts +1 -0
  13. package/types/player/types.d.ts +4 -0
  14. package/types/providers/DashProvider/baseDashProvider.d.ts +2 -1
  15. package/types/providers/DashProvider/lib/LiveTextManager.d.ts +1 -1
  16. package/types/providers/DashProvider/lib/buffer.d.ts +2 -1
  17. package/types/providers/DashProvider/lib/fetcher.d.ts +2 -1
  18. package/types/providers/DashProvider/lib/player.d.ts +6 -1
  19. package/types/providers/DashProvider/lib/types.d.ts +2 -159
  20. package/types/providers/DashProvider/lib/utils.d.ts +1 -2
  21. package/types/providers/DashProviderNew/baseDashProvider.d.ts +2 -1
  22. package/types/providers/DashProviderNew/lib/LiveTextManager.d.ts +1 -1
  23. package/types/providers/DashProviderNew/lib/buffer.d.ts +2 -1
  24. package/types/providers/DashProviderNew/lib/fetcher.d.ts +2 -1
  25. package/types/providers/DashProviderNew/lib/player.d.ts +6 -1
  26. package/types/providers/DashProviderNew/lib/types.d.ts +2 -159
  27. package/types/providers/DashProviderNew/lib/utils.d.ts +1 -2
  28. package/types/providers/ProviderContainer/utils/formatsSupport.d.ts +0 -2
  29. package/types/providers/types.d.ts +1 -0
  30. package/types/providers/utils/error.d.ts +1 -0
  31. package/types/providers/{DashProvider/lib → utils}/parsers/index.d.ts +1 -1
  32. package/types/providers/{DashProviderNew/lib → utils}/parsers/mpd.d.ts +1 -1
  33. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/BoxModel.d.ts +4 -4
  34. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/BoxParser.d.ts +2 -2
  35. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/box.d.ts +8 -8
  36. package/types/providers/utils/parsers/mpeg/boxes/avc1.d.ts +8 -0
  37. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/equi.d.ts +2 -2
  38. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/ftyp.d.ts +2 -2
  39. package/types/providers/utils/parsers/mpeg/boxes/index.d.ts +26 -0
  40. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/mdat.d.ts +2 -2
  41. package/types/providers/utils/parsers/mpeg/boxes/mdia.d.ts +8 -0
  42. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/mfhd.d.ts +2 -2
  43. package/types/providers/utils/parsers/mpeg/boxes/minf.d.ts +8 -0
  44. package/types/providers/utils/parsers/mpeg/boxes/moof.d.ts +8 -0
  45. package/types/providers/utils/parsers/mpeg/boxes/moov.d.ts +8 -0
  46. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/mvhd.d.ts +2 -2
  47. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/prhd.d.ts +2 -2
  48. package/types/providers/utils/parsers/mpeg/boxes/proj.d.ts +8 -0
  49. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/sidx.d.ts +2 -2
  50. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/st3d.d.ts +2 -2
  51. package/types/providers/utils/parsers/mpeg/boxes/stbl.d.ts +8 -0
  52. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/stsd.d.ts +2 -2
  53. package/types/providers/utils/parsers/mpeg/boxes/sv3d.d.ts +8 -0
  54. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/tfdt.d.ts +2 -2
  55. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/tfhd.d.ts +2 -2
  56. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/tkhd.d.ts +2 -2
  57. package/types/providers/utils/parsers/mpeg/boxes/traf.d.ts +8 -0
  58. package/types/providers/utils/parsers/mpeg/boxes/trak.d.ts +8 -0
  59. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/trun.d.ts +2 -2
  60. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/unknown.d.ts +1 -1
  61. package/types/providers/utils/parsers/mpeg/boxes/uuid.d.ts +18 -0
  62. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/fullBox.d.ts +2 -2
  63. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/isobmff.d.ts +1 -1
  64. package/types/providers/utils/parsers/types.d.ts +159 -0
  65. package/types/providers/{DashProvider/lib → utils}/parsers/webm/webm.d.ts +1 -1
  66. package/types/utils/tuningConfig.d.ts +2 -0
  67. package/types/utils/videoFormat.d.ts +6 -1
  68. package/types/providers/DashProvider/lib/parsers/mpd.d.ts +0 -3
  69. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/avc1.d.ts +0 -8
  70. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/index.d.ts +0 -26
  71. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mdia.d.ts +0 -8
  72. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/minf.d.ts +0 -8
  73. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moof.d.ts +0 -8
  74. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moov.d.ts +0 -8
  75. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/proj.d.ts +0 -8
  76. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/stbl.d.ts +0 -8
  77. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/sv3d.d.ts +0 -8
  78. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/traf.d.ts +0 -8
  79. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/trak.d.ts +0 -8
  80. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/uuid.d.ts +0 -11
  81. package/types/providers/DashProviderNew/lib/parsers/ietf/index.d.ts +0 -13
  82. package/types/providers/DashProviderNew/lib/parsers/index.d.ts +0 -3
  83. package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxModel.d.ts +0 -20
  84. package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxParser.d.ts +0 -21
  85. package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxTypeEnum.d.ts +0 -30
  86. package/types/providers/DashProviderNew/lib/parsers/mpeg/box.d.ts +0 -74
  87. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/avc1.d.ts +0 -8
  88. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/equi.d.ts +0 -21
  89. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/ftyp.d.ts +0 -17
  90. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/index.d.ts +0 -26
  91. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mdat.d.ts +0 -15
  92. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mdia.d.ts +0 -8
  93. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mfhd.d.ts +0 -11
  94. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/minf.d.ts +0 -8
  95. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/moof.d.ts +0 -8
  96. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/moov.d.ts +0 -8
  97. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mvhd.d.ts +0 -35
  98. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/prhd.d.ts +0 -16
  99. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/proj.d.ts +0 -8
  100. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/sidx.d.ts +0 -48
  101. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/st3d.d.ts +0 -23
  102. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/stbl.d.ts +0 -8
  103. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/stsd.d.ts +0 -11
  104. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/sv3d.d.ts +0 -8
  105. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tfdt.d.ts +0 -17
  106. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tfhd.d.ts +0 -22
  107. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tkhd.d.ts +0 -42
  108. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/traf.d.ts +0 -8
  109. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/trak.d.ts +0 -8
  110. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/trun.d.ts +0 -31
  111. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/unknown.d.ts +0 -6
  112. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/uuid.d.ts +0 -11
  113. package/types/providers/DashProviderNew/lib/parsers/mpeg/fullBox.d.ts +0 -15
  114. package/types/providers/DashProviderNew/lib/parsers/mpeg/isobmff.d.ts +0 -12
  115. package/types/providers/DashProviderNew/lib/parsers/webm/ebml.d.ts +0 -76
  116. package/types/providers/DashProviderNew/lib/parsers/webm/webm.d.ts +0 -3
  117. /package/types/providers/{DashProvider/lib → utils}/parsers/ietf/index.d.ts +0 -0
  118. /package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/BoxTypeEnum.d.ts +0 -0
  119. /package/types/providers/{DashProvider/lib → utils}/parsers/webm/ebml.d.ts +0 -0
package/es2015.cjs.js CHANGED
@@ -1,127 +1,127 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.135
3
- * Wed, 02 Jul 2025 16:16:26 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-135/doc/
2
+ * @vkontakte/videoplayer-core v2.0.136-dev.0bf6b475.0
3
+ * Wed, 16 Jul 2025 12:58:24 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-136/doc/
5
5
  */
6
- "use strict";var DT=Object.create;var Zs=Object.defineProperty,CT=Object.defineProperties,VT=Object.getOwnPropertyDescriptor,OT=Object.getOwnPropertyDescriptors,_T=Object.getOwnPropertyNames,no=Object.getOwnPropertySymbols,FT=Object.getPrototypeOf,Zu=Object.prototype.hasOwnProperty,sp=Object.prototype.propertyIsEnumerable;var NT=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var pt=Math.pow,rp=(s,e,t)=>e in s?Zs(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,P=(s,e)=>{for(var t in e||(e={}))Zu.call(e,t)&&rp(s,t,e[t]);if(no)for(var t of no(e))sp.call(e,t)&&rp(s,t,e[t]);return s},F=(s,e)=>CT(s,OT(e));var ap=(s,e)=>{var t={};for(var i in s)Zu.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&no)for(var i of no(s))e.indexOf(i)<0&&sp.call(s,i)&&(t[i]=s[i]);return t};var g=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),UT=(s,e)=>{for(var t in e)Zs(s,t,{get:e[t],enumerable:!0})},np=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _T(e))!Zu.call(s,r)&&r!==t&&Zs(s,r,{get:()=>e[r],enumerable:!(i=VT(e,r))||i.enumerable});return s};var Z=(s,e,t)=>(t=s!=null?DT(FT(s)):{},np(e||!s||!s.__esModule?Zs(t,"default",{value:s,enumerable:!0}):t,s)),qT=s=>np(Zs({},"__esModule",{value:!0}),s);var k=(s,e,t)=>new Promise((i,r)=>{var a=u=>{try{o(t.next(u))}catch(l){r(l)}},n=u=>{try{o(t.throw(u))}catch(l){r(l)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(a,n);o((t=t.apply(s,e)).next())}),cr=function(s,e){this[0]=s,this[1]=e},pe=(s,e,t)=>{var i=(n,o,u,l)=>{try{var d=t[n](o),c=(o=d.value)instanceof cr,f=d.done;Promise.resolve(c?o[0]:o).then(p=>c?i(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:f})).catch(p=>i("throw",p,u,l))}catch(p){l(p)}},r=n=>a[n]=o=>new Promise((u,l)=>i(n,o,u,l)),a={};return t=t.apply(s,e),a[NT("asyncIterator")]=()=>a,r("next"),r("throw"),r("return"),a};var _e=g((tl,op)=>{"use strict";var ia=function(s){return s&&s.Math===Math&&s};op.exports=ia(typeof globalThis=="object"&&globalThis)||ia(typeof window=="object"&&window)||ia(typeof self=="object"&&self)||ia(typeof global=="object"&&global)||ia(typeof tl=="object"&&tl)||function(){return this}()||Function("return this")()});var it=g((jB,up)=>{"use strict";up.exports=function(s){try{return!!s()}catch(e){return!0}}});var ra=g((HB,lp)=>{"use strict";var jT=it();lp.exports=!jT(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var il=g((zB,hp)=>{"use strict";var HT=ra(),pp=Function.prototype,cp=pp.apply,dp=pp.call;hp.exports=typeof Reflect=="object"&&Reflect.apply||(HT?dp.bind(cp):function(){return dp.apply(cp,arguments)})});var Xe=g((QB,bp)=>{"use strict";var fp=ra(),mp=Function.prototype,rl=mp.call,zT=fp&&mp.bind.bind(rl,rl);bp.exports=fp?zT:function(s){return function(){return rl.apply(s,arguments)}}});var dr=g((GB,Sp)=>{"use strict";var gp=Xe(),QT=gp({}.toString),GT=gp("".slice);Sp.exports=function(s){return GT(QT(s),8,-1)}});var sl=g((WB,vp)=>{"use strict";var WT=dr(),YT=Xe();vp.exports=function(s){if(WT(s)==="Function")return YT(s)}});var Ve=g((YB,yp)=>{"use strict";var al=typeof document=="object"&&document.all;yp.exports=typeof al=="undefined"&&al!==void 0?function(s){return typeof s=="function"||s===al}:function(s){return typeof s=="function"}});var Lt=g((KB,Tp)=>{"use strict";var KT=it();Tp.exports=!KT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Bt=g((XB,Ip)=>{"use strict";var XT=ra(),lo=Function.prototype.call;Ip.exports=XT?lo.bind(lo):function(){return lo.apply(lo,arguments)}});var nl=g(wp=>{"use strict";var xp={}.propertyIsEnumerable,Ep=Object.getOwnPropertyDescriptor,JT=Ep&&!xp.call({1:2},1);wp.f=JT?function(e){var t=Ep(this,e);return!!t&&t.enumerable}:xp});var sa=g((ZB,Ap)=>{"use strict";Ap.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var kp=g((e$,Pp)=>{"use strict";var ZT=Xe(),eI=it(),tI=dr(),ol=Object,iI=ZT("".split);Pp.exports=eI(function(){return!ol("z").propertyIsEnumerable(0)})?function(s){return tI(s)==="String"?iI(s,""):ol(s)}:ol});var Br=g((t$,Rp)=>{"use strict";Rp.exports=function(s){return s==null}});var Qi=g((i$,Mp)=>{"use strict";var rI=Br(),sI=TypeError;Mp.exports=function(s){if(rI(s))throw new sI("Can't call method on "+s);return s}});var pr=g((r$,Lp)=>{"use strict";var aI=kp(),nI=Qi();Lp.exports=function(s){return aI(nI(s))}});var $t=g((s$,Bp)=>{"use strict";var oI=Ve();Bp.exports=function(s){return typeof s=="object"?s!==null:oI(s)}});var $r=g((a$,$p)=>{"use strict";$p.exports={}});var Ri=g((n$,Cp)=>{"use strict";var ul=$r(),ll=_e(),uI=Ve(),Dp=function(s){return uI(s)?s:void 0};Cp.exports=function(s,e){return arguments.length<2?Dp(ul[s])||Dp(ll[s]):ul[s]&&ul[s][e]||ll[s]&&ll[s][e]}});var aa=g((o$,Vp)=>{"use strict";var lI=Xe();Vp.exports=lI({}.isPrototypeOf)});var hr=g((u$,Fp)=>{"use strict";var cI=_e(),Op=cI.navigator,_p=Op&&Op.userAgent;Fp.exports=_p?String(_p):""});var dl=g((l$,zp)=>{"use strict";var Hp=_e(),cl=hr(),Np=Hp.process,Up=Hp.Deno,qp=Np&&Np.versions||Up&&Up.version,jp=qp&&qp.v8,Jt,co;jp&&(Jt=jp.split("."),co=Jt[0]>0&&Jt[0]<4?1:+(Jt[0]+Jt[1]));!co&&cl&&(Jt=cl.match(/Edge\/(\d+)/),(!Jt||Jt[1]>=74)&&(Jt=cl.match(/Chrome\/(\d+)/),Jt&&(co=+Jt[1])));zp.exports=co});var pl=g((c$,Gp)=>{"use strict";var Qp=dl(),dI=it(),pI=_e(),hI=pI.String;Gp.exports=!!Object.getOwnPropertySymbols&&!dI(function(){var s=Symbol("symbol detection");return!hI(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Qp&&Qp<41})});var hl=g((d$,Wp)=>{"use strict";var fI=pl();Wp.exports=fI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var fl=g((p$,Yp)=>{"use strict";var mI=Ri(),bI=Ve(),gI=aa(),SI=hl(),vI=Object;Yp.exports=SI?function(s){return typeof s=="symbol"}:function(s){var e=mI("Symbol");return bI(e)&&gI(e.prototype,vI(s))}});var na=g((h$,Kp)=>{"use strict";var yI=String;Kp.exports=function(s){try{return yI(s)}catch(e){return"Object"}}});var oi=g((f$,Xp)=>{"use strict";var TI=Ve(),II=na(),xI=TypeError;Xp.exports=function(s){if(TI(s))return s;throw new xI(II(s)+" is not a function")}});var oa=g((m$,Jp)=>{"use strict";var EI=oi(),wI=Br();Jp.exports=function(s,e){var t=s[e];return wI(t)?void 0:EI(t)}});var eh=g((b$,Zp)=>{"use strict";var ml=Bt(),bl=Ve(),gl=$t(),AI=TypeError;Zp.exports=function(s,e){var t,i;if(e==="string"&&bl(t=s.toString)&&!gl(i=ml(t,s))||bl(t=s.valueOf)&&!gl(i=ml(t,s))||e!=="string"&&bl(t=s.toString)&&!gl(i=ml(t,s)))return i;throw new AI("Can't convert object to primitive value")}});var Zt=g((g$,th)=>{"use strict";th.exports=!0});var sh=g((S$,rh)=>{"use strict";var ih=_e(),PI=Object.defineProperty;rh.exports=function(s,e){try{PI(ih,s,{value:e,configurable:!0,writable:!0})}catch(t){ih[s]=e}return e}});var ua=g((v$,oh)=>{"use strict";var kI=Zt(),RI=_e(),MI=sh(),ah="__core-js_shared__",nh=oh.exports=RI[ah]||MI(ah,{});(nh.versions||(nh.versions=[])).push({version:"3.38.0",mode:kI?"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 Sl=g((y$,lh)=>{"use strict";var uh=ua();lh.exports=function(s,e){return uh[s]||(uh[s]=e||{})}});var Dr=g((T$,ch)=>{"use strict";var LI=Qi(),BI=Object;ch.exports=function(s){return BI(LI(s))}});var ei=g((I$,dh)=>{"use strict";var $I=Xe(),DI=Dr(),CI=$I({}.hasOwnProperty);dh.exports=Object.hasOwn||function(e,t){return CI(DI(e),t)}});var vl=g((x$,ph)=>{"use strict";var VI=Xe(),OI=0,_I=Math.random(),FI=VI(1 .toString);ph.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+FI(++OI+_I,36)}});var rt=g((E$,fh)=>{"use strict";var NI=_e(),UI=Sl(),hh=ei(),qI=vl(),jI=pl(),HI=hl(),Cr=NI.Symbol,yl=UI("wks"),zI=HI?Cr.for||Cr:Cr&&Cr.withoutSetter||qI;fh.exports=function(s){return hh(yl,s)||(yl[s]=jI&&hh(Cr,s)?Cr[s]:zI("Symbol."+s)),yl[s]}});var Sh=g((w$,gh)=>{"use strict";var QI=Bt(),mh=$t(),bh=fl(),GI=oa(),WI=eh(),YI=rt(),KI=TypeError,XI=YI("toPrimitive");gh.exports=function(s,e){if(!mh(s)||bh(s))return s;var t=GI(s,XI),i;if(t){if(e===void 0&&(e="default"),i=QI(t,s,e),!mh(i)||bh(i))return i;throw new KI("Can't convert object to primitive value")}return e===void 0&&(e="number"),WI(s,e)}});var Tl=g((A$,vh)=>{"use strict";var JI=Sh(),ZI=fl();vh.exports=function(s){var e=JI(s,"string");return ZI(e)?e:e+""}});var po=g((P$,Th)=>{"use strict";var ex=_e(),yh=$t(),Il=ex.document,tx=yh(Il)&&yh(Il.createElement);Th.exports=function(s){return tx?Il.createElement(s):{}}});var xl=g((k$,Ih)=>{"use strict";var ix=Lt(),rx=it(),sx=po();Ih.exports=!ix&&!rx(function(){return Object.defineProperty(sx("div"),"a",{get:function(){return 7}}).a!==7})});var wh=g(Eh=>{"use strict";var ax=Lt(),nx=Bt(),ox=nl(),ux=sa(),lx=pr(),cx=Tl(),dx=ei(),px=xl(),xh=Object.getOwnPropertyDescriptor;Eh.f=ax?xh:function(e,t){if(e=lx(e),t=cx(t),px)try{return xh(e,t)}catch(i){}if(dx(e,t))return ux(!nx(ox.f,e,t),e[t])}});var El=g((M$,Ah)=>{"use strict";var hx=it(),fx=Ve(),mx=/#|\.prototype\./,la=function(s,e){var t=gx[bx(s)];return t===vx?!0:t===Sx?!1:fx(e)?hx(e):!!e},bx=la.normalize=function(s){return String(s).replace(mx,".").toLowerCase()},gx=la.data={},Sx=la.NATIVE="N",vx=la.POLYFILL="P";Ah.exports=la});var Vr=g((L$,kh)=>{"use strict";var Ph=sl(),yx=oi(),Tx=ra(),Ix=Ph(Ph.bind);kh.exports=function(s,e){return yx(s),e===void 0?s:Tx?Ix(s,e):function(){return s.apply(e,arguments)}}});var wl=g((B$,Rh)=>{"use strict";var xx=Lt(),Ex=it();Rh.exports=xx&&Ex(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ui=g(($$,Mh)=>{"use strict";var wx=$t(),Ax=String,Px=TypeError;Mh.exports=function(s){if(wx(s))return s;throw new Px(Ax(s)+" is not an object")}});var fr=g(Bh=>{"use strict";var kx=Lt(),Rx=xl(),Mx=wl(),ho=ui(),Lh=Tl(),Lx=TypeError,Al=Object.defineProperty,Bx=Object.getOwnPropertyDescriptor,Pl="enumerable",kl="configurable",Rl="writable";Bh.f=kx?Mx?function(e,t,i){if(ho(e),t=Lh(t),ho(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Rl in i&&!i[Rl]){var r=Bx(e,t);r&&r[Rl]&&(e[t]=i.value,i={configurable:kl in i?i[kl]:r[kl],enumerable:Pl in i?i[Pl]:r[Pl],writable:!1})}return Al(e,t,i)}:Al:function(e,t,i){if(ho(e),t=Lh(t),ho(i),Rx)try{return Al(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Lx("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Or=g((C$,$h)=>{"use strict";var $x=Lt(),Dx=fr(),Cx=sa();$h.exports=$x?function(s,e,t){return Dx.f(s,e,Cx(1,t))}:function(s,e,t){return s[e]=t,s}});var je=g((V$,Ch)=>{"use strict";var ca=_e(),Vx=il(),Ox=sl(),_x=Ve(),Fx=wh().f,Nx=El(),_r=$r(),Ux=Vr(),Fr=Or(),Dh=ei();ua();var qx=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 Vx(s,this,arguments)};return e.prototype=s.prototype,e};Ch.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?ca:r?ca[t]:ca[t]&&ca[t].prototype,o=i?_r:_r[t]||Fr(_r,t,{})[t],u=o.prototype,l,d,c,f,p,h,b,S,v;for(f in e)l=Nx(i?f:t+(r?".":"#")+f,s.forced),d=!l&&n&&Dh(n,f),h=o[f],d&&(s.dontCallGetSet?(v=Fx(n,f),b=v&&v.value):b=n[f]),p=d&&b?b:e[f],!(!l&&!a&&typeof h==typeof p)&&(s.bind&&d?S=Ux(p,ca):s.wrap&&d?S=qx(p):a&&_x(p)?S=Ox(p):S=p,(s.sham||p&&p.sham||h&&h.sham)&&Fr(S,"sham",!0),Fr(o,f,S),a&&(c=t+"Prototype",Dh(_r,c)||Fr(_r,c,{}),Fr(_r[c],f,p),s.real&&u&&(l||!u[f])&&Fr(u,f,p)))}});var Oh=g((O$,Vh)=>{"use strict";var jx=Math.ceil,Hx=Math.floor;Vh.exports=Math.trunc||function(e){var t=+e;return(t>0?Hx:jx)(t)}});var da=g((_$,_h)=>{"use strict";var zx=Oh();_h.exports=function(s){var e=+s;return e!==e||e===0?0:zx(e)}});var Nh=g((F$,Fh)=>{"use strict";var Qx=da(),Gx=Math.max,Wx=Math.min;Fh.exports=function(s,e){var t=Qx(s);return t<0?Gx(t+e,0):Wx(t,e)}});var Ml=g((N$,Uh)=>{"use strict";var Yx=da(),Kx=Math.min;Uh.exports=function(s){var e=Yx(s);return e>0?Kx(e,9007199254740991):0}});var Nr=g((U$,qh)=>{"use strict";var Xx=Ml();qh.exports=function(s){return Xx(s.length)}});var Ll=g((q$,Hh)=>{"use strict";var Jx=pr(),Zx=Nh(),eE=Nr(),jh=function(s){return function(e,t,i){var r=Jx(e),a=eE(r);if(a===0)return!s&&-1;var n=Zx(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}};Hh.exports={includes:jh(!0),indexOf:jh(!1)}});var pa=g((j$,zh)=>{"use strict";zh.exports=function(){}});var Qh=g(()=>{"use strict";var tE=je(),iE=Ll().includes,rE=it(),sE=pa(),aE=rE(function(){return!Array(1).includes()});tE({target:"Array",proto:!0,forced:aE},{includes:function(e){return iE(this,e,arguments.length>1?arguments[1]:void 0)}});sE("includes")});var Gi=g((Q$,Gh)=>{"use strict";var nE=Ri();Gh.exports=nE});var Yh=g((G$,Wh)=>{"use strict";Qh();var oE=Gi();Wh.exports=oE("Array","includes")});var Xh=g((W$,Kh)=>{"use strict";var uE=Yh();Kh.exports=uE});var Dt=g((Y$,Jh)=>{"use strict";var lE=Xh();Jh.exports=lE});var mo=g((nD,tf)=>{"use strict";var dE=Sl(),pE=vl(),ef=dE("keys");tf.exports=function(s){return ef[s]||(ef[s]=pE(s))}});var sf=g((oD,rf)=>{"use strict";var hE=it();rf.exports=!hE(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var bo=g((uD,nf)=>{"use strict";var fE=ei(),mE=Ve(),bE=Dr(),gE=mo(),SE=sf(),af=gE("IE_PROTO"),Bl=Object,vE=Bl.prototype;nf.exports=SE?Bl.getPrototypeOf:function(s){var e=bE(s);if(fE(e,af))return e[af];var t=e.constructor;return mE(t)&&e instanceof t?t.prototype:e instanceof Bl?vE:null}});var go=g((lD,of)=>{"use strict";of.exports={}});var cf=g((cD,lf)=>{"use strict";var yE=Xe(),$l=ei(),TE=pr(),IE=Ll().indexOf,xE=go(),uf=yE([].push);lf.exports=function(s,e){var t=TE(s),i=0,r=[],a;for(a in t)!$l(xE,a)&&$l(t,a)&&uf(r,a);for(;e.length>i;)$l(t,a=e[i++])&&(~IE(r,a)||uf(r,a));return r}});var Dl=g((dD,df)=>{"use strict";df.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Cl=g((pD,pf)=>{"use strict";var EE=cf(),wE=Dl();pf.exports=Object.keys||function(e){return EE(e,wE)}});var Vl=g((hD,gf)=>{"use strict";var ff=Lt(),AE=it(),mf=Xe(),PE=bo(),kE=Cl(),RE=pr(),ME=nl().f,bf=mf(ME),LE=mf([].push),BE=ff&&AE(function(){var s=Object.create(null);return s[2]=2,!bf(s,2)}),hf=function(s){return function(e){for(var t=RE(e),i=kE(t),r=BE&&PE(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!ff||(r?u in t:bf(t,u)))&&LE(o,s?[u,t[u]]:t[u]);return o}};gf.exports={entries:hf(!0),values:hf(!1)}});var Sf=g(()=>{"use strict";var $E=je(),DE=Vl().entries;$E({target:"Object",stat:!0},{entries:function(e){return DE(e)}})});var yf=g((bD,vf)=>{"use strict";Sf();var CE=$r();vf.exports=CE.Object.entries});var If=g((gD,Tf)=>{"use strict";var VE=yf();Tf.exports=VE});var mr=g((SD,xf)=>{"use strict";var OE=If();xf.exports=OE});var br=g((vD,Ef)=>{"use strict";Ef.exports={}});var Pf=g((yD,Af)=>{"use strict";var _E=_e(),FE=Ve(),wf=_E.WeakMap;Af.exports=FE(wf)&&/native code/.test(String(wf))});var Nl=g((TD,Mf)=>{"use strict";var NE=Pf(),Rf=_e(),UE=$t(),qE=Or(),Ol=ei(),_l=ua(),jE=mo(),HE=go(),kf="Object already initialized",Fl=Rf.TypeError,zE=Rf.WeakMap,So,ha,vo,QE=function(s){return vo(s)?ha(s):So(s,{})},GE=function(s){return function(e){var t;if(!UE(e)||(t=ha(e)).type!==s)throw new Fl("Incompatible receiver, "+s+" required");return t}};NE||_l.state?(ti=_l.state||(_l.state=new zE),ti.get=ti.get,ti.has=ti.has,ti.set=ti.set,So=function(s,e){if(ti.has(s))throw new Fl(kf);return e.facade=s,ti.set(s,e),e},ha=function(s){return ti.get(s)||{}},vo=function(s){return ti.has(s)}):(gr=jE("state"),HE[gr]=!0,So=function(s,e){if(Ol(s,gr))throw new Fl(kf);return e.facade=s,qE(s,gr,e),e},ha=function(s){return Ol(s,gr)?s[gr]:{}},vo=function(s){return Ol(s,gr)});var ti,gr;Mf.exports={set:So,get:ha,has:vo,enforce:QE,getterFor:GE}});var jl=g((ID,Bf)=>{"use strict";var Ul=Lt(),WE=ei(),Lf=Function.prototype,YE=Ul&&Object.getOwnPropertyDescriptor,ql=WE(Lf,"name"),KE=ql&&function(){}.name==="something",XE=ql&&(!Ul||Ul&&YE(Lf,"name").configurable);Bf.exports={EXISTS:ql,PROPER:KE,CONFIGURABLE:XE}});var Df=g($f=>{"use strict";var JE=Lt(),ZE=wl(),ew=fr(),tw=ui(),iw=pr(),rw=Cl();$f.f=JE&&!ZE?Object.defineProperties:function(e,t){tw(e);for(var i=iw(t),r=rw(t),a=r.length,n=0,o;a>n;)ew.f(e,o=r[n++],i[o]);return e}});var Hl=g((ED,Cf)=>{"use strict";var sw=Ri();Cf.exports=sw("document","documentElement")});var Wl=g((wD,qf)=>{"use strict";var aw=ui(),nw=Df(),Vf=Dl(),ow=go(),uw=Hl(),lw=po(),cw=mo(),Of=">",_f="<",Ql="prototype",Gl="script",Nf=cw("IE_PROTO"),zl=function(){},Uf=function(s){return _f+Gl+Of+s+_f+"/"+Gl+Of},Ff=function(s){s.write(Uf("")),s.close();var e=s.parentWindow.Object;return s=null,e},dw=function(){var s=lw("iframe"),e="java"+Gl+":",t;return s.style.display="none",uw.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Uf("document.F=Object")),t.close(),t.F},yo,To=function(){try{yo=new ActiveXObject("htmlfile")}catch(e){}To=typeof document!="undefined"?document.domain&&yo?Ff(yo):dw():Ff(yo);for(var s=Vf.length;s--;)delete To[Ql][Vf[s]];return To()};ow[Nf]=!0;qf.exports=Object.create||function(e,t){var i;return e!==null?(zl[Ql]=aw(e),i=new zl,zl[Ql]=null,i[Nf]=e):i=To(),t===void 0?i:nw.f(i,t)}});var Ur=g((AD,jf)=>{"use strict";var pw=Or();jf.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:pw(s,e,t),s}});var Jl=g((PD,Qf)=>{"use strict";var hw=it(),fw=Ve(),mw=$t(),bw=Wl(),Hf=bo(),gw=Ur(),Sw=rt(),vw=Zt(),Xl=Sw("iterator"),zf=!1,Mi,Yl,Kl;[].keys&&(Kl=[].keys(),"next"in Kl?(Yl=Hf(Hf(Kl)),Yl!==Object.prototype&&(Mi=Yl)):zf=!0);var yw=!mw(Mi)||hw(function(){var s={};return Mi[Xl].call(s)!==s});yw?Mi={}:vw&&(Mi=bw(Mi));fw(Mi[Xl])||gw(Mi,Xl,function(){return this});Qf.exports={IteratorPrototype:Mi,BUGGY_SAFARI_ITERATORS:zf}});var Io=g((kD,Wf)=>{"use strict";var Tw=rt(),Iw=Tw("toStringTag"),Gf={};Gf[Iw]="z";Wf.exports=String(Gf)==="[object z]"});var fa=g((RD,Yf)=>{"use strict";var xw=Io(),Ew=Ve(),xo=dr(),ww=rt(),Aw=ww("toStringTag"),Pw=Object,kw=xo(function(){return arguments}())==="Arguments",Rw=function(s,e){try{return s[e]}catch(t){}};Yf.exports=xw?xo:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Rw(e=Pw(s),Aw))=="string"?t:kw?xo(e):(i=xo(e))==="Object"&&Ew(e.callee)?"Arguments":i}});var Xf=g((MD,Kf)=>{"use strict";var Mw=Io(),Lw=fa();Kf.exports=Mw?{}.toString:function(){return"[object "+Lw(this)+"]"}});var ma=g((LD,Zf)=>{"use strict";var Bw=Io(),$w=fr().f,Dw=Or(),Cw=ei(),Vw=Xf(),Ow=rt(),Jf=Ow("toStringTag");Zf.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(Cw(r,Jf)||$w(r,Jf,{configurable:!0,value:e}),i&&!Bw&&Dw(r,"toString",Vw))}});var tm=g((BD,em)=>{"use strict";var _w=Jl().IteratorPrototype,Fw=Wl(),Nw=sa(),Uw=ma(),qw=br(),jw=function(){return this};em.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Fw(_w,{next:Nw(+!i,t)}),Uw(s,r,!1,!0),qw[r]=jw,s}});var rm=g(($D,im)=>{"use strict";var Hw=Xe(),zw=oi();im.exports=function(s,e,t){try{return Hw(zw(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var am=g((DD,sm)=>{"use strict";var Qw=$t();sm.exports=function(s){return Qw(s)||s===null}});var om=g((CD,nm)=>{"use strict";var Gw=am(),Ww=String,Yw=TypeError;nm.exports=function(s){if(Gw(s))return s;throw new Yw("Can't set "+Ww(s)+" as a prototype")}});var Zl=g((VD,um)=>{"use strict";var Kw=rm(),Xw=$t(),Jw=Qi(),Zw=om();um.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=Kw(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return Jw(r),Zw(a),Xw(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var vm=g((OD,Sm)=>{"use strict";var eA=je(),tA=Bt(),Eo=Zt(),bm=jl(),iA=Ve(),rA=tm(),lm=bo(),cm=Zl(),sA=ma(),aA=Or(),ec=Ur(),nA=rt(),dm=br(),gm=Jl(),oA=bm.PROPER,uA=bm.CONFIGURABLE,pm=gm.IteratorPrototype,wo=gm.BUGGY_SAFARI_ITERATORS,ba=nA("iterator"),hm="keys",ga="values",fm="entries",mm=function(){return this};Sm.exports=function(s,e,t,i,r,a,n){rA(t,e,i);var o=function(v){if(v===r&&f)return f;if(!wo&&v&&v in d)return d[v];switch(v){case hm:return function(){return new t(this,v)};case ga:return function(){return new t(this,v)};case fm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[ba]||d["@@iterator"]||r&&d[r],f=!wo&&c||o(r),p=e==="Array"&&d.entries||c,h,b,S;if(p&&(h=lm(p.call(new s)),h!==Object.prototype&&h.next&&(!Eo&&lm(h)!==pm&&(cm?cm(h,pm):iA(h[ba])||ec(h,ba,mm)),sA(h,u,!0,!0),Eo&&(dm[u]=mm))),oA&&r===ga&&c&&c.name!==ga&&(!Eo&&uA?aA(d,"name",ga):(l=!0,f=function(){return tA(c,this)})),r)if(b={values:o(ga),keys:a?f:o(hm),entries:o(fm)},n)for(S in b)(wo||l||!(S in d))&&ec(d,S,b[S]);else eA({target:e,proto:!0,forced:wo||l},b);return(!Eo||n)&&d[ba]!==f&&ec(d,ba,f,{name:r}),dm[e]=f,b}});var Tm=g((_D,ym)=>{"use strict";ym.exports=function(s,e){return{value:s,done:e}}});var ic=g((FD,Am)=>{"use strict";var lA=pr(),tc=pa(),Im=br(),Em=Nl(),cA=fr().f,dA=vm(),Ao=Tm(),pA=Zt(),hA=Lt(),wm="Array Iterator",fA=Em.set,mA=Em.getterFor(wm);Am.exports=dA(Array,"Array",function(s,e){fA(this,{type:wm,target:lA(s),index:0,kind:e})},function(){var s=mA(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,Ao(void 0,!0);switch(s.kind){case"keys":return Ao(t,!1);case"values":return Ao(e[t],!1)}return Ao([t,e[t]],!1)},"values");var xm=Im.Arguments=Im.Array;tc("keys");tc("values");tc("entries");if(!pA&&hA&&xm.name!=="values")try{cA(xm,"name",{value:"values"})}catch(s){}});var km=g((ND,Pm)=>{"use strict";var bA=rt(),gA=br(),SA=bA("iterator"),vA=Array.prototype;Pm.exports=function(s){return s!==void 0&&(gA.Array===s||vA[SA]===s)}});var rc=g((UD,Mm)=>{"use strict";var yA=fa(),Rm=oa(),TA=Br(),IA=br(),xA=rt(),EA=xA("iterator");Mm.exports=function(s){if(!TA(s))return Rm(s,EA)||Rm(s,"@@iterator")||IA[yA(s)]}});var Bm=g((qD,Lm)=>{"use strict";var wA=Bt(),AA=oi(),PA=ui(),kA=na(),RA=rc(),MA=TypeError;Lm.exports=function(s,e){var t=arguments.length<2?RA(s):e;if(AA(t))return PA(wA(t,s));throw new MA(kA(s)+" is not iterable")}});var Cm=g((jD,Dm)=>{"use strict";var LA=Bt(),$m=ui(),BA=oa();Dm.exports=function(s,e,t){var i,r;$m(s);try{if(i=BA(s,"return"),!i){if(e==="throw")throw t;return t}i=LA(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return $m(i),t}});var ko=g((HD,Fm)=>{"use strict";var $A=Vr(),DA=Bt(),CA=ui(),VA=na(),OA=km(),_A=Nr(),Vm=aa(),FA=Bm(),NA=rc(),Om=Cm(),UA=TypeError,Po=function(s,e){this.stopped=s,this.result=e},_m=Po.prototype;Fm.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=$A(e,i),l,d,c,f,p,h,b,S=function(y){return l&&Om(l,"normal",y),new Po(!0,y)},v=function(y){return r?(CA(y),o?u(y[0],y[1],S):u(y[0],y[1])):o?u(y,S):u(y)};if(a)l=s.iterator;else if(n)l=s;else{if(d=NA(s),!d)throw new UA(VA(s)+" is not iterable");if(OA(d)){for(c=0,f=_A(s);f>c;c++)if(p=v(s[c]),p&&Vm(_m,p))return p;return new Po(!1)}l=FA(s,d)}for(h=a?s.next:l.next;!(b=DA(h,l)).done;){try{p=v(b.value)}catch(y){Om(l,"throw",y)}if(typeof p=="object"&&p&&Vm(_m,p))return p}return new Po(!1)}});var Um=g((zD,Nm)=>{"use strict";var qA=Lt(),jA=fr(),HA=sa();Nm.exports=function(s,e,t){qA?jA.f(s,e,HA(0,t)):s[e]=t}});var qm=g(()=>{"use strict";var zA=je(),QA=ko(),GA=Um();zA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return QA(e,function(i,r){GA(t,i,r)},{AS_ENTRIES:!0}),t}})});var Hm=g((WD,jm)=>{"use strict";ic();qm();var WA=$r();jm.exports=WA.Object.fromEntries});var Qm=g((YD,zm)=>{"use strict";zm.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=g(()=>{"use strict";ic();var YA=Qm(),KA=_e(),XA=ma(),Gm=br();for(Ro in YA)XA(KA[Ro],Ro),Gm[Ro]=Gm.Array;var Ro});var Km=g((JD,Ym)=>{"use strict";var JA=Hm();Wm();Ym.exports=JA});var sc=g((ZD,Xm)=>{"use strict";var ZA=Km();Xm.exports=ZA});var Jm=g(()=>{"use strict"});var ac=g((i0,Zm)=>{"use strict";var Sa=_e(),eP=hr(),tP=dr(),Mo=function(s){return eP.slice(0,s.length)===s};Zm.exports=function(){return Mo("Bun/")?"BUN":Mo("Cloudflare-Workers")?"CLOUDFLARE":Mo("Deno/")?"DENO":Mo("Node.js/")?"NODE":Sa.Bun&&typeof Bun.version=="string"?"BUN":Sa.Deno&&typeof Deno.version=="object"?"DENO":tP(Sa.process)==="process"?"NODE":Sa.window&&Sa.document?"BROWSER":"REST"}()});var Lo=g((r0,eb)=>{"use strict";var iP=ac();eb.exports=iP==="NODE"});var ib=g((s0,tb)=>{"use strict";var rP=fr();tb.exports=function(s,e,t){return rP.f(s,e,t)}});var ab=g((a0,sb)=>{"use strict";var sP=Ri(),aP=ib(),nP=rt(),oP=Lt(),rb=nP("species");sb.exports=function(s){var e=sP(s);oP&&e&&!e[rb]&&aP(e,rb,{configurable:!0,get:function(){return this}})}});var ob=g((n0,nb)=>{"use strict";var uP=aa(),lP=TypeError;nb.exports=function(s,e){if(uP(e,s))return s;throw new lP("Incorrect invocation")}});var oc=g((o0,ub)=>{"use strict";var cP=Xe(),dP=Ve(),nc=ua(),pP=cP(Function.toString);dP(nc.inspectSource)||(nc.inspectSource=function(s){return pP(s)});ub.exports=nc.inspectSource});var lc=g((u0,hb)=>{"use strict";var hP=Xe(),fP=it(),lb=Ve(),mP=fa(),bP=Ri(),gP=oc(),cb=function(){},db=bP("Reflect","construct"),uc=/^\s*(?:class|function)\b/,SP=hP(uc.exec),vP=!uc.test(cb),va=function(e){if(!lb(e))return!1;try{return db(cb,[],e),!0}catch(t){return!1}},pb=function(e){if(!lb(e))return!1;switch(mP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return vP||!!SP(uc,gP(e))}catch(t){return!0}};pb.sham=!0;hb.exports=!db||fP(function(){var s;return va(va.call)||!va(Object)||!va(function(){s=!0})||s})?pb:va});var mb=g((l0,fb)=>{"use strict";var yP=lc(),TP=na(),IP=TypeError;fb.exports=function(s){if(yP(s))return s;throw new IP(TP(s)+" is not a constructor")}});var cc=g((c0,gb)=>{"use strict";var bb=ui(),xP=mb(),EP=Br(),wP=rt(),AP=wP("species");gb.exports=function(s,e){var t=bb(s).constructor,i;return t===void 0||EP(i=bb(t)[AP])?e:xP(i)}});var vb=g((d0,Sb)=>{"use strict";var PP=Xe();Sb.exports=PP([].slice)});var Tb=g((p0,yb)=>{"use strict";var kP=TypeError;yb.exports=function(s,e){if(s<e)throw new kP("Not enough arguments");return s}});var dc=g((h0,Ib)=>{"use strict";var RP=hr();Ib.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(RP)});var yc=g((f0,Lb)=>{"use strict";var Ct=_e(),MP=il(),LP=Vr(),xb=Ve(),BP=ei(),Mb=it(),Eb=Hl(),$P=vb(),wb=po(),DP=Tb(),CP=dc(),VP=Lo(),gc=Ct.setImmediate,Sc=Ct.clearImmediate,OP=Ct.process,pc=Ct.Dispatch,_P=Ct.Function,Ab=Ct.MessageChannel,FP=Ct.String,hc=0,ya={},Pb="onreadystatechange",Ta,Sr,fc,mc;Mb(function(){Ta=Ct.location});var vc=function(s){if(BP(ya,s)){var e=ya[s];delete ya[s],e()}},bc=function(s){return function(){vc(s)}},kb=function(s){vc(s.data)},Rb=function(s){Ct.postMessage(FP(s),Ta.protocol+"//"+Ta.host)};(!gc||!Sc)&&(gc=function(e){DP(arguments.length,1);var t=xb(e)?e:_P(e),i=$P(arguments,1);return ya[++hc]=function(){MP(t,void 0,i)},Sr(hc),hc},Sc=function(e){delete ya[e]},VP?Sr=function(s){OP.nextTick(bc(s))}:pc&&pc.now?Sr=function(s){pc.now(bc(s))}:Ab&&!CP?(fc=new Ab,mc=fc.port2,fc.port1.onmessage=kb,Sr=LP(mc.postMessage,mc)):Ct.addEventListener&&xb(Ct.postMessage)&&!Ct.importScripts&&Ta&&Ta.protocol!=="file:"&&!Mb(Rb)?(Sr=Rb,Ct.addEventListener("message",kb,!1)):Pb in wb("script")?Sr=function(s){Eb.appendChild(wb("script"))[Pb]=function(){Eb.removeChild(this),vc(s)}}:Sr=function(s){setTimeout(bc(s),0)});Lb.exports={set:gc,clear:Sc}});var Db=g((m0,$b)=>{"use strict";var Bb=_e(),NP=Lt(),UP=Object.getOwnPropertyDescriptor;$b.exports=function(s){if(!NP)return Bb[s];var e=UP(Bb,s);return e&&e.value}});var Tc=g((b0,Vb)=>{"use strict";var Cb=function(){this.head=null,this.tail=null};Cb.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}}};Vb.exports=Cb});var _b=g((g0,Ob)=>{"use strict";var qP=hr();Ob.exports=/ipad|iphone|ipod/i.test(qP)&&typeof Pebble!="undefined"});var Nb=g((S0,Fb)=>{"use strict";var jP=hr();Fb.exports=/web0s(?!.*chrome)/i.test(jP)});var Gb=g((v0,Qb)=>{"use strict";var jr=_e(),HP=Db(),Ub=Vr(),Ic=yc().set,zP=Tc(),QP=dc(),GP=_b(),WP=Nb(),xc=Lo(),qb=jr.MutationObserver||jr.WebKitMutationObserver,jb=jr.document,Hb=jr.process,Bo=jr.Promise,Ac=HP("queueMicrotask"),qr,Ec,wc,$o,zb;Ac||(Ia=new zP,xa=function(){var s,e;for(xc&&(s=Hb.domain)&&s.exit();e=Ia.get();)try{e()}catch(t){throw Ia.head&&qr(),t}s&&s.enter()},!QP&&!xc&&!WP&&qb&&jb?(Ec=!0,wc=jb.createTextNode(""),new qb(xa).observe(wc,{characterData:!0}),qr=function(){wc.data=Ec=!Ec}):!GP&&Bo&&Bo.resolve?($o=Bo.resolve(void 0),$o.constructor=Bo,zb=Ub($o.then,$o),qr=function(){zb(xa)}):xc?qr=function(){Hb.nextTick(xa)}:(Ic=Ub(Ic,jr),qr=function(){Ic(xa)}),Ac=function(s){Ia.head||qr(),Ia.add(s)});var Ia,xa;Qb.exports=Ac});var Yb=g((y0,Wb)=>{"use strict";Wb.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var Do=g((T0,Kb)=>{"use strict";Kb.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var vr=g((I0,Xb)=>{"use strict";var YP=_e();Xb.exports=YP.Promise});var Hr=g((x0,tg)=>{"use strict";var KP=_e(),Ea=vr(),XP=Ve(),JP=El(),ZP=oc(),ek=rt(),Jb=ac(),tk=Zt(),Pc=dl(),Zb=Ea&&Ea.prototype,ik=ek("species"),kc=!1,eg=XP(KP.PromiseRejectionEvent),rk=JP("Promise",function(){var s=ZP(Ea),e=s!==String(Ea);if(!e&&Pc===66||tk&&!(Zb.catch&&Zb.finally))return!0;if(!Pc||Pc<51||!/native code/.test(s)){var t=new Ea(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[ik]=i,kc=t.then(function(){})instanceof i,!kc)return!0}return!e&&(Jb==="BROWSER"||Jb==="DENO")&&!eg});tg.exports={CONSTRUCTOR:rk,REJECTION_EVENT:eg,SUBCLASSING:kc}});var zr=g((E0,rg)=>{"use strict";var ig=oi(),sk=TypeError,ak=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new sk("Bad Promise constructor");e=i,t=r}),this.resolve=ig(e),this.reject=ig(t)};rg.exports.f=function(s){return new ak(s)}});var Ig=g(()=>{"use strict";var nk=je(),ok=Zt(),_o=Lo(),Wi=_e(),Yr=Bt(),sg=Ur(),ag=Zl(),uk=ma(),lk=ab(),ck=oi(),Oo=Ve(),dk=$t(),pk=ob(),hk=cc(),cg=yc().set,$c=Gb(),fk=Yb(),mk=Do(),bk=Tc(),dg=Nl(),Fo=vr(),Dc=Hr(),pg=zr(),No="Promise",hg=Dc.CONSTRUCTOR,gk=Dc.REJECTION_EVENT,Sk=Dc.SUBCLASSING,Rc=dg.getterFor(No),vk=dg.set,Qr=Fo&&Fo.prototype,yr=Fo,Co=Qr,fg=Wi.TypeError,Mc=Wi.document,Cc=Wi.process,Lc=pg.f,yk=Lc,Tk=!!(Mc&&Mc.createEvent&&Wi.dispatchEvent),mg="unhandledrejection",Ik="rejectionhandled",ng=0,bg=1,xk=2,Vc=1,gg=2,Vo,og,Ek,ug,Sg=function(s){var e;return dk(s)&&Oo(e=s.then)?e:!1},vg=function(s,e){var t=e.value,i=e.state===bg,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===gg&&Ak(e),e.rejection=Vc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new fg("Promise-chain cycle")):(l=Sg(u))?Yr(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},yg=function(s,e){s.notified||(s.notified=!0,$c(function(){for(var t=s.reactions,i;i=t.get();)vg(i,s);s.notified=!1,e&&!s.rejection&&wk(s)}))},Tg=function(s,e,t){var i,r;Tk?(i=Mc.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Wi.dispatchEvent(i)):i={promise:e,reason:t},!gk&&(r=Wi["on"+s])?r(i):s===mg&&fk("Unhandled promise rejection",t)},wk=function(s){Yr(cg,Wi,function(){var e=s.facade,t=s.value,i=lg(s),r;if(i&&(r=mk(function(){_o?Cc.emit("unhandledRejection",t,e):Tg(mg,e,t)}),s.rejection=_o||lg(s)?gg:Vc,r.error))throw r.value})},lg=function(s){return s.rejection!==Vc&&!s.parent},Ak=function(s){Yr(cg,Wi,function(){var e=s.facade;_o?Cc.emit("rejectionHandled",e):Tg(Ik,e,s.value)})},Gr=function(s,e,t){return function(i){s(e,i,t)}},Wr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=xk,yg(s,!0))},Bc=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new fg("Promise can't be resolved itself");var i=Sg(e);i?$c(function(){var r={done:!1};try{Yr(i,e,Gr(Bc,r,s),Gr(Wr,r,s))}catch(a){Wr(r,a,s)}}):(s.value=e,s.state=bg,yg(s,!1))}catch(r){Wr({done:!1},r,s)}}};if(hg&&(yr=function(e){pk(this,Co),ck(e),Yr(Vo,this);var t=Rc(this);try{e(Gr(Bc,t),Gr(Wr,t))}catch(i){Wr(t,i)}},Co=yr.prototype,Vo=function(e){vk(this,{type:No,done:!1,notified:!1,parent:!1,reactions:new bk,rejection:!1,state:ng,value:void 0})},Vo.prototype=sg(Co,"then",function(e,t){var i=Rc(this),r=Lc(hk(this,yr));return i.parent=!0,r.ok=Oo(e)?e:!0,r.fail=Oo(t)&&t,r.domain=_o?Cc.domain:void 0,i.state===ng?i.reactions.add(r):$c(function(){vg(r,i)}),r.promise}),og=function(){var s=new Vo,e=Rc(s);this.promise=s,this.resolve=Gr(Bc,e),this.reject=Gr(Wr,e)},pg.f=Lc=function(s){return s===yr||s===Ek?new og(s):yk(s)},!ok&&Oo(Fo)&&Qr!==Object.prototype)){ug=Qr.then,Sk||sg(Qr,"then",function(e,t){var i=this;return new yr(function(r,a){Yr(ug,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Qr.constructor}catch(s){}ag&&ag(Qr,Co)}nk({global:!0,constructor:!0,wrap:!0,forced:hg},{Promise:yr});uk(yr,No,!1,!0);lk(No)});var Pg=g((P0,Ag)=>{"use strict";var Pk=rt(),Eg=Pk("iterator"),wg=!1;try{xg=0,Oc={next:function(){return{done:!!xg++}},return:function(){wg=!0}},Oc[Eg]=function(){return this},Array.from(Oc,function(){throw 2})}catch(s){}var xg,Oc;Ag.exports=function(s,e){try{if(!e&&!wg)return!1}catch(r){return!1}var t=!1;try{var i={};i[Eg]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var _c=g((k0,kg)=>{"use strict";var kk=vr(),Rk=Pg(),Mk=Hr().CONSTRUCTOR;kg.exports=Mk||!Rk(function(s){kk.all(s).then(void 0,function(){})})});var Rg=g(()=>{"use strict";var Lk=je(),Bk=Bt(),$k=oi(),Dk=zr(),Ck=Do(),Vk=ko(),Ok=_c();Lk({target:"Promise",stat:!0,forced:Ok},{all:function(e){var t=this,i=Dk.f(t),r=i.resolve,a=i.reject,n=Ck(function(){var o=$k(t.resolve),u=[],l=0,d=1;Vk(e,function(c){var f=l++,p=!1;d++,Bk(o,t,c).then(function(h){p||(p=!0,u[f]=h,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),i.promise}})});var Lg=g(()=>{"use strict";var _k=je(),Fk=Zt(),Nk=Hr().CONSTRUCTOR,Nc=vr(),Uk=Ri(),qk=Ve(),jk=Ur(),Mg=Nc&&Nc.prototype;_k({target:"Promise",proto:!0,forced:Nk,real:!0},{catch:function(s){return this.then(void 0,s)}});!Fk&&qk(Nc)&&(Fc=Uk("Promise").prototype.catch,Mg.catch!==Fc&&jk(Mg,"catch",Fc,{unsafe:!0}));var Fc});var Bg=g(()=>{"use strict";var Hk=je(),zk=Bt(),Qk=oi(),Gk=zr(),Wk=Do(),Yk=ko(),Kk=_c();Hk({target:"Promise",stat:!0,forced:Kk},{race:function(e){var t=this,i=Gk.f(t),r=i.reject,a=Wk(function(){var n=Qk(t.resolve);Yk(e,function(o){zk(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var $g=g(()=>{"use strict";var Xk=je(),Jk=zr(),Zk=Hr().CONSTRUCTOR;Xk({target:"Promise",stat:!0,forced:Zk},{reject:function(e){var t=Jk.f(this),i=t.reject;return i(e),t.promise}})});var Uc=g((O0,Dg)=>{"use strict";var eR=ui(),tR=$t(),iR=zr();Dg.exports=function(s,e){if(eR(s),tR(e)&&e.constructor===s)return e;var t=iR.f(s),i=t.resolve;return i(e),t.promise}});var Og=g(()=>{"use strict";var rR=je(),sR=Ri(),Cg=Zt(),aR=vr(),Vg=Hr().CONSTRUCTOR,nR=Uc(),oR=sR("Promise"),uR=Cg&&!Vg;rR({target:"Promise",stat:!0,forced:Cg||Vg},{resolve:function(e){return nR(uR&&this===oR?aR:this,e)}})});var _g=g(()=>{"use strict";Ig();Rg();Lg();Bg();$g();Og()});var qg=g(()=>{"use strict";var lR=je(),cR=Zt(),Uo=vr(),dR=it(),Ng=Ri(),Ug=Ve(),pR=cc(),Fg=Uc(),hR=Ur(),jc=Uo&&Uo.prototype,fR=!!Uo&&dR(function(){jc.finally.call({then:function(){}},function(){})});lR({target:"Promise",proto:!0,real:!0,forced:fR},{finally:function(s){var e=pR(this,Ng("Promise")),t=Ug(s);return this.then(t?function(i){return Fg(e,s()).then(function(){return i})}:s,t?function(i){return Fg(e,s()).then(function(){throw i})}:s)}});!cR&&Ug(Uo)&&(qc=Ng("Promise").prototype.finally,jc.finally!==qc&&hR(jc,"finally",qc,{unsafe:!0}));var qc});var Hg=g((H0,jg)=>{"use strict";Jm();_g();qg();var mR=Gi();jg.exports=mR("Promise","finally")});var Qg=g((z0,zg)=>{"use strict";var bR=Hg();zg.exports=bR});var qo=g((Q0,Gg)=>{"use strict";var gR=Qg();Gg.exports=gR});var eS=g(()=>{"use strict";var IR=je(),xR=Vl().values;IR({target:"Object",stat:!0},{values:function(e){return xR(e)}})});var iS=g((xC,tS)=>{"use strict";eS();var ER=$r();tS.exports=ER.Object.values});var sS=g((EC,rS)=>{"use strict";var wR=iS();rS.exports=wR});var Tr=g((wC,aS)=>{"use strict";var AR=sS();aS.exports=AR});var bS=g(()=>{"use strict";var VR=je(),OR=Dr(),_R=Nr(),FR=da(),NR=pa();VR({target:"Array",proto:!0},{at:function(e){var t=OR(this),i=_R(t),r=FR(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});NR("at")});var SS=g((BV,gS)=>{"use strict";bS();var UR=Gi();gS.exports=UR("Array","at")});var yS=g(($V,vS)=>{"use strict";var qR=SS();vS.exports=qR});var ii=g((DV,TS)=>{"use strict";var jR=yS();TS.exports=jR});var ud=g((p_,jS)=>{"use strict";var eM=dr();jS.exports=Array.isArray||function(e){return eM(e)==="Array"}});var zS=g((h_,HS)=>{"use strict";var tM=TypeError,iM=9007199254740991;HS.exports=function(s){if(s>iM)throw tM("Maximum allowed index exceeded");return s}});var WS=g((f_,GS)=>{"use strict";var rM=ud(),sM=Nr(),aM=zS(),nM=Vr(),QS=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?nM(n,o):!1,c,f;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&rM(c)?(f=sM(c),u=QS(s,e,c,f,u,a-1)-1):(aM(u+1),s[u]=c),u++),l++;return u};GS.exports=QS});var JS=g((m_,XS)=>{"use strict";var YS=ud(),oM=lc(),uM=$t(),lM=rt(),cM=lM("species"),KS=Array;XS.exports=function(s){var e;return YS(s)&&(e=s.constructor,oM(e)&&(e===KS||YS(e.prototype))?e=void 0:uM(e)&&(e=e[cM],e===null&&(e=void 0))),e===void 0?KS:e}});var ev=g((b_,ZS)=>{"use strict";var dM=JS();ZS.exports=function(s,e){return new(dM(s))(e===0?0:e)}});var tv=g(()=>{"use strict";var pM=je(),hM=WS(),fM=oi(),mM=Dr(),bM=Nr(),gM=ev();pM({target:"Array",proto:!0},{flatMap:function(e){var t=mM(this),i=bM(t),r;return fM(e),r=gM(t,0),r.length=hM(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var iv=g(()=>{"use strict";var SM=pa();SM("flatMap")});var sv=g((T_,rv)=>{"use strict";tv();iv();var vM=Gi();rv.exports=vM("Array","flatMap")});var nv=g((I_,av)=>{"use strict";var yM=sv();av.exports=yM});var Oa=g((x_,ov)=>{"use strict";var TM=nv();ov.exports=TM});var _a=g((E_,uv)=>{"use strict";var IM=fa(),xM=String;uv.exports=function(s){if(IM(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return xM(s)}});var ld=g((w_,lv)=>{"use strict";lv.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 pv=g((A_,dv)=>{"use strict";var EM=Xe(),wM=Qi(),AM=_a(),dd=ld(),cv=EM("".replace),PM=RegExp("^["+dd+"]+"),kM=RegExp("(^|[^"+dd+"])["+dd+"]+$"),cd=function(s){return function(e){var t=AM(wM(e));return s&1&&(t=cv(t,PM,"")),s&2&&(t=cv(t,kM,"$1")),t}};dv.exports={start:cd(1),end:cd(2),trim:cd(3)}});var bv=g((P_,mv)=>{"use strict";var RM=jl().PROPER,MM=it(),hv=ld(),fv="\u200B\x85\u180E";mv.exports=function(s){return MM(function(){return!!hv[s]()||fv[s]()!==fv||RM&&hv[s].name!==s})}});var pd=g((k_,gv)=>{"use strict";var LM=pv().start,BM=bv();gv.exports=BM("trimStart")?function(){return LM(this)}:"".trimStart});var vv=g(()=>{"use strict";var $M=je(),Sv=pd();$M({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Sv},{trimLeft:Sv})});var Tv=g(()=>{"use strict";vv();var DM=je(),yv=pd();DM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==yv},{trimStart:yv})});var xv=g(($_,Iv)=>{"use strict";Tv();var CM=Gi();Iv.exports=CM("String","trimLeft")});var wv=g((D_,Ev)=>{"use strict";var VM=xv();Ev.exports=VM});var Pv=g((C_,Av)=>{"use strict";var OM=wv();Av.exports=OM});var Nv=g(()=>{"use strict"});var Uv=g(()=>{"use strict"});var jv=g((fU,qv)=>{"use strict";var rL=$t(),sL=dr(),aL=rt(),nL=aL("match");qv.exports=function(s){var e;return rL(s)&&((e=s[nL])!==void 0?!!e:sL(s)==="RegExp")}});var zv=g((mU,Hv)=>{"use strict";var oL=ui();Hv.exports=function(){var s=oL(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 Wv=g((bU,Gv)=>{"use strict";var uL=Bt(),lL=ei(),cL=aa(),dL=zv(),Qv=RegExp.prototype;Gv.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in Qv)&&!lL(s,"flags")&&cL(Qv,s)?uL(dL,s):e}});var Kv=g((gU,Yv)=>{"use strict";var gd=Xe(),pL=Dr(),hL=Math.floor,md=gd("".charAt),fL=gd("".replace),bd=gd("".slice),mL=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,bL=/\$([$&'`]|\d{1,2})/g;Yv.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=bL;return r!==void 0&&(r=pL(r),u=mL),fL(a,u,function(l,d){var c;switch(md(d,0)){case"$":return"$";case"&":return s;case"`":return bd(e,0,t);case"'":return bd(e,n);case"<":c=r[bd(d,1,-1)];break;default:var f=+d;if(f===0)return l;if(f>o){var p=hL(f/10);return p===0?l:p<=o?i[p-1]===void 0?md(d,1):i[p-1]+md(d,1):l}c=i[f-1]}return c===void 0?"":c})}});var Zv=g(()=>{"use strict";var gL=je(),SL=Bt(),vd=Xe(),Xv=Qi(),vL=Ve(),yL=Br(),TL=jv(),os=_a(),IL=oa(),xL=Wv(),EL=Kv(),wL=rt(),AL=Zt(),PL=wL("replace"),kL=TypeError,Sd=vd("".indexOf),RL=vd("".replace),Jv=vd("".slice),ML=Math.max;gL({target:"String",proto:!0},{replaceAll:function(e,t){var i=Xv(this),r,a,n,o,u,l,d,c,f,p,h=0,b="";if(!yL(e)){if(r=TL(e),r&&(a=os(Xv(xL(e))),!~Sd(a,"g")))throw new kL("`.replaceAll` does not allow non-global regexes");if(n=IL(e,PL),n)return SL(n,e,i,t);if(AL&&r)return RL(os(i),e,t)}for(o=os(i),u=os(e),l=vL(t),l||(t=os(t)),d=u.length,c=ML(1,d),f=Sd(o,u);f!==-1;)p=l?os(t(u,f,o)):EL(u,o,f,[],void 0,t),b+=Jv(o,h,f)+p,h=f+d,f=f+c>o.length?-1:Sd(o,u,f+c);return h<o.length&&(b+=Jv(o,h)),b}})});var ty=g((yU,ey)=>{"use strict";Nv();Uv();Zv();var LL=Gi();ey.exports=LL("String","replaceAll")});var ry=g((TU,iy)=>{"use strict";var BL=ty();iy.exports=BL});var yd=g((IU,sy)=>{"use strict";var $L=ry();sy.exports=$L});var ny=g((xU,ay)=>{"use strict";var DL=da(),CL=_a(),VL=Qi(),OL=RangeError;ay.exports=function(e){var t=CL(VL(this)),i="",r=DL(e);if(r<0||r===1/0)throw new OL("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var dy=g((EU,cy)=>{"use strict";var ly=Xe(),_L=Ml(),oy=_a(),FL=ny(),NL=Qi(),UL=ly(FL),qL=ly("".slice),jL=Math.ceil,uy=function(s){return function(e,t,i){var r=oy(NL(e)),a=_L(t),n=r.length,o=i===void 0?" ":oy(i),u,l;return a<=n||o===""?r:(u=a-n,l=UL(o,jL(u/o.length)),l.length>u&&(l=qL(l,0,u)),s?r+l:l+r)}};cy.exports={start:uy(!1),end:uy(!0)}});var hy=g((wU,py)=>{"use strict";var HL=hr();py.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(HL)});var fy=g(()=>{"use strict";var zL=je(),QL=dy().start,GL=hy();zL({target:"String",proto:!0,forced:GL},{padStart:function(e){return QL(this,e,arguments.length>1?arguments[1]:void 0)}})});var by=g((kU,my)=>{"use strict";fy();var WL=Gi();my.exports=WL("String","padStart")});var Sy=g((RU,gy)=>{"use strict";var YL=by();gy.exports=YL});var Td=g((MU,vy)=>{"use strict";var KL=Sy();vy.exports=KL});var FB={};UT(FB,{ChromecastState:()=>ea,HttpConnectionType:()=>oo,Observable:()=>fi.Observable,PlaybackState:()=>ht,Player:()=>ao,PredefinedQualityLimits:()=>ta,SDK_VERSION:()=>_B,Subject:()=>fi.Subject,Subscription:()=>fi.Subscription,Surface:()=>uo,VERSION:()=>el,ValueSubject:()=>fi.ValueSubject,VideoFormat:()=>ni,VideoQuality:()=>fi.VideoQuality,clientChecker:()=>te,isMobile:()=>Kr});module.exports=qT(FB);var el="2.0.135";var ht=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ht||{}),ni=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(ni||{});var ea=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(ea||{}),oo=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(oo||{});var uo=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(uo||{}),ta=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(ta||{});var $T=Z(Dt(),1);var le=require("@vkontakte/videoplayer-shared/es2015");var Zh=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 fo=class{constructor(e){this.connection$=new le.ValueSubject(void 0);this.castState$=new le.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new le.Subject;this.realCastState$=new le.ValueSubject("NOT_AVAILABLE");this.subscription=new le.Subscription;this.isDestroyed=!1;var a;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,le.isNonNullable)((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Zh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:le.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,le.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,le.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,le.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add((0,le.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,le.assertNever)(r.sessionState)}})).add((0,le.merge)((0,le.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,le.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,le.map)(r=>r.castState)),(0,le.observableFrom)([i.getCastState()])).pipe((0,le.filterChanged)(),(0,le.map)(cE),(0,le.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=(0,le.isNonNullable)(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();(0,le.assertNonNullable)(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,le.isNullable)(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,le.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:le.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},cE=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,le.assertNever)(s)}};var ep=Z(Dt(),1),yT=Z(mr(),1),TT=Z(sc(),1);var Xg=Z(qo(),1);var Hc=require("@vkontakte/videoplayer-shared/es2015");var Oe=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Hc.assertNever)(t)}return s},Yi=(s,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Hc.assertNever)(e)}};var q=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var li=require("@vkontakte/videoplayer-shared/es2015"),ce=class{constructor(e){this.transitionStarted$=new li.Subject;this.transitionEnded$=new li.Subject;this.transitionUpdated$=new li.Subject;this.forceChanged$=new li.Subject;this.stateChangeStarted$=(0,li.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,li.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,li.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Wg=require("@vkontakte/videoplayer-shared/es2015"),Yg=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Wg.assertNever)(s)}};var K=require("@vkontakte/videoplayer-shared/es2015");var SR=5,vR=5,yR=500,Kg=7e3,wa=class{constructor(e){this.subscription=new K.Subscription;this.loadMediaTimeoutSubscription=new K.Subscription;this.videoState=new ce("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,K.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,K.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,K.assertNever)(e)}break}default:(0,K.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Yg(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 K.Subscription;this.subscription.add(e),this.subscription.add((0,K.merge)(this.videoState.stateChangeStarted$.pipe((0,K.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,K.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new K.Subject;e.add(r.pipe((0,K.debounce)(yR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,K.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>SR)&&r.next(o),a=o})),e.add((0,K.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,K.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,K.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,K.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<vR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),q(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,K.assertNever)(n)}}),t((0,K.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,K.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,K.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,K.observableFrom)(["init"])).pipe((0,K.debounce)(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),q(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),q(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),q(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),q(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&q(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let d=t[e];(0,K.assertNonNullable)(d);let c=(0,K.getHighestQuality)(Object.keys(d));(0,K.assertNonNullable)(c);let f=d[c];(0,K.assertNonNullable)(f),i=f,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];(0,K.assertNonNullable)(d),i=d.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];(0,K.assertNonNullable)(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];(0,K.assertNonNullable)(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];(0,K.assertNonNullable)(d),i=Oe(d.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:K.ErrorCategory.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,K.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,K.isNonNullable)(o)&&(n.metadata.title=o),(0,K.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add((0,K.timeout)(Kg).subscribe(()=>a(`timeout(${Kg})`)))});(0,Xg.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:K.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var nd=Z(Dt(),1);var Wc=require("@vkontakte/videoplayer-shared/es2015");var Jg=require("@vkontakte/videoplayer-shared/es2015"),Zg=s=>{try{s.pause(),s.playbackRate=0,(0,Jg.clearVideoElement)(s),s.remove()}catch(e){console.error(e)}};var jo=require("@vkontakte/videoplayer-shared/es2015"),zc=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Qc=window.WeakMap?new WeakMap:new zc,Gc=window.WeakMap?new WeakMap:new Map,TR=(s,e=20)=>{let t=0;return(0,jo.fromEvent)(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},St=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?(0,Wc.clearVideoElement)(i):(i=document.createElement("video"),s.appendChild(i)),Qc.set(i,r);let a=new jo.Subscription;return a.add(TR(i,e)),Gc.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},vt=s=>{let e=Gc.get(s);e==null||e.unsubscribe(),Gc.delete(s);let t=Qc.get(s);Qc.delete(s),t?(0,Wc.clearVideoElement)(s):Zg(s)};var Yc=Z(Tr(),1),X=require("@vkontakte/videoplayer-shared/es2015");var Ki=require("@vkontakte/videoplayer-shared/es2015"),Ho=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=(0,Ki.isNullable)(r),l=new Ki.Subscription;return r&&l.add(r.subscribe(d=>{let c=s.getState();i(d,c)&&s.setState(d)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(d=>{t(d.to),u&&s.setState(d.to)},a)),l},ci=(s,e,t)=>Ho(e,()=>s.loop,i=>{(0,Ki.isNonNullable)(i)&&(s.loop=i)},{onError:t}),yt=(s,e,t,i)=>Ho(e,()=>({muted:s.muted,volume:s.volume}),r=>{(0,Ki.isNonNullable)(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),Nt=(s,e,t,i)=>Ho(e,()=>s.playbackRate,r=>{(0,Ki.isNonNullable)(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Aa=Ho;var PR=s=>["__",s.language,s.label].join("|"),kR=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Kc=class s{constructor(e){this.available$=new X.Subject;this.current$=new X.ValueSubject(void 0);this.error$=new X.Subject;this.subscription=new X.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:X.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Aa(t.internalTextTracks,()=>(0,Yc.default)(this.internalTracks),a=>{(0,X.isNonNullable)(a)&&this.setInternal(a)},{equal:(a,n)=>(0,X.isNonNullable)(a)&&(0,X.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,X.map)(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Aa(t.externalTextTracks,()=>(0,Yc.default)(this.externalTracks),a=>{(0,X.isNonNullable)(a)&&this.setExternal(a)},{equal:(a,n)=>(0,X.isNonNullable)(a)&&(0,X.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,X.map)(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Aa(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(Aa(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){(0,X.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,X.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,X.merge)((0,X.fromEvent)(e,"addtrack"),(0,X.fromEvent)(e,"removetrack"),(0,X.observableFrom)(["init"])).pipe((0,X.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,X.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add((0,X.merge)((0,X.fromEvent)(e,"change"),(0,X.observableFrom)(["init"])).pipe((0,X.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,X.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,X.filterChanged)()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add((0,X.fromEvent)(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,d,c,f,p;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((f=(c=o.target)==null?void 0:c.cues)!=null?f:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,X.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,X.isNonNullable)(t.align)&&(r.align=t.align),(0,X.isNonNullable)(t.position)&&(r.position=t.position),(0,X.isNonNullable)(t.size)&&(r.size=t.size),(0,X.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,X.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:PR(e),a=this.externalTracks.has(r),n=(l=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,X.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,X.isNullable)(e)||!kR(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,X.assertNonNullable)(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,X.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ut=Kc;var Ir=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 nS=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Xc=s=>{let e=nS(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},oS=s=>{let e=nS(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};var U=require("@vkontakte/videoplayer-shared/es2015");var RR=3,uS=(s,e,t=RR)=>{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 zo=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 lS=Z(Dt(),1);var Kr=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Qo=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,lS.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=Kr()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return k(this,null,function*(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Go=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var Vt=()=>window.ManagedMediaSource||window.MediaSource,Xr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},cS=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},Wo=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var MR=document.createElement("video"),LR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',BR='video/mp4; codecs="hev1.1.6.L93.B0"',dS='video/webm; codecs="vp09.00.10.08"',pS='video/webm; codecs="av01.0.00M.08"',$R='audio/mp4; codecs="mp4a.40.2"',DR='audio/webm; codecs="opus"',hS,CR=()=>k(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(F(P({},s),{video:F(P({},s.video),{contentType:pS})})),window.navigator.mediaCapabilities.decodingInfo(F(P({},s),{video:F(P({},s.video),{contentType:dS})}))]);hS={DASH_WEBM_AV1:e,DASH_WEBM:t}});CR().catch(s=>{console.log(MR),console.error(s)});var Yo=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 hS}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,a,n,o,u,l,d,c,f,p,h,b,S,v,y,x,E;this._video=document.createElement("video");try{this._protocols={mms:Xr(),mse:cS(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(a=this._video).canPlayType)!=null&&n.call(a,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let A=!!((d=(l=Vt())==null?void 0:l.isTypeSupported)!=null&&d.call(l,LR)),D=!!((f=(c=Vt())==null?void 0:c.isTypeSupported)!=null&&f.call(c,BR)),j=!!((h=(p=Vt())==null?void 0:p.isTypeSupported)!=null&&h.call(p,$R));this._codecs={h264:A,h265:D,vp9:!!((S=(b=Vt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,dS)),av1:!!((y=(v=Vt())==null?void 0:v.isTypeSupported)!=null&&y.call(v,pS)),aac:j,opus:!!((E=(x=Vt())==null?void 0:x.isTypeSupported)!=null&&E.call(x,DR)),mpeg:(A||D)&&j},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(A){console.error(A)}try{this.destroyVideoElement()}catch(A){console.error("Error destroying video element:",A)}}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var fS="audio/mpeg",Ko=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,fS))},this._codecs={mp3:!!((r=(i=Vt())==null?void 0:i.isTypeSupported)!=null&&r.call(i,fS))}}catch(a){console.error(a)}try{this.destroyAudioElement()}catch(a){console.error("Error destroying audio element:",a)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};var mS=require("@vkontakte/videoplayer-shared/es2015");var Jc=class{constructor(){this.isInited$=new mS.ValueSubject(!1);this._displayChecker=new Go,this._deviceChecker=new Qo(this._displayChecker),this._browserChecker=new zo,this._videoChecker=new Yo(this._deviceChecker,this._browserChecker),this._audioChecker=new Ko,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}detect(){return k(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},te=new Jc;var Tt=s=>{let e=L=>(0,U.fromEvent)(s,L).pipe((0,U.mapTo)(void 0)),t=new U.Subscription,i=()=>t.unsubscribe(),r=(0,U.merge)((0,U.fromEvent)(s,"progress"),(0,U.fromEvent)(s,"timeupdate")).pipe((0,U.map)(()=>uS(s.buffered,s.currentTime))),a=te.browser.isSafari?(0,U.combine)({play:e("play").pipe((0,U.once)()),playing:e("playing")}).pipe((0,U.mapTo)(void 0)):e("playing"),n=(0,U.fromEvent)(s,"volumechange").pipe((0,U.map)(()=>({muted:s.muted,volume:s.volume}))),o=(0,U.fromEvent)(s,"ratechange").pipe((0,U.map)(()=>s.playbackRate)),u=(0,U.fromEvent)(s,"error").pipe((0,U.filter)(()=>!!(s.error||s.played.length)),(0,U.map)(()=>{var Q;let L=s.error;return{id:L?`MediaError#${L.code}`:"HtmlVideoError",category:U.ErrorCategory.VIDEO_PIPELINE,message:L?L.message:"Error event from HTML video element",thrown:(Q=s.error)!=null?Q:void 0}})),l=(0,U.fromEvent)(s,"timeupdate").pipe((0,U.map)(()=>s.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new U.Subject,f=.3,p;t.add((0,U.merge)(...d.map(L=>(0,U.fromEvent)(s,L))).subscribe(L=>{let Q=s.currentTime;s.loop&&(0,U.isNonNullable)(p)&&(0,U.isNonNullable)(Q)&&p>=s.duration-f&&Q<=f&&c.next(p),p=Q}));let h=e("pause").pipe((0,U.filter)(()=>!s.error&&p!==s.duration)),b=(0,U.fromEvent)(s,"enterpictureinpicture"),S=(0,U.fromEvent)(s,"leavepictureinpicture"),v=new U.ValueSubject(oS(s));t.add(b.subscribe(()=>v.next(!0))),t.add(S.subscribe(()=>v.next(!1)));let y=new U.ValueSubject(Xc(s)),x=(0,U.fromEvent)(s,"fullscreenchange");t.add(x.pipe((0,U.map)(()=>Xc(s))).subscribe(y));let E=.1,A=1e3,D=(0,U.fromEvent)(s,"timeupdate").pipe((0,U.map)(L=>s.duration-s.currentTime<E),(0,U.filterChanged)()),j=(0,U.merge)(D.pipe((0,U.filter)(L=>!s.loop&&L)),(0,U.fromEvent)(s,"ended")).pipe((0,U.throttle)(A),(0,U.mapTo)(void 0)),N=(0,U.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(L=>(0,U.fromEvent)(s,L)),D.pipe((0,U.map)(L=>({type:L?"ended":"unknown"})))).pipe((0,U.map)(L=>te.browser.isFirefox&&L.type==="ended"?s.readyState<2:s.readyState<3),(0,U.filterChanged)());return{playing$:a,pause$:h,canplay$:e("canplay"),ended$:j,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$:(0,U.fromEvent)(s,"durationchange").pipe((0,U.map)(()=>s.duration)),isBuffering$:N,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:y,enterPip$:b,leavePip$:S,destroy:i}};var Bi=require("@vkontakte/videoplayer-shared/es2015"),Xi=s=>{switch(s){case"mobile":return Bi.VideoQuality.Q_144P;case"lowest":return Bi.VideoQuality.Q_240P;case"low":return Bi.VideoQuality.Q_360P;case"sd":case"medium":return Bi.VideoQuality.Q_480P;case"hd":case"high":return Bi.VideoQuality.Q_720P;case"fullhd":case"full":return Bi.VideoQuality.Q_1080P;case"quadhd":case"quad":return Bi.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Bi.VideoQuality.Q_2160P}};var mt=Z(ii(),1),td=Z(Dt(),1),xr=Z(mr(),1),C=require("@vkontakte/videoplayer-shared/es2015");var Zc=!1,$i={},IS=s=>{Zc=s},xS=()=>{$i={}},ES=s=>{s($i)},Pa=(s,e)=>{var t;Zc&&($i.meta=(t=$i.meta)!=null?t:{},$i.meta[s]=e)},ft=class{constructor(e){this.name=e}next(e){var i,r;if(!Zc)return;$i.series=(i=$i.series)!=null?i:{};let t=(r=$i.series[this.name])!=null?r:[];t.push([Date.now(),e]),$i.series[this.name]=t}};var He=require("@vkontakte/videoplayer-shared/es2015");function ed(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Xo(s,e,t){return!!s&&ed(s,e,t)==="high_quality"}function Jr(s,e,t){return(0,He.isNullable)(s)||(0,He.isNonNullable)(s.min)&&(0,He.isNonNullable)(s.max)&&(0,He.isLower)(s.max,s.min)||(0,He.isNonNullable)(s.min)&&e&&(0,He.isHigher)(s.min,e)||(0,He.isNonNullable)(s.max)&&t&&(0,He.isLower)(s.max,t)}function wS({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Jr({max:s!=null&&s.max?(0,He.videoHeightToQuality)(s.max):void 0,min:s!=null&&s.min?(0,He.videoHeightToQuality)(s.min):void 0},e?(0,He.videoHeightToQuality)(e):void 0,t?(0,He.videoHeightToQuality)(t):void 0)}var MS=new ft("best_bitrate"),Zo=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Zr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),Ji=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,C.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},eu='Assertion "ABR Tracks is empty array" failed',Jo=new WeakMap,AS=new WeakMap,PS=new WeakMap,ka=(s,e,t,i)=>{var u;let r=[...e].sort(Zr(1)),a=[...t].sort(Zr(1)),n=a.filter(l=>(0,C.isNonNullable)(l.bitrate)&&(0,C.isNonNullable)(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,mt.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,mt.default)(a,-1);return o&&(0,td.default)(n,o)?o:n.length?(0,mt.default)(n,-1):(0,mt.default)(a,0)},Ra=(s,e,t,i)=>{var u;let r=Jo.get(e);r||(r=[...e].sort(Zr(1)),Jo.set(e,r));let a=Jo.get(t);a||(a=[...t].sort(Zr(1)),Jo.set(t,a));let n=PS.get(s);n||(n=a.filter(l=>(0,C.isNonNullable)(l.bitrate)&&(0,C.isNonNullable)(s.bitrate)?s.bitrate/l.bitrate>i:!0),PS.set(s,n));let o=(u=(0,mt.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,mt.default)(a,-1);return o&&(0,td.default)(n,o)?o:n.length?(0,mt.default)(n,-1):(0,mt.default)(a,0)},kS=s=>"quality"in s,tu=(s,e,t,i)=>{var n;let r=(0,C.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,C.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&(0,C.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!a&&i.recordSelection(t),a&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=kS(o)?"video":"audio",l=kS(o)?o.quality:o.bitrate;return e({message:`
8
- [last ${u} selected] ${l}
9
- `}),o}return i==null||i.recordSwitch(t),t},HR=(s,e)=>Math.log(e)/Math.log(s),LS=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&te.display.pixelRatio){let a=te.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=HR(n,o*a+u)+l;Number.isFinite(d)&&(r*=d)}}return Xo(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}},RS=new WeakMap,di=(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:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:b})=>{var J,G,de,$,_;(0,C.assertNotEmptyArray)(s,eu);let{containerSizeFactor:S,containerSizeLimit:v}=LS({container:e,tuning:i,limits:r,panelSize:b}),y=i.considerPlaybackRate&&(0,C.isNonNullable)(o)?o:1,x=RS.get(s);x||(x=s.filter(V=>!(0,C.isInvariantQuality)(V.quality)).sort((V,B)=>(0,C.isHigher)(V.quality,B.quality)?-1:1),RS.set(s,x));let E=(J=(0,mt.default)(x,-1))==null?void 0:J.quality,A=(G=(0,mt.default)(x,0))==null?void 0:G.quality,D=Jr(r,A,E),j=y*Zo(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),H={},N=null;for(let V of x){let B=!0;if(v)if(V.size)B=V.size.width<=v.width&&V.size.height<=v.height;else{let tt=v&&(0,C.videoSizeToQuality)(v);B=tt?(0,C.isLowerOrEqual)(V.quality,tt):!0}if(!B){H[V.quality]="FitsContainer";continue}let z=p||t,Ee=(0,C.isNonNullable)(z)&&isFinite(z)&&(0,C.isNonNullable)(V.bitrate)?z-a>=V.bitrate*j:!0,et=Xo(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===V.quality;if(!Ee&&!et){H[V.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&(0,C.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,C.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,C.isHigher)(V.quality,u.quality)){H[V.quality]="Buffer";continue}if(!!c&&(0,C.isHigherOrEqual)(V.quality,c)&&!et){H[V.quality]="DroppedFramesLimit";continue}if(!!f&&(0,C.isHigherOrEqual)(V.quality,f)&&!et){H[V.quality]="StallsLimit";continue}let Ne=D||((0,C.isNullable)(r==null?void 0:r.max)||(0,C.isLowerOrEqual)(V.quality,r.max))&&((0,C.isNullable)(r==null?void 0:r.min)||(0,C.isHigherOrEqual)(V.quality,r.min)),Ue=(0,C.isNonNullable)(d)&&!d?(0,C.isLowerOrEqual)(V.quality,i.backgroundVideoQualityLimit):!0;if(!Ne||!Ue){H[V.quality]="FitsQualityLimits";continue}N||(N=V)}N&&N.bitrate&&MS.next(N.bitrate);let L=(de=N!=null?N:(0,mt.default)(x,-1))!=null?de:s[0],Q=l==null?void 0:l.last,O=tu(i,h,L,l);return(0,C.isNonNullable)(l)&&O.quality!==(Q==null?void 0:Q.quality)&&h({message:`
6
+ "use strict";var qy=Object.create;var Hr=Object.defineProperty,jy=Object.defineProperties,Hy=Object.getOwnPropertyDescriptor,Qy=Object.getOwnPropertyDescriptors,Gy=Object.getOwnPropertyNames,Ds=Object.getOwnPropertySymbols,Wy=Object.getPrototypeOf,Po=Object.prototype.hasOwnProperty,cd=Object.prototype.propertyIsEnumerable;var zy=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var kt=Math.pow,ld=(a,e,t)=>e in a?Hr(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,C=(a,e)=>{for(var t in e||(e={}))Po.call(e,t)&&ld(a,t,e[t]);if(Ds)for(var t of Ds(e))cd.call(e,t)&&ld(a,t,e[t]);return a},Q=(a,e)=>jy(a,Qy(e));var dd=(a,e)=>{var t={};for(var i in a)Po.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&Ds)for(var i of Ds(a))e.indexOf(i)<0&&cd.call(a,i)&&(t[i]=a[i]);return t};var g=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Yy=(a,e)=>{for(var t in e)Hr(a,t,{get:e[t],enumerable:!0})},pd=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Gy(e))!Po.call(a,r)&&r!==t&&Hr(a,r,{get:()=>e[r],enumerable:!(i=Hy(e,r))||i.enumerable});return a};var J=(a,e,t)=>(t=a!=null?qy(Wy(a)):{},pd(e||!a||!a.__esModule?Hr(t,"default",{value:a,enumerable:!0}):t,a)),Ky=a=>pd(Hr({},"__esModule",{value:!0}),a);var R=(a,e,t)=>new Promise((i,r)=>{var s=o=>{try{u(t.next(o))}catch(l){r(l)}},n=o=>{try{u(t.throw(o))}catch(l){r(l)}},u=o=>o.done?i(o.value):Promise.resolve(o.value).then(s,n);u((t=t.apply(a,e)).next())}),Pi=function(a,e){this[0]=a,this[1]=e},oe=(a,e,t)=>{var i=(n,u,o,l)=>{try{var d=t[n](u),c=(u=d.value)instanceof Pi,f=d.done;Promise.resolve(c?u[0]:u).then(p=>c?i(n==="return"?n:"next",u[1]?{done:p.done,value:p.value}:p,o,l):o({value:p,done:f})).catch(p=>i("throw",p,o,l))}catch(p){l(p)}},r=n=>s[n]=u=>new Promise((o,l)=>i(n,u,o,l)),s={};return t=t.apply(a,e),s[zy("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var Ae=g((ko,hd)=>{"use strict";var Wr=function(a){return a&&a.Math===Math&&a};hd.exports=Wr(typeof globalThis=="object"&&globalThis)||Wr(typeof window=="object"&&window)||Wr(typeof self=="object"&&self)||Wr(typeof global=="object"&&global)||Wr(typeof ko=="object"&&ko)||function(){return this}()||Function("return this")()});var Me=g((O$,fd)=>{"use strict";fd.exports=function(a){try{return!!a()}catch(e){return!0}}});var zr=g((F$,md)=>{"use strict";var Xy=Me();md.exports=!Xy(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Lo=g((N$,vd)=>{"use strict";var Jy=zr(),Sd=Function.prototype,bd=Sd.apply,gd=Sd.call;vd.exports=typeof Reflect=="object"&&Reflect.apply||(Jy?gd.bind(bd):function(){return gd.apply(bd,arguments)})});var De=g((U$,Id)=>{"use strict";var yd=zr(),Td=Function.prototype,$o=Td.call,Zy=yd&&Td.bind.bind($o,$o);Id.exports=yd?Zy:function(a){return function(){return $o.apply(a,arguments)}}});var Ri=g((q$,xd)=>{"use strict";var Ed=De(),eT=Ed({}.toString),tT=Ed("".slice);xd.exports=function(a){return tT(eT(a),8,-1)}});var Mo=g((j$,wd)=>{"use strict";var iT=Ri(),rT=De();wd.exports=function(a){if(iT(a)==="Function")return rT(a)}});var Pe=g((H$,Ad)=>{"use strict";var Do=typeof document=="object"&&document.all;Ad.exports=typeof Do=="undefined"&&Do!==void 0?function(a){return typeof a=="function"||a===Do}:function(a){return typeof a=="function"}});var it=g((Q$,Pd)=>{"use strict";var aT=Me();Pd.exports=!aT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var rt=g((G$,Rd)=>{"use strict";var sT=zr(),Vs=Function.prototype.call;Rd.exports=sT?Vs.bind(Vs):function(){return Vs.apply(Vs,arguments)}});var Co=g($d=>{"use strict";var kd={}.propertyIsEnumerable,Ld=Object.getOwnPropertyDescriptor,nT=Ld&&!kd.call({1:2},1);$d.f=nT?function(e){var t=Ld(this,e);return!!t&&t.enumerable}:kd});var Yr=g((z$,Md)=>{"use strict";Md.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Cd=g((Y$,Dd)=>{"use strict";var oT=De(),uT=Me(),lT=Ri(),Bo=Object,cT=oT("".split);Dd.exports=uT(function(){return!Bo("z").propertyIsEnumerable(0)})?function(a){return lT(a)==="String"?cT(a,""):Bo(a)}:Bo});var Kr=g((K$,Bd)=>{"use strict";Bd.exports=function(a){return a==null}});var ui=g((X$,Vd)=>{"use strict";var dT=Kr(),pT=TypeError;Vd.exports=function(a){if(dT(a))throw new pT("Can't call method on "+a);return a}});var ki=g((J$,_d)=>{"use strict";var hT=Cd(),fT=ui();_d.exports=function(a){return hT(fT(a))}});var Ge=g((Z$,Od)=>{"use strict";var mT=Pe();Od.exports=function(a){return typeof a=="object"?a!==null:mT(a)}});var Li=g((eM,Fd)=>{"use strict";Fd.exports={}});var jt=g((tM,Ud)=>{"use strict";var Vo=Li(),_o=Ae(),bT=Pe(),Nd=function(a){return bT(a)?a:void 0};Ud.exports=function(a,e){return arguments.length<2?Nd(Vo[a])||Nd(_o[a]):Vo[a]&&Vo[a][e]||_o[a]&&_o[a][e]}});var Xr=g((iM,qd)=>{"use strict";var gT=De();qd.exports=gT({}.isPrototypeOf)});var $i=g((rM,Qd)=>{"use strict";var ST=Ae(),jd=ST.navigator,Hd=jd&&jd.userAgent;Qd.exports=Hd?String(Hd):""});var Fo=g((aM,Xd)=>{"use strict";var Kd=Ae(),Oo=$i(),Gd=Kd.process,Wd=Kd.Deno,zd=Gd&&Gd.versions||Wd&&Wd.version,Yd=zd&&zd.v8,yt,_s;Yd&&(yt=Yd.split("."),_s=yt[0]>0&&yt[0]<4?1:+(yt[0]+yt[1]));!_s&&Oo&&(yt=Oo.match(/Edge\/(\d+)/),(!yt||yt[1]>=74)&&(yt=Oo.match(/Chrome\/(\d+)/),yt&&(_s=+yt[1])));Xd.exports=_s});var No=g((sM,Zd)=>{"use strict";var Jd=Fo(),vT=Me(),yT=Ae(),TT=yT.String;Zd.exports=!!Object.getOwnPropertySymbols&&!vT(function(){var a=Symbol("symbol detection");return!TT(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Jd&&Jd<41})});var Uo=g((nM,ep)=>{"use strict";var IT=No();ep.exports=IT&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var qo=g((oM,tp)=>{"use strict";var ET=jt(),xT=Pe(),wT=Xr(),AT=Uo(),PT=Object;tp.exports=AT?function(a){return typeof a=="symbol"}:function(a){var e=ET("Symbol");return xT(e)&&wT(e.prototype,PT(a))}});var Jr=g((uM,ip)=>{"use strict";var RT=String;ip.exports=function(a){try{return RT(a)}catch(e){return"Object"}}});var $t=g((lM,rp)=>{"use strict";var kT=Pe(),LT=Jr(),$T=TypeError;rp.exports=function(a){if(kT(a))return a;throw new $T(LT(a)+" is not a function")}});var Zr=g((cM,ap)=>{"use strict";var MT=$t(),DT=Kr();ap.exports=function(a,e){var t=a[e];return DT(t)?void 0:MT(t)}});var np=g((dM,sp)=>{"use strict";var jo=rt(),Ho=Pe(),Qo=Ge(),CT=TypeError;sp.exports=function(a,e){var t,i;if(e==="string"&&Ho(t=a.toString)&&!Qo(i=jo(t,a))||Ho(t=a.valueOf)&&!Qo(i=jo(t,a))||e!=="string"&&Ho(t=a.toString)&&!Qo(i=jo(t,a)))return i;throw new CT("Can't convert object to primitive value")}});var Tt=g((pM,op)=>{"use strict";op.exports=!0});var cp=g((hM,lp)=>{"use strict";var up=Ae(),BT=Object.defineProperty;lp.exports=function(a,e){try{BT(up,a,{value:e,configurable:!0,writable:!0})}catch(t){up[a]=e}return e}});var ea=g((fM,hp)=>{"use strict";var VT=Tt(),_T=Ae(),OT=cp(),dp="__core-js_shared__",pp=hp.exports=_T[dp]||OT(dp,{});(pp.versions||(pp.versions=[])).push({version:"3.43.0",mode:VT?"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 Go=g((mM,mp)=>{"use strict";var fp=ea();mp.exports=function(a,e){return fp[a]||(fp[a]=e||{})}});var ir=g((bM,bp)=>{"use strict";var FT=ui(),NT=Object;bp.exports=function(a){return NT(FT(a))}});var It=g((gM,gp)=>{"use strict";var UT=De(),qT=ir(),jT=UT({}.hasOwnProperty);gp.exports=Object.hasOwn||function(e,t){return jT(qT(e),t)}});var Wo=g((SM,Sp)=>{"use strict";var HT=De(),QT=0,GT=Math.random(),WT=HT(1.1.toString);Sp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+WT(++QT+GT,36)}});var Fe=g((vM,yp)=>{"use strict";var zT=Ae(),YT=Go(),vp=It(),KT=Wo(),XT=No(),JT=Uo(),rr=zT.Symbol,zo=YT("wks"),ZT=JT?rr.for||rr:rr&&rr.withoutSetter||KT;yp.exports=function(a){return vp(zo,a)||(zo[a]=XT&&vp(rr,a)?rr[a]:ZT("Symbol."+a)),zo[a]}});var xp=g((yM,Ep)=>{"use strict";var eI=rt(),Tp=Ge(),Ip=qo(),tI=Zr(),iI=np(),rI=Fe(),aI=TypeError,sI=rI("toPrimitive");Ep.exports=function(a,e){if(!Tp(a)||Ip(a))return a;var t=tI(a,sI),i;if(t){if(e===void 0&&(e="default"),i=eI(t,a,e),!Tp(i)||Ip(i))return i;throw new aI("Can't convert object to primitive value")}return e===void 0&&(e="number"),iI(a,e)}});var Yo=g((TM,wp)=>{"use strict";var nI=xp(),oI=qo();wp.exports=function(a){var e=nI(a,"string");return oI(e)?e:e+""}});var Os=g((IM,Pp)=>{"use strict";var uI=Ae(),Ap=Ge(),Ko=uI.document,lI=Ap(Ko)&&Ap(Ko.createElement);Pp.exports=function(a){return lI?Ko.createElement(a):{}}});var Xo=g((EM,Rp)=>{"use strict";var cI=it(),dI=Me(),pI=Os();Rp.exports=!cI&&!dI(function(){return Object.defineProperty(pI("div"),"a",{get:function(){return 7}}).a!==7})});var $p=g(Lp=>{"use strict";var hI=it(),fI=rt(),mI=Co(),bI=Yr(),gI=ki(),SI=Yo(),vI=It(),yI=Xo(),kp=Object.getOwnPropertyDescriptor;Lp.f=hI?kp:function(e,t){if(e=gI(e),t=SI(t),yI)try{return kp(e,t)}catch(i){}if(vI(e,t))return bI(!fI(mI.f,e,t),e[t])}});var Jo=g((wM,Mp)=>{"use strict";var TI=Me(),II=Pe(),EI=/#|\.prototype\./,ta=function(a,e){var t=wI[xI(a)];return t===PI?!0:t===AI?!1:II(e)?TI(e):!!e},xI=ta.normalize=function(a){return String(a).replace(EI,".").toLowerCase()},wI=ta.data={},AI=ta.NATIVE="N",PI=ta.POLYFILL="P";Mp.exports=ta});var ar=g((AM,Cp)=>{"use strict";var Dp=Mo(),RI=$t(),kI=zr(),LI=Dp(Dp.bind);Cp.exports=function(a,e){return RI(a),e===void 0?a:kI?LI(a,e):function(){return a.apply(e,arguments)}}});var Zo=g((PM,Bp)=>{"use strict";var $I=it(),MI=Me();Bp.exports=$I&&MI(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Mt=g((RM,Vp)=>{"use strict";var DI=Ge(),CI=String,BI=TypeError;Vp.exports=function(a){if(DI(a))return a;throw new BI(CI(a)+" is not an object")}});var Mi=g(Op=>{"use strict";var VI=it(),_I=Xo(),OI=Zo(),Fs=Mt(),_p=Yo(),FI=TypeError,eu=Object.defineProperty,NI=Object.getOwnPropertyDescriptor,tu="enumerable",iu="configurable",ru="writable";Op.f=VI?OI?function(e,t,i){if(Fs(e),t=_p(t),Fs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&ru in i&&!i[ru]){var r=NI(e,t);r&&r[ru]&&(e[t]=i.value,i={configurable:iu in i?i[iu]:r[iu],enumerable:tu in i?i[tu]:r[tu],writable:!1})}return eu(e,t,i)}:eu:function(e,t,i){if(Fs(e),t=_p(t),Fs(i),_I)try{return eu(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new FI("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var sr=g((LM,Fp)=>{"use strict";var UI=it(),qI=Mi(),jI=Yr();Fp.exports=UI?function(a,e,t){return qI.f(a,e,jI(1,t))}:function(a,e,t){return a[e]=t,a}});var Le=g(($M,Up)=>{"use strict";var ia=Ae(),HI=Lo(),QI=Mo(),GI=Pe(),WI=$p().f,zI=Jo(),nr=Li(),YI=ar(),or=sr(),Np=It();ea();var KI=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 HI(a,this,arguments)};return e.prototype=a.prototype,e};Up.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?ia:r?ia[t]:ia[t]&&ia[t].prototype,u=i?nr:nr[t]||or(nr,t,{})[t],o=u.prototype,l,d,c,f,p,h,b,v,S;for(f in e)l=zI(i?f:t+(r?".":"#")+f,a.forced),d=!l&&n&&Np(n,f),h=u[f],d&&(a.dontCallGetSet?(S=WI(n,f),b=S&&S.value):b=n[f]),p=d&&b?b:e[f],!(!l&&!s&&typeof h==typeof p)&&(a.bind&&d?v=YI(p,ia):a.wrap&&d?v=KI(p):s&&GI(p)?v=QI(p):v=p,(a.sham||p&&p.sham||h&&h.sham)&&or(v,"sham",!0),or(u,f,v),s&&(c=t+"Prototype",Np(nr,c)||or(nr,c,{}),or(nr[c],f,p),a.real&&o&&(l||!o[f])&&or(o,f,p)))}});var jp=g((MM,qp)=>{"use strict";var XI=Math.ceil,JI=Math.floor;qp.exports=Math.trunc||function(e){var t=+e;return(t>0?JI:XI)(t)}});var ra=g((DM,Hp)=>{"use strict";var ZI=jp();Hp.exports=function(a){var e=+a;return e!==e||e===0?0:ZI(e)}});var Gp=g((CM,Qp)=>{"use strict";var eE=ra(),tE=Math.max,iE=Math.min;Qp.exports=function(a,e){var t=eE(a);return t<0?tE(t+e,0):iE(t,e)}});var au=g((BM,Wp)=>{"use strict";var rE=ra(),aE=Math.min;Wp.exports=function(a){var e=rE(a);return e>0?aE(e,9007199254740991):0}});var ur=g((VM,zp)=>{"use strict";var sE=au();zp.exports=function(a){return sE(a.length)}});var su=g((_M,Kp)=>{"use strict";var nE=ki(),oE=Gp(),uE=ur(),Yp=function(a){return function(e,t,i){var r=nE(e),s=uE(r);if(s===0)return!a&&-1;var n=oE(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}};Kp.exports={includes:Yp(!0),indexOf:Yp(!1)}});var aa=g((OM,Xp)=>{"use strict";Xp.exports=function(){}});var Jp=g(()=>{"use strict";var lE=Le(),cE=su().includes,dE=Me(),pE=aa(),hE=dE(function(){return!Array(1).includes()});lE({target:"Array",proto:!0,forced:hE},{includes:function(e){return cE(this,e,arguments.length>1?arguments[1]:void 0)}});pE("includes")});var li=g((UM,Zp)=>{"use strict";var fE=jt();Zp.exports=fE});var th=g((qM,eh)=>{"use strict";Jp();var mE=li();eh.exports=mE("Array","includes")});var rh=g((jM,ih)=>{"use strict";var bE=th();ih.exports=bE});var dt=g((HM,ah)=>{"use strict";var gE=rh();ah.exports=gE});var Us=g((tD,oh)=>{"use strict";var vE=Go(),yE=Wo(),nh=vE("keys");oh.exports=function(a){return nh[a]||(nh[a]=yE(a))}});var lh=g((iD,uh)=>{"use strict";var TE=Me();uh.exports=!TE(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var qs=g((rD,dh)=>{"use strict";var IE=It(),EE=Pe(),xE=ir(),wE=Us(),AE=lh(),ch=wE("IE_PROTO"),nu=Object,PE=nu.prototype;dh.exports=AE?nu.getPrototypeOf:function(a){var e=xE(a);if(IE(e,ch))return e[ch];var t=e.constructor;return EE(t)&&e instanceof t?t.prototype:e instanceof nu?PE:null}});var js=g((aD,ph)=>{"use strict";ph.exports={}});var mh=g((sD,fh)=>{"use strict";var RE=De(),ou=It(),kE=ki(),LE=su().indexOf,$E=js(),hh=RE([].push);fh.exports=function(a,e){var t=kE(a),i=0,r=[],s;for(s in t)!ou($E,s)&&ou(t,s)&&hh(r,s);for(;e.length>i;)ou(t,s=e[i++])&&(~LE(r,s)||hh(r,s));return r}});var uu=g((nD,bh)=>{"use strict";bh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var lu=g((oD,gh)=>{"use strict";var ME=mh(),DE=uu();gh.exports=Object.keys||function(e){return ME(e,DE)}});var cu=g((uD,Ih)=>{"use strict";var vh=it(),CE=Me(),yh=De(),BE=qs(),VE=lu(),_E=ki(),OE=Co().f,Th=yh(OE),FE=yh([].push),NE=vh&&CE(function(){var a=Object.create(null);return a[2]=2,!Th(a,2)}),Sh=function(a){return function(e){for(var t=_E(e),i=VE(t),r=NE&&BE(t)===null,s=i.length,n=0,u=[],o;s>n;)o=i[n++],(!vh||(r?o in t:Th(t,o)))&&FE(u,a?[o,t[o]]:t[o]);return u}};Ih.exports={entries:Sh(!0),values:Sh(!1)}});var Eh=g(()=>{"use strict";var UE=Le(),qE=cu().entries;UE({target:"Object",stat:!0},{entries:function(e){return qE(e)}})});var wh=g((dD,xh)=>{"use strict";Eh();var jE=Li();xh.exports=jE.Object.entries});var Ph=g((pD,Ah)=>{"use strict";var HE=wh();Ah.exports=HE});var lr=g((hD,Rh)=>{"use strict";var QE=Ph();Rh.exports=QE});var Di=g((fD,kh)=>{"use strict";kh.exports={}});var Mh=g((mD,$h)=>{"use strict";var GE=Ae(),WE=Pe(),Lh=GE.WeakMap;$h.exports=WE(Lh)&&/native code/.test(String(Lh))});var fu=g((bD,Bh)=>{"use strict";var zE=Mh(),Ch=Ae(),YE=Ge(),KE=sr(),du=It(),pu=ea(),XE=Us(),JE=js(),Dh="Object already initialized",hu=Ch.TypeError,ZE=Ch.WeakMap,Hs,sa,Qs,ex=function(a){return Qs(a)?sa(a):Hs(a,{})},tx=function(a){return function(e){var t;if(!YE(e)||(t=sa(e)).type!==a)throw new hu("Incompatible receiver, "+a+" required");return t}};zE||pu.state?(Et=pu.state||(pu.state=new ZE),Et.get=Et.get,Et.has=Et.has,Et.set=Et.set,Hs=function(a,e){if(Et.has(a))throw new hu(Dh);return e.facade=a,Et.set(a,e),e},sa=function(a){return Et.get(a)||{}},Qs=function(a){return Et.has(a)}):(Ci=XE("state"),JE[Ci]=!0,Hs=function(a,e){if(du(a,Ci))throw new hu(Dh);return e.facade=a,KE(a,Ci,e),e},sa=function(a){return du(a,Ci)?a[Ci]:{}},Qs=function(a){return du(a,Ci)});var Et,Ci;Bh.exports={set:Hs,get:sa,has:Qs,enforce:ex,getterFor:tx}});var gu=g((gD,_h)=>{"use strict";var mu=it(),ix=It(),Vh=Function.prototype,rx=mu&&Object.getOwnPropertyDescriptor,bu=ix(Vh,"name"),ax=bu&&function(){}.name==="something",sx=bu&&(!mu||mu&&rx(Vh,"name").configurable);_h.exports={EXISTS:bu,PROPER:ax,CONFIGURABLE:sx}});var Fh=g(Oh=>{"use strict";var nx=it(),ox=Zo(),ux=Mi(),lx=Mt(),cx=ki(),dx=lu();Oh.f=nx&&!ox?Object.defineProperties:function(e,t){lx(e);for(var i=cx(t),r=dx(t),s=r.length,n=0,u;s>n;)ux.f(e,u=r[n++],i[u]);return e}});var Su=g((vD,Nh)=>{"use strict";var px=jt();Nh.exports=px("document","documentElement")});var Iu=g((yD,Wh)=>{"use strict";var hx=Mt(),fx=Fh(),Uh=uu(),mx=js(),bx=Su(),gx=Os(),Sx=Us(),qh=">",jh="<",yu="prototype",Tu="script",Qh=Sx("IE_PROTO"),vu=function(){},Gh=function(a){return jh+Tu+qh+a+jh+"/"+Tu+qh},Hh=function(a){a.write(Gh("")),a.close();var e=a.parentWindow.Object;return a=null,e},vx=function(){var a=gx("iframe"),e="java"+Tu+":",t;return a.style.display="none",bx.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Gh("document.F=Object")),t.close(),t.F},Gs,Ws=function(){try{Gs=new ActiveXObject("htmlfile")}catch(e){}Ws=typeof document!="undefined"?document.domain&&Gs?Hh(Gs):vx():Hh(Gs);for(var a=Uh.length;a--;)delete Ws[yu][Uh[a]];return Ws()};mx[Qh]=!0;Wh.exports=Object.create||function(e,t){var i;return e!==null?(vu[yu]=hx(e),i=new vu,vu[yu]=null,i[Qh]=e):i=Ws(),t===void 0?i:fx.f(i,t)}});var cr=g((TD,zh)=>{"use strict";var yx=sr();zh.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:yx(a,e,t),a}});var Au=g((ID,Xh)=>{"use strict";var Tx=Me(),Ix=Pe(),Ex=Ge(),xx=Iu(),Yh=qs(),wx=cr(),Ax=Fe(),Px=Tt(),wu=Ax("iterator"),Kh=!1,Ht,Eu,xu;[].keys&&(xu=[].keys(),"next"in xu?(Eu=Yh(Yh(xu)),Eu!==Object.prototype&&(Ht=Eu)):Kh=!0);var Rx=!Ex(Ht)||Tx(function(){var a={};return Ht[wu].call(a)!==a});Rx?Ht={}:Px&&(Ht=xx(Ht));Ix(Ht[wu])||wx(Ht,wu,function(){return this});Xh.exports={IteratorPrototype:Ht,BUGGY_SAFARI_ITERATORS:Kh}});var zs=g((ED,Zh)=>{"use strict";var kx=Fe(),Lx=kx("toStringTag"),Jh={};Jh[Lx]="z";Zh.exports=String(Jh)==="[object z]"});var na=g((xD,ef)=>{"use strict";var $x=zs(),Mx=Pe(),Ys=Ri(),Dx=Fe(),Cx=Dx("toStringTag"),Bx=Object,Vx=Ys(function(){return arguments}())==="Arguments",_x=function(a,e){try{return a[e]}catch(t){}};ef.exports=$x?Ys:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=_x(e=Bx(a),Cx))=="string"?t:Vx?Ys(e):(i=Ys(e))==="Object"&&Mx(e.callee)?"Arguments":i}});var rf=g((wD,tf)=>{"use strict";var Ox=zs(),Fx=na();tf.exports=Ox?{}.toString:function(){return"[object "+Fx(this)+"]"}});var oa=g((AD,sf)=>{"use strict";var Nx=zs(),Ux=Mi().f,qx=sr(),jx=It(),Hx=rf(),Qx=Fe(),af=Qx("toStringTag");sf.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(jx(r,af)||Ux(r,af,{configurable:!0,value:e}),i&&!Nx&&qx(r,"toString",Hx))}});var of=g((PD,nf)=>{"use strict";var Gx=Au().IteratorPrototype,Wx=Iu(),zx=Yr(),Yx=oa(),Kx=Di(),Xx=function(){return this};nf.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=Wx(Gx,{next:zx(+!i,t)}),Yx(a,r,!1,!0),Kx[r]=Xx,a}});var lf=g((RD,uf)=>{"use strict";var Jx=De(),Zx=$t();uf.exports=function(a,e,t){try{return Jx(Zx(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var df=g((kD,cf)=>{"use strict";var ew=Ge();cf.exports=function(a){return ew(a)||a===null}});var hf=g((LD,pf)=>{"use strict";var tw=df(),iw=String,rw=TypeError;pf.exports=function(a){if(tw(a))return a;throw new rw("Can't set "+iw(a)+" as a prototype")}});var Pu=g(($D,ff)=>{"use strict";var aw=lf(),sw=Ge(),nw=ui(),ow=hf();ff.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=aw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return nw(r),ow(s),sw(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var wf=g((MD,xf)=>{"use strict";var uw=Le(),lw=rt(),Ks=Tt(),If=gu(),cw=Pe(),dw=of(),mf=qs(),bf=Pu(),pw=oa(),hw=sr(),Ru=cr(),fw=Fe(),gf=Di(),Ef=Au(),mw=If.PROPER,bw=If.CONFIGURABLE,Sf=Ef.IteratorPrototype,Xs=Ef.BUGGY_SAFARI_ITERATORS,ua=fw("iterator"),vf="keys",la="values",yf="entries",Tf=function(){return this};xf.exports=function(a,e,t,i,r,s,n){dw(t,e,i);var u=function(S){if(S===r&&f)return f;if(!Xs&&S&&S in d)return d[S];switch(S){case vf:return function(){return new t(this,S)};case la:return function(){return new t(this,S)};case yf:return function(){return new t(this,S)}}return function(){return new t(this)}},o=e+" Iterator",l=!1,d=a.prototype,c=d[ua]||d["@@iterator"]||r&&d[r],f=!Xs&&c||u(r),p=e==="Array"&&d.entries||c,h,b,v;if(p&&(h=mf(p.call(new a)),h!==Object.prototype&&h.next&&(!Ks&&mf(h)!==Sf&&(bf?bf(h,Sf):cw(h[ua])||Ru(h,ua,Tf)),pw(h,o,!0,!0),Ks&&(gf[o]=Tf))),mw&&r===la&&c&&c.name!==la&&(!Ks&&bw?hw(d,"name",la):(l=!0,f=function(){return lw(c,this)})),r)if(b={values:u(la),keys:s?f:u(vf),entries:u(yf)},n)for(v in b)(Xs||l||!(v in d))&&Ru(d,v,b[v]);else uw({target:e,proto:!0,forced:Xs||l},b);return(!Ks||n)&&d[ua]!==f&&Ru(d,ua,f,{name:r}),gf[e]=f,b}});var Pf=g((DD,Af)=>{"use strict";Af.exports=function(a,e){return{value:a,done:e}}});var Lu=g((CD,Mf)=>{"use strict";var gw=ki(),ku=aa(),Rf=Di(),Lf=fu(),Sw=Mi().f,vw=wf(),Js=Pf(),yw=Tt(),Tw=it(),$f="Array Iterator",Iw=Lf.set,Ew=Lf.getterFor($f);Mf.exports=vw(Array,"Array",function(a,e){Iw(this,{type:$f,target:gw(a),index:0,kind:e})},function(){var a=Ew(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,Js(void 0,!0);switch(a.kind){case"keys":return Js(t,!1);case"values":return Js(e[t],!1)}return Js([t,e[t]],!1)},"values");var kf=Rf.Arguments=Rf.Array;ku("keys");ku("values");ku("entries");if(!yw&&Tw&&kf.name!=="values")try{Sw(kf,"name",{value:"values"})}catch(a){}});var Cf=g((BD,Df)=>{"use strict";var xw=Fe(),ww=Di(),Aw=xw("iterator"),Pw=Array.prototype;Df.exports=function(a){return a!==void 0&&(ww.Array===a||Pw[Aw]===a)}});var $u=g((VD,Vf)=>{"use strict";var Rw=na(),Bf=Zr(),kw=Kr(),Lw=Di(),$w=Fe(),Mw=$w("iterator");Vf.exports=function(a){if(!kw(a))return Bf(a,Mw)||Bf(a,"@@iterator")||Lw[Rw(a)]}});var Of=g((_D,_f)=>{"use strict";var Dw=rt(),Cw=$t(),Bw=Mt(),Vw=Jr(),_w=$u(),Ow=TypeError;_f.exports=function(a,e){var t=arguments.length<2?_w(a):e;if(Cw(t))return Bw(Dw(t,a));throw new Ow(Vw(a)+" is not iterable")}});var Uf=g((OD,Nf)=>{"use strict";var Fw=rt(),Ff=Mt(),Nw=Zr();Nf.exports=function(a,e,t){var i,r;Ff(a);try{if(i=Nw(a,"return"),!i){if(e==="throw")throw t;return t}i=Fw(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Ff(i),t}});var en=g((FD,Qf)=>{"use strict";var Uw=ar(),qw=rt(),jw=Mt(),Hw=Jr(),Qw=Cf(),Gw=ur(),qf=Xr(),Ww=Of(),zw=$u(),jf=Uf(),Yw=TypeError,Zs=function(a,e){this.stopped=a,this.result=e},Hf=Zs.prototype;Qf.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=Uw(e,i),l,d,c,f,p,h,b,v=function(T){return l&&jf(l,"normal"),new Zs(!0,T)},S=function(T){return r?(jw(T),u?o(T[0],T[1],v):o(T[0],T[1])):u?o(T,v):o(T)};if(s)l=a.iterator;else if(n)l=a;else{if(d=zw(a),!d)throw new Yw(Hw(a)+" is not iterable");if(Qw(d)){for(c=0,f=Gw(a);f>c;c++)if(p=S(a[c]),p&&qf(Hf,p))return p;return new Zs(!1)}l=Ww(a,d)}for(h=s?a.next:l.next;!(b=qw(h,l)).done;){try{p=S(b.value)}catch(T){jf(l,"throw",T)}if(typeof p=="object"&&p&&qf(Hf,p))return p}return new Zs(!1)}});var Wf=g((ND,Gf)=>{"use strict";var Kw=it(),Xw=Mi(),Jw=Yr();Gf.exports=function(a,e,t){Kw?Xw.f(a,e,Jw(0,t)):a[e]=t}});var zf=g(()=>{"use strict";var Zw=Le(),eA=en(),tA=Wf();Zw({target:"Object",stat:!0},{fromEntries:function(e){var t={};return eA(e,function(i,r){tA(t,i,r)},{AS_ENTRIES:!0}),t}})});var Kf=g((jD,Yf)=>{"use strict";Lu();zf();var iA=Li();Yf.exports=iA.Object.fromEntries});var Jf=g((HD,Xf)=>{"use strict";Xf.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 em=g(()=>{"use strict";Lu();var rA=Jf(),aA=Ae(),sA=oa(),Zf=Di();for(tn in rA)sA(aA[tn],tn),Zf[tn]=Zf.Array;var tn});var im=g((WD,tm)=>{"use strict";var nA=Kf();em();tm.exports=nA});var Mu=g((zD,rm)=>{"use strict";var oA=im();rm.exports=oA});var am=g(()=>{"use strict"});var Du=g((XD,sm)=>{"use strict";var ca=Ae(),uA=$i(),lA=Ri(),rn=function(a){return uA.slice(0,a.length)===a};sm.exports=function(){return rn("Bun/")?"BUN":rn("Cloudflare-Workers")?"CLOUDFLARE":rn("Deno/")?"DENO":rn("Node.js/")?"NODE":ca.Bun&&typeof Bun.version=="string"?"BUN":ca.Deno&&typeof Deno.version=="object"?"DENO":lA(ca.process)==="process"?"NODE":ca.window&&ca.document?"BROWSER":"REST"}()});var an=g((JD,nm)=>{"use strict";var cA=Du();nm.exports=cA==="NODE"});var um=g((ZD,om)=>{"use strict";var dA=Mi();om.exports=function(a,e,t){return dA.f(a,e,t)}});var dm=g((e0,cm)=>{"use strict";var pA=jt(),hA=um(),fA=Fe(),mA=it(),lm=fA("species");cm.exports=function(a){var e=pA(a);mA&&e&&!e[lm]&&hA(e,lm,{configurable:!0,get:function(){return this}})}});var hm=g((t0,pm)=>{"use strict";var bA=Xr(),gA=TypeError;pm.exports=function(a,e){if(bA(e,a))return a;throw new gA("Incorrect invocation")}});var Bu=g((i0,fm)=>{"use strict";var SA=De(),vA=Pe(),Cu=ea(),yA=SA(Function.toString);vA(Cu.inspectSource)||(Cu.inspectSource=function(a){return yA(a)});fm.exports=Cu.inspectSource});var _u=g((r0,vm)=>{"use strict";var TA=De(),IA=Me(),mm=Pe(),EA=na(),xA=jt(),wA=Bu(),bm=function(){},gm=xA("Reflect","construct"),Vu=/^\s*(?:class|function)\b/,AA=TA(Vu.exec),PA=!Vu.test(bm),da=function(e){if(!mm(e))return!1;try{return gm(bm,[],e),!0}catch(t){return!1}},Sm=function(e){if(!mm(e))return!1;switch(EA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return PA||!!AA(Vu,wA(e))}catch(t){return!0}};Sm.sham=!0;vm.exports=!gm||IA(function(){var a;return da(da.call)||!da(Object)||!da(function(){a=!0})||a})?Sm:da});var Tm=g((a0,ym)=>{"use strict";var RA=_u(),kA=Jr(),LA=TypeError;ym.exports=function(a){if(RA(a))return a;throw new LA(kA(a)+" is not a constructor")}});var Ou=g((s0,Em)=>{"use strict";var Im=Mt(),$A=Tm(),MA=Kr(),DA=Fe(),CA=DA("species");Em.exports=function(a,e){var t=Im(a).constructor,i;return t===void 0||MA(i=Im(t)[CA])?e:$A(i)}});var wm=g((n0,xm)=>{"use strict";var BA=De();xm.exports=BA([].slice)});var Pm=g((o0,Am)=>{"use strict";var VA=TypeError;Am.exports=function(a,e){if(a<e)throw new VA("Not enough arguments");return a}});var Fu=g((u0,Rm)=>{"use strict";var _A=$i();Rm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(_A)});var zu=g((l0,_m)=>{"use strict";var at=Ae(),OA=Lo(),FA=ar(),km=Pe(),NA=It(),Vm=Me(),Lm=Su(),UA=wm(),$m=Os(),qA=Pm(),jA=Fu(),HA=an(),Qu=at.setImmediate,Gu=at.clearImmediate,QA=at.process,Nu=at.Dispatch,GA=at.Function,Mm=at.MessageChannel,WA=at.String,Uu=0,pa={},Dm="onreadystatechange",ha,Bi,qu,ju;Vm(function(){ha=at.location});var Wu=function(a){if(NA(pa,a)){var e=pa[a];delete pa[a],e()}},Hu=function(a){return function(){Wu(a)}},Cm=function(a){Wu(a.data)},Bm=function(a){at.postMessage(WA(a),ha.protocol+"//"+ha.host)};(!Qu||!Gu)&&(Qu=function(e){qA(arguments.length,1);var t=km(e)?e:GA(e),i=UA(arguments,1);return pa[++Uu]=function(){OA(t,void 0,i)},Bi(Uu),Uu},Gu=function(e){delete pa[e]},HA?Bi=function(a){QA.nextTick(Hu(a))}:Nu&&Nu.now?Bi=function(a){Nu.now(Hu(a))}:Mm&&!jA?(qu=new Mm,ju=qu.port2,qu.port1.onmessage=Cm,Bi=FA(ju.postMessage,ju)):at.addEventListener&&km(at.postMessage)&&!at.importScripts&&ha&&ha.protocol!=="file:"&&!Vm(Bm)?(Bi=Bm,at.addEventListener("message",Cm,!1)):Dm in $m("script")?Bi=function(a){Lm.appendChild($m("script"))[Dm]=function(){Lm.removeChild(this),Wu(a)}}:Bi=function(a){setTimeout(Hu(a),0)});_m.exports={set:Qu,clear:Gu}});var Nm=g((c0,Fm)=>{"use strict";var Om=Ae(),zA=it(),YA=Object.getOwnPropertyDescriptor;Fm.exports=function(a){if(!zA)return Om[a];var e=YA(Om,a);return e&&e.value}});var Yu=g((d0,qm)=>{"use strict";var Um=function(){this.head=null,this.tail=null};Um.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}}};qm.exports=Um});var Hm=g((p0,jm)=>{"use strict";var KA=$i();jm.exports=/ipad|iphone|ipod/i.test(KA)&&typeof Pebble!="undefined"});var Gm=g((h0,Qm)=>{"use strict";var XA=$i();Qm.exports=/web0s(?!.*chrome)/i.test(XA)});var Zm=g((f0,Jm)=>{"use strict";var pr=Ae(),JA=Nm(),Wm=ar(),Ku=zu().set,ZA=Yu(),eP=Fu(),tP=Hm(),iP=Gm(),Xu=an(),zm=pr.MutationObserver||pr.WebKitMutationObserver,Ym=pr.document,Km=pr.process,sn=pr.Promise,el=JA("queueMicrotask"),dr,Ju,Zu,nn,Xm;el||(fa=new ZA,ma=function(){var a,e;for(Xu&&(a=Km.domain)&&a.exit();e=fa.get();)try{e()}catch(t){throw fa.head&&dr(),t}a&&a.enter()},!eP&&!Xu&&!iP&&zm&&Ym?(Ju=!0,Zu=Ym.createTextNode(""),new zm(ma).observe(Zu,{characterData:!0}),dr=function(){Zu.data=Ju=!Ju}):!tP&&sn&&sn.resolve?(nn=sn.resolve(void 0),nn.constructor=sn,Xm=Wm(nn.then,nn),dr=function(){Xm(ma)}):Xu?dr=function(){Km.nextTick(ma)}:(Ku=Wm(Ku,pr),dr=function(){Ku(ma)}),el=function(a){fa.head||dr(),fa.add(a)});var fa,ma;Jm.exports=el});var tb=g((m0,eb)=>{"use strict";eb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var on=g((b0,ib)=>{"use strict";ib.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Vi=g((g0,rb)=>{"use strict";var rP=Ae();rb.exports=rP.Promise});var hr=g((S0,ob)=>{"use strict";var aP=Ae(),ba=Vi(),sP=Pe(),nP=Jo(),oP=Bu(),uP=Fe(),ab=Du(),lP=Tt(),tl=Fo(),sb=ba&&ba.prototype,cP=uP("species"),il=!1,nb=sP(aP.PromiseRejectionEvent),dP=nP("Promise",function(){var a=oP(ba),e=a!==String(ba);if(!e&&tl===66||lP&&!(sb.catch&&sb.finally))return!0;if(!tl||tl<51||!/native code/.test(a)){var t=new ba(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[cP]=i,il=t.then(function(){})instanceof i,!il)return!0}return!e&&(ab==="BROWSER"||ab==="DENO")&&!nb});ob.exports={CONSTRUCTOR:dP,REJECTION_EVENT:nb,SUBCLASSING:il}});var fr=g((v0,lb)=>{"use strict";var ub=$t(),pP=TypeError,hP=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new pP("Bad Promise constructor");e=i,t=r}),this.resolve=ub(e),this.reject=ub(t)};lb.exports.f=function(a){return new hP(a)}});var kb=g(()=>{"use strict";var fP=Le(),mP=Tt(),dn=an(),ci=Ae(),bP=Li(),Sr=rt(),cb=cr(),db=Pu(),gP=oa(),SP=dm(),vP=$t(),cn=Pe(),yP=Ge(),TP=hm(),IP=Ou(),bb=zu().set,ol=Zm(),EP=tb(),xP=on(),wP=Yu(),gb=fu(),pn=Vi(),ul=hr(),Sb=fr(),hn="Promise",vb=ul.CONSTRUCTOR,AP=ul.REJECTION_EVENT,PP=ul.SUBCLASSING,rl=gb.getterFor(hn),RP=gb.set,mr=pn&&pn.prototype,_i=pn,un=mr,yb=ci.TypeError,al=ci.document,ll=ci.process,sl=Sb.f,kP=sl,LP=!!(al&&al.createEvent&&ci.dispatchEvent),Tb="unhandledrejection",$P="rejectionhandled",pb=0,Ib=1,MP=2,cl=1,Eb=2,ln,hb,xb,fb,wb=function(a){var e;return yP(a)&&cn(e=a.then)?e:!1},Ab=function(a,e){var t=e.value,i=e.state===Ib,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,u=a.domain,o,l,d;try{r?(i||(e.rejection===Eb&&CP(e),e.rejection=cl),r===!0?o=t:(u&&u.enter(),o=r(t),u&&(u.exit(),d=!0)),o===a.promise?n(new yb("Promise-chain cycle")):(l=wb(o))?Sr(l,o,s,n):s(o)):n(t)}catch(c){u&&!d&&u.exit(),n(c)}},Pb=function(a,e){a.notified||(a.notified=!0,ol(function(){for(var t=a.reactions,i;i=t.get();)Ab(i,a);a.notified=!1,e&&!a.rejection&&DP(a)}))},Rb=function(a,e,t){var i,r;LP?(i=al.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),ci.dispatchEvent(i)):i={promise:e,reason:t},!AP&&(r=ci["on"+a])?r(i):a===Tb&&EP("Unhandled promise rejection",t)},DP=function(a){Sr(bb,ci,function(){var e=a.facade,t=a.value,i=mb(a),r;if(i&&(r=xP(function(){dn?ll.emit("unhandledRejection",t,e):Rb(Tb,e,t)}),a.rejection=dn||mb(a)?Eb:cl,r.error))throw r.value})},mb=function(a){return a.rejection!==cl&&!a.parent},CP=function(a){Sr(bb,ci,function(){var e=a.facade;dn?ll.emit("rejectionHandled",e):Rb($P,e,a.value)})},br=function(a,e,t){return function(i){a(e,i,t)}},gr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=MP,Pb(a,!0))},nl=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new yb("Promise can't be resolved itself");var i=wb(e);i?ol(function(){var r={done:!1};try{Sr(i,e,br(nl,r,a),br(gr,r,a))}catch(s){gr(r,s,a)}}):(a.value=e,a.state=Ib,Pb(a,!1))}catch(r){gr({done:!1},r,a)}}};if(vb&&(_i=function(e){TP(this,un),vP(e),Sr(ln,this);var t=rl(this);try{e(br(nl,t),br(gr,t))}catch(i){gr(t,i)}},un=_i.prototype,ln=function(e){RP(this,{type:hn,done:!1,notified:!1,parent:!1,reactions:new wP,rejection:!1,state:pb,value:null})},ln.prototype=cb(un,"then",function(e,t){var i=rl(this),r=sl(IP(this,_i));return i.parent=!0,r.ok=cn(e)?e:!0,r.fail=cn(t)&&t,r.domain=dn?ll.domain:void 0,i.state===pb?i.reactions.add(r):ol(function(){Ab(r,i)}),r.promise}),hb=function(){var a=new ln,e=rl(a);this.promise=a,this.resolve=br(nl,e),this.reject=br(gr,e)},Sb.f=sl=function(a){return a===_i||a===xb?new hb(a):kP(a)},!mP&&cn(pn)&&mr!==Object.prototype)){fb=mr.then,PP||cb(mr,"then",function(e,t){var i=this;return new _i(function(r,s){Sr(fb,i,r,s)}).then(e,t)},{unsafe:!0});try{delete mr.constructor}catch(a){}db&&db(mr,un)}fP({global:!0,constructor:!0,wrap:!0,forced:vb},{Promise:_i});xb=bP.Promise;gP(_i,hn,!1,!0);SP(hn)});var Cb=g((I0,Db)=>{"use strict";var BP=Fe(),$b=BP("iterator"),Mb=!1;try{Lb=0,dl={next:function(){return{done:!!Lb++}},return:function(){Mb=!0}},dl[$b]=function(){return this},Array.from(dl,function(){throw 2})}catch(a){}var Lb,dl;Db.exports=function(a,e){try{if(!e&&!Mb)return!1}catch(r){return!1}var t=!1;try{var i={};i[$b]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var pl=g((E0,Bb)=>{"use strict";var VP=Vi(),_P=Cb(),OP=hr().CONSTRUCTOR;Bb.exports=OP||!_P(function(a){VP.all(a).then(void 0,function(){})})});var Vb=g(()=>{"use strict";var FP=Le(),NP=rt(),UP=$t(),qP=fr(),jP=on(),HP=en(),QP=pl();FP({target:"Promise",stat:!0,forced:QP},{all:function(e){var t=this,i=qP.f(t),r=i.resolve,s=i.reject,n=jP(function(){var u=UP(t.resolve),o=[],l=0,d=1;HP(e,function(c){var f=l++,p=!1;d++,NP(u,t,c).then(function(h){p||(p=!0,o[f]=h,--d||r(o))},s)}),--d||r(o)});return n.error&&s(n.value),i.promise}})});var Ob=g(()=>{"use strict";var GP=Le(),WP=Tt(),zP=hr().CONSTRUCTOR,fl=Vi(),YP=jt(),KP=Pe(),XP=cr(),_b=fl&&fl.prototype;GP({target:"Promise",proto:!0,forced:zP,real:!0},{catch:function(a){return this.then(void 0,a)}});!WP&&KP(fl)&&(hl=YP("Promise").prototype.catch,_b.catch!==hl&&XP(_b,"catch",hl,{unsafe:!0}));var hl});var Fb=g(()=>{"use strict";var JP=Le(),ZP=rt(),eR=$t(),tR=fr(),iR=on(),rR=en(),aR=pl();JP({target:"Promise",stat:!0,forced:aR},{race:function(e){var t=this,i=tR.f(t),r=i.reject,s=iR(function(){var n=eR(t.resolve);rR(e,function(u){ZP(n,t,u).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Nb=g(()=>{"use strict";var sR=Le(),nR=fr(),oR=hr().CONSTRUCTOR;sR({target:"Promise",stat:!0,forced:oR},{reject:function(e){var t=nR.f(this),i=t.reject;return i(e),t.promise}})});var ml=g((M0,Ub)=>{"use strict";var uR=Mt(),lR=Ge(),cR=fr();Ub.exports=function(a,e){if(uR(a),lR(e)&&e.constructor===a)return e;var t=cR.f(a),i=t.resolve;return i(e),t.promise}});var Hb=g(()=>{"use strict";var dR=Le(),pR=jt(),qb=Tt(),hR=Vi(),jb=hr().CONSTRUCTOR,fR=ml(),mR=pR("Promise"),bR=qb&&!jb;dR({target:"Promise",stat:!0,forced:qb||jb},{resolve:function(e){return fR(bR&&this===mR?hR:this,e)}})});var Qb=g(()=>{"use strict";kb();Vb();Ob();Fb();Nb();Hb()});var Yb=g(()=>{"use strict";var gR=Le(),SR=Tt(),fn=Vi(),vR=Me(),Wb=jt(),zb=Pe(),yR=Ou(),Gb=ml(),TR=cr(),gl=fn&&fn.prototype,IR=!!fn&&vR(function(){gl.finally.call({then:function(){}},function(){})});gR({target:"Promise",proto:!0,real:!0,forced:IR},{finally:function(a){var e=yR(this,Wb("Promise")),t=zb(a);return this.then(t?function(i){return Gb(e,a()).then(function(){return i})}:a,t?function(i){return Gb(e,a()).then(function(){throw i})}:a)}});!SR&&zb(fn)&&(bl=Wb("Promise").prototype.finally,gl.finally!==bl&&TR(gl,"finally",bl,{unsafe:!0}));var bl});var Xb=g((F0,Kb)=>{"use strict";am();Qb();Yb();var ER=li();Kb.exports=ER("Promise","finally")});var Zb=g((N0,Jb)=>{"use strict";var xR=Xb();Jb.exports=xR});var mn=g((U0,eg)=>{"use strict";var wR=Zb();eg.exports=wR});var hg=g(()=>{"use strict";var VR=Le(),_R=cu().values;VR({target:"Object",stat:!0},{values:function(e){return _R(e)}})});var mg=g((eB,fg)=>{"use strict";hg();var OR=Li();fg.exports=OR.Object.values});var gg=g((tB,bg)=>{"use strict";var FR=mg();bg.exports=FR});var Tr=g((iB,Sg)=>{"use strict";var NR=gg();Sg.exports=NR});var Ig=g(()=>{"use strict";var HR=Le(),QR=ir(),GR=ur(),WR=ra(),zR=aa();HR({target:"Array",proto:!0},{at:function(e){var t=QR(this),i=GR(t),r=WR(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});zR("at")});var xg=g((RB,Eg)=>{"use strict";Ig();var YR=li();Eg.exports=YR("Array","at")});var Ag=g((kB,wg)=>{"use strict";var KR=xg();wg.exports=KR});var xt=g((LB,Pg)=>{"use strict";var XR=Ag();Pg.exports=XR});var Fl=g((h_,Xg)=>{"use strict";var uk=Ri();Xg.exports=Array.isArray||function(e){return uk(e)==="Array"}});var Zg=g((f_,Jg)=>{"use strict";var lk=TypeError,ck=9007199254740991;Jg.exports=function(a){if(a>ck)throw lk("Maximum allowed index exceeded");return a}});var iS=g((m_,tS)=>{"use strict";var dk=Fl(),pk=ur(),hk=Zg(),fk=ar(),eS=function(a,e,t,i,r,s,n,u){for(var o=r,l=0,d=n?fk(n,u):!1,c,f;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&dk(c)?(f=pk(c),o=eS(a,e,c,f,o,s-1)-1):(hk(o+1),a[o]=c),o++),l++;return o};tS.exports=eS});var nS=g((b_,sS)=>{"use strict";var rS=Fl(),mk=_u(),bk=Ge(),gk=Fe(),Sk=gk("species"),aS=Array;sS.exports=function(a){var e;return rS(a)&&(e=a.constructor,mk(e)&&(e===aS||rS(e.prototype))?e=void 0:bk(e)&&(e=e[Sk],e===null&&(e=void 0))),e===void 0?aS:e}});var uS=g((g_,oS)=>{"use strict";var vk=nS();oS.exports=function(a,e){return new(vk(a))(e===0?0:e)}});var lS=g(()=>{"use strict";var yk=Le(),Tk=iS(),Ik=$t(),Ek=ir(),xk=ur(),wk=uS();yk({target:"Array",proto:!0},{flatMap:function(e){var t=Ek(this),i=xk(t),r;return Ik(e),r=wk(t,0),r.length=Tk(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var cS=g(()=>{"use strict";var Ak=aa();Ak("flatMap")});var pS=g((I_,dS)=>{"use strict";lS();cS();var Pk=li();dS.exports=Pk("Array","flatMap")});var fS=g((E_,hS)=>{"use strict";var Rk=pS();hS.exports=Rk});var Ra=g((x_,mS)=>{"use strict";var kk=fS();mS.exports=kk});var ka=g((w_,bS)=>{"use strict";var Lk=na(),$k=String;bS.exports=function(a){if(Lk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return $k(a)}});var Nl=g((A_,gS)=>{"use strict";gS.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 yS=g((P_,vS)=>{"use strict";var Mk=De(),Dk=ui(),Ck=ka(),ql=Nl(),SS=Mk("".replace),Bk=RegExp("^["+ql+"]+"),Vk=RegExp("(^|[^"+ql+"])["+ql+"]+$"),Ul=function(a){return function(e){var t=Ck(Dk(e));return a&1&&(t=SS(t,Bk,"")),a&2&&(t=SS(t,Vk,"$1")),t}};vS.exports={start:Ul(1),end:Ul(2),trim:Ul(3)}});var xS=g((R_,ES)=>{"use strict";var _k=gu().PROPER,Ok=Me(),TS=Nl(),IS="\u200B\x85\u180E";ES.exports=function(a){return Ok(function(){return!!TS[a]()||IS[a]()!==IS||_k&&TS[a].name!==a})}});var jl=g((k_,wS)=>{"use strict";var Fk=yS().start,Nk=xS();wS.exports=Nk("trimStart")?function(){return Fk(this)}:"".trimStart});var PS=g(()=>{"use strict";var Uk=Le(),AS=jl();Uk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==AS},{trimLeft:AS})});var kS=g(()=>{"use strict";PS();var qk=Le(),RS=jl();qk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==RS},{trimStart:RS})});var $S=g((C_,LS)=>{"use strict";kS();var jk=li();LS.exports=jk("String","trimLeft")});var DS=g((B_,MS)=>{"use strict";var Hk=$S();MS.exports=Hk});var BS=g((V_,CS)=>{"use strict";var Qk=DS();CS.exports=Qk});var KS=g(()=>{"use strict"});var XS=g(()=>{"use strict"});var ZS=g((yN,JS)=>{"use strict";var dL=Ge(),pL=Ri(),hL=Fe(),fL=hL("match");JS.exports=function(a){var e;return dL(a)&&((e=a[fL])!==void 0?!!e:pL(a)==="RegExp")}});var iv=g((TN,tv)=>{"use strict";var mL=Ae(),bL=Me(),ev=mL.RegExp,gL=!bL(function(){var a=!0;try{ev(".","d")}catch(o){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(ev.prototype,"flags").get.call(e);return u!==i||t!==i});tv.exports={correct:gL}});var av=g((IN,rv)=>{"use strict";var SL=Mt();rv.exports=function(){var a=SL(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 ov=g((EN,nv)=>{"use strict";var vL=rt(),yL=It(),TL=Xr(),sv=iv(),IL=av(),EL=RegExp.prototype;nv.exports=sv.correct?function(a){return a.flags}:function(a){return!sv.correct&&TL(EL,a)&&!yL(a,"flags")?vL(IL,a):a.flags}});var lv=g((xN,uv)=>{"use strict";var Wl=De(),xL=ir(),wL=Math.floor,Ql=Wl("".charAt),AL=Wl("".replace),Gl=Wl("".slice),PL=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,RL=/\$([$&'`]|\d{1,2})/g;uv.exports=function(a,e,t,i,r,s){var n=t+a.length,u=i.length,o=RL;return r!==void 0&&(r=xL(r),o=PL),AL(s,o,function(l,d){var c;switch(Ql(d,0)){case"$":return"$";case"&":return a;case"`":return Gl(e,0,t);case"'":return Gl(e,n);case"<":c=r[Gl(d,1,-1)];break;default:var f=+d;if(f===0)return l;if(f>u){var p=wL(f/10);return p===0?l:p<=u?i[p-1]===void 0?Ql(d,1):i[p-1]+Ql(d,1):l}c=i[f-1]}return c===void 0?"":c})}});var pv=g(()=>{"use strict";var kL=Le(),LL=rt(),Yl=De(),cv=ui(),$L=Pe(),ML=Ge(),DL=ZS(),$r=ka(),CL=Zr(),BL=ov(),VL=lv(),_L=Fe(),OL=Tt(),FL=_L("replace"),NL=TypeError,zl=Yl("".indexOf),UL=Yl("".replace),dv=Yl("".slice),qL=Math.max;kL({target:"String",proto:!0},{replaceAll:function(e,t){var i=cv(this),r,s,n,u,o,l,d,c,f,p,h=0,b="";if(ML(e)){if(r=DL(e),r&&(s=$r(cv(BL(e))),!~zl(s,"g")))throw new NL("`.replaceAll` does not allow non-global regexes");if(n=CL(e,FL),n)return LL(n,e,i,t);if(OL&&r)return UL($r(i),e,t)}for(u=$r(i),o=$r(e),l=$L(t),l||(t=$r(t)),d=o.length,c=qL(1,d),f=zl(u,o);f!==-1;)p=l?$r(t(o,f,u)):VL(o,u,f,[],void 0,t),b+=dv(u,h,f)+p,h=f+d,f=f+c>u.length?-1:zl(u,o,f+c);return h<u.length&&(b+=dv(u,h)),b}})});var fv=g((PN,hv)=>{"use strict";KS();XS();pv();var jL=li();hv.exports=jL("String","replaceAll")});var bv=g((RN,mv)=>{"use strict";var HL=fv();mv.exports=HL});var Sv=g((kN,gv)=>{"use strict";var QL=bv();gv.exports=QL});var yv=g((LN,vv)=>{"use strict";var GL=ra(),WL=ka(),zL=ui(),YL=RangeError;vv.exports=function(e){var t=WL(zL(this)),i="",r=GL(e);if(r<0||r===1/0)throw new YL("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var wv=g(($N,xv)=>{"use strict";var Ev=De(),KL=au(),Tv=ka(),XL=yv(),JL=ui(),ZL=Ev(XL),e$=Ev("".slice),t$=Math.ceil,Iv=function(a){return function(e,t,i){var r=Tv(JL(e)),s=KL(t),n=r.length,u=i===void 0?" ":Tv(i),o,l;return s<=n||u===""?r:(o=s-n,l=ZL(u,t$(o/u.length)),l.length>o&&(l=e$(l,0,o)),a?r+l:l+r)}};xv.exports={start:Iv(!1),end:Iv(!0)}});var Pv=g((MN,Av)=>{"use strict";var i$=$i();Av.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(i$)});var Rv=g(()=>{"use strict";var r$=Le(),a$=wv().start,s$=Pv();r$({target:"String",proto:!0,forced:s$},{padStart:function(e){return a$(this,e,arguments.length>1?arguments[1]:void 0)}})});var Lv=g((BN,kv)=>{"use strict";Rv();var n$=li();kv.exports=n$("String","padStart")});var Mv=g((VN,$v)=>{"use strict";var o$=Lv();$v.exports=o$});var Cv=g((_N,Dv)=>{"use strict";var u$=Mv();Dv.exports=u$});var C$={};Yy(C$,{ChromecastState:()=>Qr,HttpConnectionType:()=>Cs,Observable:()=>Nt.Observable,PlaybackState:()=>je,Player:()=>vs,PredefinedQualityLimits:()=>Gr,SDK_VERSION:()=>D$,Subject:()=>Nt.Subject,Subscription:()=>Nt.Subscription,Surface:()=>Bs,VERSION:()=>Ro,ValueSubject:()=>Nt.ValueSubject,VideoFormat:()=>Lt,VideoQuality:()=>Nt.VideoQuality,areValidLiveRecordSources:()=>ug,clientChecker:()=>X,isMobile:()=>vr});module.exports=Ky(C$);var Ro="2.0.136-dev.0bf6b475.0";var je=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(je||{}),Lt=(E=>(E.MPEG="MPEG",E.DASH="DASH",E.DASH_SEP="DASH_SEP",E.DASH_SEP_VK="DASH_SEP",E.DASH_WEBM="DASH_WEBM",E.DASH_WEBM_AV1="DASH_WEBM_AV1",E.DASH_STREAMS="DASH_STREAMS",E.DASH_WEBM_VK="DASH_WEBM",E.DASH_ONDEMAND="DASH_ONDEMAND",E.DASH_ONDEMAND_VK="DASH_ONDEMAND",E.DASH_LIVE="DASH_LIVE",E.DASH_LIVE_CMAF="DASH_LIVE_CMAF",E.DASH_LIVE_WEBM="DASH_LIVE_WEBM",E.HLS="HLS",E.HLS_ONDEMAND="HLS_ONDEMAND",E.HLS_JS="HLS",E.HLS_LIVE="HLS_LIVE",E.HLS_LIVE_CMAF="HLS_LIVE_CMAF",E.WEB_RTC_LIVE="WEB_RTC_LIVE",E))(Lt||{});var Qr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Qr||{}),Cs=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Cs||{});var Bs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Bs||{}),Gr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Gr||{});var Cy=J(dt(),1);var se=require("@vkontakte/videoplayer-shared/es2015");var sh=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 Ns=class{constructor(e){this.connection$=new se.ValueSubject(void 0);this.castState$=new se.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new se.Subject;this.realCastState$=new se.ValueSubject("NOT_AVAILABLE");this.subscription=new se.Subscription;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,se.isNonNullable)((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||sh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:se.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,se.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,se.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,se.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add((0,se.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,u;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(u=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:u.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,se.assertNever)(r.sessionState)}})).add((0,se.merge)((0,se.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,se.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,se.map)(r=>r.castState)),(0,se.observableFrom)([i.getCastState()])).pipe((0,se.filterChanged)(),(0,se.map)(SE),(0,se.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var u,o;let s=r==="CONNECTED",n=(0,se.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();(0,se.assertNonNullable)(l);let d=l.getCastDevice(),c=(o=(u=l.getMediaSession())==null?void 0:u.media)==null?void 0:o.contentId;((0,se.isNullable)(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,se.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:se.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},SE=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,se.assertNever)(a)}};var Ic=J(dt(),1),Ty=J(lr(),1),Iy=J(Mu(),1);var cg=J(mn(),1);var Sl=require("@vkontakte/videoplayer-shared/es2015");var Re=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Sl.assertNever)(t)}return a},di=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Sl.assertNever)(e)}};var j=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var Dt=require("@vkontakte/videoplayer-shared/es2015"),ne=class{constructor(e){this.transitionStarted$=new Dt.Subject;this.transitionEnded$=new Dt.Subject;this.transitionUpdated$=new Dt.Subject;this.forceChanged$=new Dt.Subject;this.stateChangeStarted$=(0,Dt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Dt.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,Dt.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var yl=require("@vkontakte/videoplayer-shared/es2015");var bn=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 tg=J(dt(),1);var vr=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var gn=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,tg.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=vr()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return R(this,null,function*(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=yield 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 Sn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var st=()=>window.ManagedMediaSource||window.MediaSource,yr=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},ig=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},vn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var AR=document.createElement("video"),PR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',RR='video/mp4; codecs="hev1.1.6.L93.B0"',rg='video/webm; codecs="vp09.00.10.08"',ag='video/webm; codecs="av01.0.00M.08"',kR='audio/mp4; codecs="mp4a.40.2"',LR='audio/webm; codecs="opus"',sg,$R=()=>R(null,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Q(C({},a),{video:Q(C({},a.video),{contentType:ag})})),window.navigator.mediaCapabilities.decodingInfo(Q(C({},a),{video:Q(C({},a.video),{contentType:rg})}))]);sg={DASH_WEBM_AV1:e,DASH_WEBM:t}});$R().catch(a=>{console.log(AR),console.error(a)});var yn=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 sg}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,u,o,l,d,c,f,p,h,b,v,S,T,E,w;this._video=document.createElement("video");try{this._protocols={mms:yr(),mse:ig(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((o=(u=this._video).canPlayType)!=null&&o.call(u,"video/webm")),cmaf:!0};let A=!!((d=(l=st())==null?void 0:l.isTypeSupported)!=null&&d.call(l,PR)),O=!!((f=(c=st())==null?void 0:c.isTypeSupported)!=null&&f.call(c,RR)),H=!!((h=(p=st())==null?void 0:p.isTypeSupported)!=null&&h.call(p,kR));this._codecs={h264:A,h265:O,vp9:!!((v=(b=st())==null?void 0:b.isTypeSupported)!=null&&v.call(b,rg)),av1:!!((T=(S=st())==null?void 0:S.isTypeSupported)!=null&&T.call(S,ag)),aac:H,opus:!!((w=(E=st())==null?void 0:E.isTypeSupported)!=null&&w.call(E,LR)),mpeg:(A||O)&&H},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(A){console.error(A)}try{this.destroyVideoElement()}catch(A){console.error("Error destroying video element:",A)}}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var ng="audio/mpeg",Tn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,ng))},this._codecs={mp3:!!((r=(i=st())==null?void 0:i.isTypeSupported)!=null&&r.call(i,ng))}}catch(s){console.error(s)}try{this.destroyAudioElement()}catch(s){console.error("Error destroying audio element:",s)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};var og=require("@vkontakte/videoplayer-shared/es2015");var vl=class{constructor(){this.isInited$=new og.ValueSubject(!1);this._displayChecker=new Sn,this._deviceChecker=new gn(this._displayChecker),this._browserChecker=new bn,this._videoChecker=new yn(this._deviceChecker,this._browserChecker),this._audioChecker=new Tn,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}detect(){return R(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},X=new vl;var Tl=(a,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:n}=X.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(0,yl.assertNever)(l)}})},Il=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,yl.assertNever)(a)}},ug=(a,e)=>{let i=Object.keys(a).filter(r=>!Il(r));return Tl(i,e).length>0};var W=require("@vkontakte/videoplayer-shared/es2015");var MR=5,DR=5,CR=500,lg=7e3,ga=class{constructor(e){this.subscription=new W.Subscription;this.loadMediaTimeoutSubscription=new W.Subscription;this.videoState=new ne("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,W.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,W.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,W.assertNever)(e)}break}default:(0,W.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Il(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 W.Subscription;this.subscription.add(e),this.subscription.add((0,W.merge)(this.videoState.stateChangeStarted$.pipe((0,W.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,W.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new W.Subject;e.add(r.pipe((0,W.debounce)(CR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,W.fromEvent)(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)>MR)&&r.next(u),s=u})),e.add((0,W.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,W.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,W.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,W.fromEvent)(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<DR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),j(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,W.assertNever)(n)}}),t((0,W.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,W.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,W.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,W.observableFrom)(["init"])).pipe((0,W.debounce)(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),j(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),j(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),j(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),j(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&j(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let d=t[e];(0,W.assertNonNullable)(d);let c=(0,W.getHighestQuality)(Object.keys(d));(0,W.assertNonNullable)(c);let f=d[c];(0,W.assertNonNullable)(f),i=f,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];(0,W.assertNonNullable)(d),i=d.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];(0,W.assertNonNullable)(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];(0,W.assertNonNullable)(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];(0,W.assertNonNullable)(d),i=Re(d.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:W.ErrorCategory.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,W.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:u,subtitle:o}=this.params.meta;return(0,W.isNonNullable)(u)&&(n.metadata.title=u),(0,W.isNonNullable)(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((0,W.timeout)(lg).subscribe(()=>s(`timeout(${lg})`)))});(0,cg.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:W.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var _l=J(dt(),1);var Al=require("@vkontakte/videoplayer-shared/es2015");var dg=require("@vkontakte/videoplayer-shared/es2015"),pg=a=>{try{a.pause(),a.playbackRate=0,(0,dg.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var In=require("@vkontakte/videoplayer-shared/es2015"),El=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)}},xl=window.WeakMap?new WeakMap:new El,wl=window.WeakMap?new WeakMap:new Map,BR=(a,e=20)=>{let t=0;return(0,In.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},We=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?(0,Al.clearVideoElement)(i):(i=document.createElement("video"),a.appendChild(i)),xl.set(i,r);let s=new In.Subscription;return s.add(BR(i,e)),wl.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},ze=a=>{let e=wl.get(a);e==null||e.unsubscribe(),wl.delete(a);let t=xl.get(a);xl.delete(a),t?(0,Al.clearVideoElement)(a):pg(a)};var Pl=J(Tr(),1),z=require("@vkontakte/videoplayer-shared/es2015");var pi=require("@vkontakte/videoplayer-shared/es2015"),En=(a,e,t,{equal:i=(n,u)=>n===u,changed$:r,onError:s}={})=>{let n=a.getState(),u=e(),o=(0,pi.isNullable)(r),l=new pi.Subscription;return r&&l.add(r.subscribe(d=>{let c=a.getState();i(d,c)&&a.setState(d)},s)),i(u,n)||(t(n),o&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),o&&a.setState(d.to)},s)),l},Ct=(a,e,t)=>En(e,()=>a.loop,i=>{(0,pi.isNonNullable)(i)&&(a.loop=i)},{onError:t}),Ye=(a,e,t,i)=>En(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,pi.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),pt=(a,e,t,i)=>En(e,()=>a.playbackRate,r=>{(0,pi.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Sa=En;var UR=a=>["__",a.language,a.label].join("|"),qR=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Rl=class a{constructor(e){this.available$=new z.Subject;this.current$=new z.ValueSubject(void 0);this.error$=new z.Subject;this.subscription=new z.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:z.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Sa(t.internalTextTracks,()=>(0,Pl.default)(this.internalTracks),s=>{(0,z.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,z.isNonNullable)(s)&&(0,z.isNonNullable)(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe((0,z.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Sa(t.externalTextTracks,()=>(0,Pl.default)(this.externalTracks),s=>{(0,z.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,z.isNonNullable)(s)&&(0,z.isNonNullable)(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe((0,z.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Sa(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(Sa(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,z.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,z.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,z.merge)((0,z.fromEvent)(e,"addtrack"),(0,z.fromEvent)(e,"removetrack"),(0,z.observableFrom)(["init"])).pipe((0,z.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,z.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,z.merge)((0,z.fromEvent)(e,"change"),(0,z.observableFrom)(["init"])).pipe((0,z.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,z.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,z.filterChanged)()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add((0,z.fromEvent)(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=u=>{var l,d,c,f,p;let o=(d=(l=u.target)==null?void 0:l.cues)!=null?d:null;o&&o.length&&(this.applyCueSettings((f=(c=u.target)==null?void 0:c.cues)!=null?f:null),(p=u.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,z.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,z.isNonNullable)(t.align)&&(r.align=t.align),(0,z.isNonNullable)(t.position)&&(r.position=t.position),(0,z.isNonNullable)(t.size)&&(r.size=t.size),(0,z.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,z.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var u,o,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:UR(e),s=this.externalTracks.has(r),n=(l=s?(u=this.externalTracks.get(r))==null?void 0:u.isAuto:(o=this.internalTracks.get(r))==null?void 0:o.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,z.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,z.isNullable)(e)||!qR(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,z.assertNonNullable)(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,z.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},ht=Rl;var Oi=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 vg=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},kl=a=>{let e=vg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},yg=a=>{let e=vg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var D=require("@vkontakte/videoplayer-shared/es2015");var jR=3,Tg=(a,e,t=jR)=>{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 Ke=a=>{let e=M=>(0,D.fromEvent)(a,M).pipe((0,D.mapTo)(void 0),(0,D.shareReplay)(1)),t=new D.Subscription,i=()=>t.unsubscribe(),r=(0,D.merge)((0,D.fromEvent)(a,"progress"),(0,D.fromEvent)(a,"timeupdate")).pipe((0,D.map)(()=>Tg(a.buffered,a.currentTime)),(0,D.shareReplay)(1)),s=X.browser.isSafari?(0,D.combine)({play:e("play").pipe((0,D.once)()),playing:e("playing")}).pipe((0,D.mapTo)(void 0),(0,D.shareReplay)(1)):e("playing"),n=(0,D.fromEvent)(a,"volumechange").pipe((0,D.map)(()=>({muted:a.muted,volume:a.volume})),(0,D.shareReplay)(1)),u=(0,D.fromEvent)(a,"ratechange").pipe((0,D.map)(()=>a.playbackRate),(0,D.shareReplay)(1)),o=(0,D.fromEvent)(a,"error").pipe((0,D.filter)(()=>!!(a.error||a.played.length)),(0,D.map)(()=>{var G;let M=a.error;return{id:M?`MediaError#${M.code}`:"HtmlVideoError",category:D.ErrorCategory.VIDEO_PIPELINE,message:M?M.message:"Error event from HTML video element",thrown:(G=a.error)!=null?G:void 0}}),(0,D.shareReplay)(1)),l=(0,D.fromEvent)(a,"timeupdate").pipe((0,D.map)(()=>a.currentTime),(0,D.shareReplay)(1)),d=["waiting","seeking","seeked","timeupdate"],c=new D.Subject,f=.3,p;t.add((0,D.merge)(...d.map(M=>(0,D.fromEvent)(a,M))).subscribe(M=>{let G=a.currentTime;a.loop&&(0,D.isNonNullable)(p)&&(0,D.isNonNullable)(G)&&p>=a.duration-f&&G<=f&&c.next(p),p=G}));let h=e("pause").pipe((0,D.filter)(()=>!a.error&&p!==a.duration),(0,D.shareReplay)(1)),b=(0,D.fromEvent)(a,"enterpictureinpicture").pipe((0,D.shareReplay)(1)),v=(0,D.fromEvent)(a,"leavepictureinpicture").pipe((0,D.shareReplay)(1)),S=new D.ValueSubject(yg(a));t.add(b.subscribe(()=>S.next(!0))),t.add(v.subscribe(()=>S.next(!1)));let T=new D.ValueSubject(kl(a)),E=(0,D.fromEvent)(a,"fullscreenchange").pipe((0,D.shareReplay)(1));t.add(E.pipe((0,D.map)(()=>kl(a))).subscribe(T));let w=.1,A=1e3,O=(0,D.fromEvent)(a,"timeupdate").pipe((0,D.map)(M=>a.duration-a.currentTime<w),(0,D.filterChanged)(),(0,D.shareReplay)(1)),H=(0,D.merge)(O.pipe((0,D.filter)(M=>!a.loop&&M)),(0,D.fromEvent)(a,"ended")).pipe((0,D.throttle)(A),(0,D.mapTo)(void 0),(0,D.shareReplay)(1)),U=(0,D.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(M=>(0,D.fromEvent)(a,M)),O.pipe((0,D.map)(M=>({type:M?"ended":"unknown"})))).pipe((0,D.map)(M=>X.browser.isFirefox&&M.type==="ended"?a.readyState<2:a.readyState<3),(0,D.filterChanged)(),(0,D.shareReplay)(1));return{playing$:s,pause$:h,canplay$:e("canplay"),ended$:H,looped$:c,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,D.fromEvent)(a,"durationchange").pipe((0,D.map)(()=>a.duration),(0,D.shareReplay)(1)),isBuffering$:U,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:S,inFullscreen$:T,enterPip$:b,leavePip$:v,destroy:i}};var Gt=require("@vkontakte/videoplayer-shared/es2015"),hi=a=>{switch(a){case"mobile":return Gt.VideoQuality.Q_144P;case"lowest":return Gt.VideoQuality.Q_240P;case"low":return Gt.VideoQuality.Q_360P;case"sd":case"medium":return Gt.VideoQuality.Q_480P;case"hd":case"high":return Gt.VideoQuality.Q_720P;case"fullhd":case"full":return Gt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Gt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Gt.VideoQuality.Q_2160P}};var Qe=J(xt(),1),Ml=J(dt(),1),Fi=J(lr(),1),V=require("@vkontakte/videoplayer-shared/es2015");var Ll=!1,Wt={},Rg=a=>{Ll=a},kg=()=>{Wt={}},Lg=a=>{a(Wt)},va=(a,e)=>{var t;Ll&&(Wt.meta=(t=Wt.meta)!=null?t:{},Wt.meta[a]=e)},He=class{constructor(e){this.name=e}next(e){var i,r;if(!Ll)return;Wt.series=(i=Wt.series)!=null?i:{};let t=(r=Wt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Wt.series[this.name]=t}};var $e=require("@vkontakte/videoplayer-shared/es2015");function $l(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&&$l(a,e,t)==="high_quality"}function Ir(a,e,t){return(0,$e.isNullable)(a)||(0,$e.isNonNullable)(a.min)&&(0,$e.isNonNullable)(a.max)&&(0,$e.isLower)(a.max,a.min)||(0,$e.isNonNullable)(a.min)&&e&&(0,$e.isHigher)(a.min,e)||(0,$e.isNonNullable)(a.max)&&t&&(0,$e.isLower)(a.max,t)}function $g({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Ir({max:a!=null&&a.max?(0,$e.videoHeightToQuality)(a.max):void 0,min:a!=null&&a.min?(0,$e.videoHeightToQuality)(a.min):void 0},e?(0,$e.videoHeightToQuality)(e):void 0,t?(0,$e.videoHeightToQuality)(t):void 0)}var Vg=new He("best_bitrate"),An=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Er=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),fi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,V.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Pn='Assertion "ABR Tracks is empty array" failed',wn=new WeakMap,Mg=new WeakMap,Dg=new WeakMap,ya=(a,e,t,i)=>{var o;let r=[...e].sort(Er(1)),s=[...t].sort(Er(1)),n=s.filter(l=>(0,V.isNonNullable)(l.bitrate)&&(0,V.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>i:!0),u=(o=(0,Qe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?o:(0,Qe.default)(s,-1);return u&&(0,Ml.default)(n,u)?u:n.length?(0,Qe.default)(n,-1):(0,Qe.default)(s,0)},Ta=(a,e,t,i)=>{var o;let r=wn.get(e);r||(r=[...e].sort(Er(1)),wn.set(e,r));let s=wn.get(t);s||(s=[...t].sort(Er(1)),wn.set(t,s));let n=Dg.get(a);n||(n=s.filter(l=>(0,V.isNonNullable)(l.bitrate)&&(0,V.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>i:!0),Dg.set(a,n));let u=(o=(0,Qe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?o:(0,Qe.default)(s,-1);return u&&(0,Ml.default)(n,u)?u:n.length?(0,Qe.default)(n,-1):(0,Qe.default)(s,0)},Cg=a=>"quality"in a,Rn=(a,e,t,i)=>{var n;let r=(0,V.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,V.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,V.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let u=i.last;i==null||i.recordSwitch(u);let o=Cg(u)?"video":"audio",l=Cg(u)?u.quality:u.bitrate;return e({message:`
8
+ [last ${o} selected] ${l}
9
+ `}),u}return i==null||i.recordSwitch(t),t},JR=(a,e)=>Math.log(e)/Math.log(a),_g=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&X.display.pixelRatio){let s=X.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[u=0,o=0,l=0]=a.pixelRatioLogCoefficients,d=JR(n,u*s+o)+l;Number.isFinite(d)&&(r*=d)}}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}},Bg=new WeakMap,Bt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:b})=>{var Y,le,he,F,$;(0,V.assertNotEmptyArray)(a,Pn);let{containerSizeFactor:v,containerSizeLimit:S}=_g({container:e,tuning:i,limits:r,panelSize:b}),T=i.considerPlaybackRate&&(0,V.isNonNullable)(u)?u:1,E=Bg.get(a);E||(E=a.filter(P=>!(0,V.isInvariantQuality)(P.quality)).sort((P,B)=>(0,V.isHigher)(P.quality,B.quality)?-1:1),Bg.set(a,E));let w=(Y=(0,Qe.default)(E,-1))==null?void 0:Y.quality,A=(le=(0,Qe.default)(E,0))==null?void 0:le.quality,O=Ir(r,A,w),H=T*An(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),_={},U=null;for(let P of E){let B=!0;if(S)if(P.size)B=P.size.width<=S.width&&P.size.height<=S.height;else{let tt=S&&(0,V.videoSizeToQuality)(S);B=tt?(0,V.isLowerOrEqual)(P.quality,tt):!0}if(!B){_[P.quality]="FitsContainer";continue}let N=p||t,we=(0,V.isNonNullable)(N)&&isFinite(N)&&(0,V.isNonNullable)(P.bitrate)?N-s>=P.bitrate*H:!0,et=xn(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===P.quality;if(!we&&!et){_[P.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&(0,V.isNonNullable)(i.minBufferToSwitchUp)&&o&&!(0,V.isInvariantQuality)(o.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,V.isHigher)(P.quality,o.quality)){_[P.quality]="Buffer";continue}if(!!c&&(0,V.isHigherOrEqual)(P.quality,c)&&!et){_[P.quality]="DroppedFramesLimit";continue}if(!!f&&(0,V.isHigherOrEqual)(P.quality,f)&&!et){_[P.quality]="StallsLimit";continue}let _e=O||((0,V.isNullable)(r==null?void 0:r.max)||(0,V.isLowerOrEqual)(P.quality,r.max))&&((0,V.isNullable)(r==null?void 0:r.min)||(0,V.isHigherOrEqual)(P.quality,r.min)),Oe=(0,V.isNonNullable)(d)&&!d?(0,V.isLowerOrEqual)(P.quality,i.backgroundVideoQualityLimit):!0;if(!_e||!Oe){_[P.quality]="FitsQualityLimits";continue}U||(U=P)}U&&U.bitrate&&Vg.next(U.bitrate);let M=(he=U!=null?U:(0,Qe.default)(E,-1))!=null?he:a[0],G=l==null?void 0:l.last,q=Rn(i,h,M,l);return(0,V.isNonNullable)(l)&&q.quality!==(G==null?void 0:G.quality)&&h({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${s.map(V=>{var B,z;return`{ id: ${V.id}, quality: ${V.quality}, bitrate: ${V.bitrate}, size: ${(B=V.size)==null?void 0:B.width}:${(z=V.size)==null?void 0:z.height} }`}).join(`
12
+ ${a.map(P=>{var B,N;return`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate}, size: ${(B=P.size)==null?void 0:B.width}:${(N=P.size)==null?void 0:N.height} }`}).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,xr.default)(i!=null?i:{}).map(([V,B])=>`${V}: ${B}`).join(`
16
+ ${(0,Fi.default)(i!=null?i:{}).map(([P,B])=>`${P}: ${B}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
20
- containerSizeFactor: ${S},
21
- containerSizeLimit: ${($=v==null?void 0:v.width)!=null?$:0} x ${(_=v==null?void 0:v.height)!=null?_:0},
20
+ containerSizeFactor: ${v},
21
+ containerSizeLimit: ${(F=S==null?void 0:S.width)!=null?F:0} x ${($=S==null?void 0:S.height)!=null?$:0},
22
22
  estimatedThroughput: ${t},
23
23
  stallsPredictedThroughput: ${p},
24
- reserve: ${a},
25
- playbackRate: ${o},
26
- playbackRateFactor: ${y},
24
+ reserve: ${s},
25
+ playbackRate: ${u},
26
+ playbackRateFactor: ${T},
27
27
  forwardBufferHealth: ${n},
28
- bitrateFactor: ${j},
28
+ bitrateFactor: ${H},
29
29
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
30
30
  droppedVideoMaxQualityLimit: ${c},
31
31
  stallsVideoMaxQualityLimit: ${f},
32
- limitsAreInvalid: ${D},
32
+ limitsAreInvalid: ${O},
33
33
  maxQualityLimit: ${r==null?void 0:r.max},
34
34
  minQualityLimit: ${r==null?void 0:r.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,xr.default)(H).map(([V,B])=>`${V}: ${B}`).join(`
37
+ ${(0,Fi.default)(_).map(([P,B])=>`${P}: ${B}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
- [best video track] ${N==null?void 0:N.quality}
41
- [selected video track] ${O==null?void 0:O.quality}
42
- `}),O},iu=(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:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:b})=>{var G,de,$,_,V;(0,C.assertNotEmptyArray)(s,eu);let{containerSizeFactor:S,containerSizeLimit:v}=LS({container:e,tuning:i,limits:r,panelSize:b}),y=i.considerPlaybackRate&&(0,C.isNonNullable)(o)?o:1,x=s.filter(B=>!(0,C.isInvariantQuality)(B.quality)).sort((B,z)=>(0,C.isHigher)(B.quality,z.quality)?-1:1),E=(G=(0,mt.default)(x,-1))==null?void 0:G.quality,A=(de=(0,mt.default)(x,0))==null?void 0:de.quality,D=Jr(r,A,E),j=y*Zo(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),H={},L=x.filter(B=>{let z=!0;if(v)if(B.size)z=B.size.width<=v.width&&B.size.height<=v.height;else{let Ft=v&&(0,C.videoSizeToQuality)(v);z=Ft?(0,C.isLowerOrEqual)(B.quality,Ft):!0}if(!z)return H[B.quality]="FitsContainer",!1;let Ee=p||t,et=(0,C.isNonNullable)(Ee)&&isFinite(Ee)&&(0,C.isNonNullable)(B.bitrate)?Ee-a>=B.bitrate*j:!0,ve=Xo(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===B.quality;if(!et&&!ve)return H[B.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,C.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,C.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,C.isHigher)(B.quality,u.quality))return H[B.quality]="Buffer",!1;if(!!c&&(0,C.isHigherOrEqual)(B.quality,c)&&!ve)return H[B.quality]="DroppedFramesLimit",!1;if(!!f&&(0,C.isHigherOrEqual)(B.quality,f)&&!ve)return H[B.quality]="StallsLimit",!1;let Ue=D||((0,C.isNullable)(r==null?void 0:r.max)||(0,C.isLowerOrEqual)(B.quality,r.max))&&((0,C.isNullable)(r==null?void 0:r.min)||(0,C.isHigherOrEqual)(B.quality,r.min)),tt=(0,C.isNonNullable)(d)&&!d?(0,C.isLowerOrEqual)(B.quality,i.backgroundVideoQualityLimit):!0;return!Ue||!tt?(H[B.quality]="FitsQualityLimits",!1):!0})[0];L&&L.bitrate&&MS.next(L.bitrate);let Q=($=L!=null?L:(0,mt.default)(x,-1))!=null?$:s[0],O=l==null?void 0:l.last,J=tu(i,h,Q,l);return(0,C.isNonNullable)(l)&&J.quality!==(O==null?void 0:O.quality)&&h({message:`
40
+ [best video track] ${U==null?void 0:U.quality}
41
+ [selected video track] ${q==null?void 0:q.quality}
42
+ `}),q},kn=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:b})=>{var le,he,F,$,P;(0,V.assertNotEmptyArray)(a,Pn);let{containerSizeFactor:v,containerSizeLimit:S}=_g({container:e,tuning:i,limits:r,panelSize:b}),T=i.considerPlaybackRate&&(0,V.isNonNullable)(u)?u:1,E=a.filter(B=>!(0,V.isInvariantQuality)(B.quality)).sort((B,N)=>(0,V.isHigher)(B.quality,N.quality)?-1:1),w=(le=(0,Qe.default)(E,-1))==null?void 0:le.quality,A=(he=(0,Qe.default)(E,0))==null?void 0:he.quality,O=Ir(r,A,w),H=T*An(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),_={},M=E.filter(B=>{let N=!0;if(S)if(B.size)N=B.size.width<=S.width&&B.size.height<=S.height;else{let Ut=S&&(0,V.videoSizeToQuality)(S);N=Ut?(0,V.isLowerOrEqual)(B.quality,Ut):!0}if(!N)return _[B.quality]="FitsContainer",!1;let we=p||t,et=(0,V.isNonNullable)(we)&&isFinite(we)&&(0,V.isNonNullable)(B.bitrate)?we-s>=B.bitrate*H:!0,ve=xn(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===B.quality;if(!et&&!ve)return _[B.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,V.isNonNullable)(i.minBufferToSwitchUp)&&o&&!(0,V.isInvariantQuality)(o.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,V.isHigher)(B.quality,o.quality))return _[B.quality]="Buffer",!1;if(!!c&&(0,V.isHigherOrEqual)(B.quality,c)&&!ve)return _[B.quality]="DroppedFramesLimit",!1;if(!!f&&(0,V.isHigherOrEqual)(B.quality,f)&&!ve)return _[B.quality]="StallsLimit",!1;let Oe=O||((0,V.isNullable)(r==null?void 0:r.max)||(0,V.isLowerOrEqual)(B.quality,r.max))&&((0,V.isNullable)(r==null?void 0:r.min)||(0,V.isHigherOrEqual)(B.quality,r.min)),tt=(0,V.isNonNullable)(d)&&!d?(0,V.isLowerOrEqual)(B.quality,i.backgroundVideoQualityLimit):!0;return!Oe||!tt?(_[B.quality]="FitsQualityLimits",!1):!0})[0];M&&M.bitrate&&Vg.next(M.bitrate);let G=(F=M!=null?M:(0,Qe.default)(E,-1))!=null?F:a[0],q=l==null?void 0:l.last,Y=Rn(i,h,G,l);return(0,V.isNonNullable)(l)&&Y.quality!==(q==null?void 0:q.quality)&&h({message:`
43
43
  [VIDEO TRACKS ABR]
44
44
  [available video tracks]
45
- ${s.map(B=>{var z,Ee;return`{ id: ${B.id}, quality: ${B.quality}, bitrate: ${B.bitrate}, size: ${(z=B.size)==null?void 0:z.width}:${(Ee=B.size)==null?void 0:Ee.height} }`}).join(`
45
+ ${a.map(B=>{var N,we;return`{ id: ${B.id}, quality: ${B.quality}, bitrate: ${B.bitrate}, size: ${(N=B.size)==null?void 0:N.width}:${(we=B.size)==null?void 0:we.height} }`}).join(`
46
46
  `)}
47
47
 
48
48
  [tuning]
49
- ${(0,xr.default)(i!=null?i:{}).map(([B,z])=>`${B}: ${z}`).join(`
49
+ ${(0,Fi.default)(i!=null?i:{}).map(([B,N])=>`${B}: ${N}`).join(`
50
50
  `)}
51
51
 
52
52
  [limit params]
53
- containerSizeFactor: ${S},
54
- containerSizeLimit: ${(_=v==null?void 0:v.width)!=null?_:0} x ${(V=v==null?void 0:v.height)!=null?V:0},
53
+ containerSizeFactor: ${v},
54
+ containerSizeLimit: ${($=S==null?void 0:S.width)!=null?$:0} x ${(P=S==null?void 0:S.height)!=null?P:0},
55
55
  estimatedThroughput: ${t},
56
56
  stallsPredictedThroughput: ${p},
57
- reserve: ${a},
58
- playbackRate: ${o},
59
- playbackRateFactor: ${y},
57
+ reserve: ${s},
58
+ playbackRate: ${u},
59
+ playbackRateFactor: ${T},
60
60
  forwardBufferHealth: ${n},
61
- bitrateFactor: ${j},
61
+ bitrateFactor: ${H},
62
62
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
63
63
  droppedVideoMaxQualityLimit: ${c},
64
64
  stallsVideoMaxQualityLimit: ${f},
65
- limitsAreInvalid: ${D},
65
+ limitsAreInvalid: ${O},
66
66
  maxQualityLimit: ${r==null?void 0:r.max},
67
67
  minQualityLimit: ${r==null?void 0:r.min},
68
68
 
69
69
  [limited video tracks]
70
- ${(0,xr.default)(H).map(([B,z])=>`${B}: ${z}`).join(`
70
+ ${(0,Fi.default)(_).map(([B,N])=>`${B}: ${N}`).join(`
71
71
  `)||"All tracks are available"}
72
72
 
73
- [best video track] ${L==null?void 0:L.quality}
74
- [selected video track] ${J==null?void 0:J.quality}
75
- `}),J},ru=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{(0,C.assertNotEmptyArray)(t,eu);let d=r.considerPlaybackRate&&(0,C.isNonNullable)(a)?a:1,c=[...t].sort(Zr(-1)),f=s.bitrate;(0,C.assertNonNullable)(f);let p=d*Zo(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,b=ka(s,e,t,r.minVideoAudioRatio),S=l||i;(0,C.isNonNullable)(S)&&isFinite(S)&&(h=c.find(x=>(0,C.isNonNullable)(x.bitrate)&&(0,C.isNonNullable)(b==null?void 0:b.bitrate)?S-f>=x.bitrate*p&&x.bitrate>=b.bitrate:!1)),h||(h=b);let v=o==null?void 0:o.last,y=h&&tu(r,u,h,o);return(0,C.isNonNullable)(o)&&(y==null?void 0:y.bitrate)!==(v==null?void 0:v.bitrate)&&u({message:`
73
+ [best video track] ${M==null?void 0:M.quality}
74
+ [selected video track] ${Y==null?void 0:Y.quality}
75
+ `}),Y},Ln=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{(0,V.assertNotEmptyArray)(t,Pn);let d=r.considerPlaybackRate&&(0,V.isNonNullable)(s)?s:1,c=[...t].sort(Er(-1)),f=a.bitrate;(0,V.assertNonNullable)(f);let p=d*An(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,b=ya(a,e,t,r.minVideoAudioRatio),v=l||i;(0,V.isNonNullable)(v)&&isFinite(v)&&(h=c.find(E=>(0,V.isNonNullable)(E.bitrate)&&(0,V.isNonNullable)(b==null?void 0:b.bitrate)?v-f>=E.bitrate*p&&E.bitrate>=b.bitrate:!1)),h||(h=b);let S=u==null?void 0:u.last,T=h&&Rn(r,o,h,u);return(0,V.isNonNullable)(u)&&(T==null?void 0:T.bitrate)!==(S==null?void 0:S.bitrate)&&o({message:`
76
76
  [AUDIO TRACKS ABR]
77
77
  [available audio tracks]
78
- ${t.map(x=>`{ id: ${x.id}, bitrate: ${x.bitrate} }`).join(`
78
+ ${t.map(E=>`{ id: ${E.id}, bitrate: ${E.bitrate} }`).join(`
79
79
  `)}
80
80
 
81
81
  [tuning]
82
- ${(0,xr.default)(r!=null?r:{}).map(([x,E])=>`${x}: ${E}`).join(`
82
+ ${(0,Fi.default)(r!=null?r:{}).map(([E,w])=>`${E}: ${w}`).join(`
83
83
  `)}
84
84
 
85
85
  [limit params]
86
86
  estimatedThroughput: ${i},
87
87
  stallsPredictedThroughput: ${l},
88
88
  reserve: ${f},
89
- playbackRate: ${a},
89
+ playbackRate: ${s},
90
90
  playbackRateFactor: ${d},
91
91
  forwardBufferHealth: ${n},
92
92
  bitrateFactor: ${p},
93
93
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
94
94
 
95
- [selected audio track] ${y==null?void 0:y.id}
96
- `}),y},su=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{(0,C.assertNotEmptyArray)(t,eu);let d=r.considerPlaybackRate&&(0,C.isNonNullable)(a)?a:1,c=AS.get(t);c||(c=[...t].sort(Zr(-1)),AS.set(t,c));let f=s.bitrate;(0,C.assertNonNullable)(f);let p=d*Zo(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,b=Ra(s,e,t,r.minVideoAudioRatio),S=l||i;(0,C.isNonNullable)(S)&&isFinite(S)&&(h=c.find(x=>(0,C.isNonNullable)(x.bitrate)&&(0,C.isNonNullable)(b==null?void 0:b.bitrate)?S-f>=x.bitrate*p&&x.bitrate>=b.bitrate:!1)),h||(h=b);let v=o==null?void 0:o.last,y=h&&tu(r,u,h,o);return(0,C.isNonNullable)(o)&&(y==null?void 0:y.bitrate)!==(v==null?void 0:v.bitrate)&&u({message:`
95
+ [selected audio track] ${T==null?void 0:T.id}
96
+ `}),T},$n=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{(0,V.assertNotEmptyArray)(t,Pn);let d=r.considerPlaybackRate&&(0,V.isNonNullable)(s)?s:1,c=Mg.get(t);c||(c=[...t].sort(Er(-1)),Mg.set(t,c));let f=a.bitrate;(0,V.assertNonNullable)(f);let p=d*An(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,b=Ta(a,e,t,r.minVideoAudioRatio),v=l||i;(0,V.isNonNullable)(v)&&isFinite(v)&&(h=c.find(E=>(0,V.isNonNullable)(E.bitrate)&&(0,V.isNonNullable)(b==null?void 0:b.bitrate)?v-f>=E.bitrate*p&&E.bitrate>=b.bitrate:!1)),h||(h=b);let S=u==null?void 0:u.last,T=h&&Rn(r,o,h,u);return(0,V.isNonNullable)(u)&&(T==null?void 0:T.bitrate)!==(S==null?void 0:S.bitrate)&&o({message:`
97
97
  [AUDIO TRACKS ABR]
98
98
  [available audio tracks]
99
- ${t.map(x=>`{ id: ${x.id}, bitrate: ${x.bitrate} }`).join(`
99
+ ${t.map(E=>`{ id: ${E.id}, bitrate: ${E.bitrate} }`).join(`
100
100
  `)}
101
101
 
102
102
  [tuning]
103
- ${(0,xr.default)(r!=null?r:{}).map(([x,E])=>`${x}: ${E}`).join(`
103
+ ${(0,Fi.default)(r!=null?r:{}).map(([E,w])=>`${E}: ${w}`).join(`
104
104
  `)}
105
105
 
106
106
  [limit params]
107
107
  estimatedThroughput: ${i},
108
108
  stallsPredictedThroughput: ${l},
109
109
  reserve: ${f},
110
- playbackRate: ${a},
110
+ playbackRate: ${s},
111
111
  playbackRateFactor: ${d},
112
112
  forwardBufferHealth: ${n},
113
113
  bitrateFactor: ${p},
114
114
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
115
115
 
116
- [selected audio track] ${y==null?void 0:y.id}
117
- `}),y};var st=s=>new URL(s).hostname;var ee=require("@vkontakte/videoplayer-shared/es2015");var OS=Z(ii(),1);var $S=Z(Dt(),1);var BS=s=>{if(s instanceof DOMException&&(0,$S.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"))},It=(s,e)=>k(void 0,null,function*(){let t=s.muted;try{yield s.play()}catch(i){if(!BS(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{yield s.play()}catch(r){return BS(r)&&(s.muted=!1,console.warn(r)),!1}}return!0});var Ot=require("@vkontakte/videoplayer-shared/es2015");var DS=Z(Tr(),1),pi=require("@vkontakte/videoplayer-shared/es2015");function Je(){return(0,pi.now)()}function id(s){return Je()-s}function rd(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 CS(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function es(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,d,c,f=!1,p="arraybuffer",h=7e3,b=2e3,S=()=>{if(u)return;(0,pi.assertNonNullable)(d);let O=id(d),J;if(O<b){J=b-O,setTimeout(S,J);return}b*=2,b>h&&(b=h),n&&n.abort(),n=new r,D()},v=O=>(a=O,Q),y=O=>(c=O,Q),x=()=>(p="json",Q),E=()=>{if(!u){if(--l>=0){S(),i&&i();return}u=!0,c&&c(),t&&t()}},A=O=>(f=O,Q),D=()=>{d=Je(),n=new r,n.open("get",s);let O=0,J,G=0,de=()=>((0,pi.assertNonNullable)(d),Math.max(d,Math.max(J||0,G||0)));if(a&&n.addEventListener("progress",$=>{let _=Je();a.updateChunk&&$.loaded>O&&(a.updateChunk(de(),$.loaded-O),O=$.loaded,J=_)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;(0,pi.assertNonNullable)(n);let $=n.status;if($>=200&&$<300){let{response:_,responseType:V}=n,B=_==null?void 0:_.byteLength;if(typeof B=="number"&&a){let z=B-O;z&&a.updateChunk&&a.updateChunk(de(),z)}V==="json"&&(!_||!(0,DS.default)(_).length)?E():(c&&c(),e(_))}else E()}),n.addEventListener("error",()=>{E()}),f){let $=()=>{(0,pi.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(G=Je(),n.removeEventListener("readystatechange",$))};n.addEventListener("readystatechange",$)}return n.responseType=p,n.send(),Q},Q={withBitrateReporting:v,withParallel:A,withJSONResponse:x,withRetryCount:O=>(l=O,Q),withRetryInterval:(O,J)=>((0,pi.isNonNullable)(O)&&(b=O),(0,pi.isNonNullable)(J)&&(h=J),Q),withTimeout:O=>(o=O,Q),withFinally:y,send:D,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return Q}var Ma=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 VS=Z(Tr(),1);var La=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=Je(),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=Je()-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=es(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=Je()}_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=Je();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,VS.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var _S=require("@vkontakte/videoplayer-shared/es2015");var au=1e4,sd=3;var QR=6e4,GR=10,WR=1,YR=500,Ba=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 _S.Subject,this.chunkRateEstimator=new Ma(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=rd(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=rd(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r,a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(a=e.error)==null?void 0:a.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*(te.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||{};!wS({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,OS.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Ot.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{CS(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 La(sd,au,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},f=(E,A,D)=>{u&&u.abort(),u=es(this.urlResolver.resolve(E,!1),A,D,()=>this._retryCallback()).withTimeout(au).withBitrateReporting(this.bitrateSwitcher).withRetryCount(sd).withFinally(()=>{u=null}).send()},p=(E,A,D)=>{(0,Ot.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),A,D,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=E=>{let A=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${A}=>${E}`),i.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let D=Je()-1e4,j=0;for(let N=0;N<this.bufferStates.length;N++){let L=this.bufferStates[N];E=Math.min(E,L.buf),L.ts<D&&j++}this.bufferStates.splice(0,j),t(`update playback rate; minBuffer=${E} drop=${j} jitter=${this.sourceJitter}`);let H=E-WR;this.sourceJitter>=0?H-=this.sourceJitter/2:this.sourceJitter-=1,H>3?h(1.15):H>1?h(1.1):H>.3?h(1.05):h(1)}},v=E=>{let A,D=()=>A&&A.start?A.start.length:0,j=$=>A.start[$]/1e3,H=$=>A.dur[$]/1e3,N=$=>A.fragIndex+$,L=($,_)=>({chunkIdx:N($),startTS:j($),dur:H($),discontinuity:_}),Q=()=>{let $=0;if(A&&A.dur){let _=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,V=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,B=_;this.sourceJitter>1&&(B+=this.sourceJitter-1);let z=A.dur.length-1;for(;z>=0&&(B-=A.dur[z],!(B<=0));--z);$=Math.min(z,A.dur.length-1-V),$=Math.max($,0)}return L($,!0)},O=$=>{let _=D();if(!(_<=0)){if((0,Ot.isNonNullable)($)){for(let V=0;V<_;V++)if(j(V)>$)return L(V)}return Q()}},J=$=>{let _=D(),V=$?$.chunkIdx+1:0,B=V-A.fragIndex;if(!(_<=0)){if(!$||B<0||B-_>GR)return t(`Resync: offset=${B} bChunks=${_} chunk=`+JSON.stringify($)),Q();if(!(B>=_))return L(V-A.fragIndex,!1)}},G=($,_,V)=>{l&&l.abort(),l=es(this.urlResolver.resolve($,!0,this.lowLatency),_,V,()=>this._retryCallback()).withTimeout(au).withRetryCount(sd).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:($,_)=>{G(E,V=>{if(!c())return;A=V;let B=!!A.lowLatency;B!==this.lowLatency&&b(B);let z=0;for(let Ee=0;Ee<A.dur.length;++Ee)z+=A.dur[Ee];z>0&&((0,Ot.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(z/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,$(O(_))},()=>this._handleNetworkError())},nextChunk:J}},y=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ot.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:E=>{let{videoElement:A,logger:D}=this.params,j=v(e.jidxUrl),H,N,L,Q,O=0,J,G,de,$=()=>{J&&(clearTimeout(J),J=void 0);let fe=Math.max(YR,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Fe=O+fe,Ne=Je(),Ue=Math.min(1e4,Fe-Ne);O=Ne;let tt=()=>{l||c()&&j.seek(()=>{c()&&(O=Je(),_(),$())})};Ue>0?J=window.setTimeout(()=>{this.paused?$():tt()},Ue):tt()},_=()=>{let fe;for(;fe=j.nextChunk(Q);)Q=fe,et(fe);let Fe=j.nextChunk(L);if(Fe){if(L&&Fe.discontinuity){D("Detected discontinuity; restarting playback"),this.paused?$():(y(),this._initPlayerWith(e));return}Ee(Fe)}else $()},V=(fe,Fe)=>{if(!c()||!this.sourceBuffer)return;let Ne,Ue,tt,Ft=zt=>{window.setTimeout(()=>{c()&&V(fe,Fe)},zt)};if(this.sourceBuffer.updating)D("Source buffer is updating; delaying appendBuffer"),Ft(100);else{let zt=Je(),ai=A.currentTime;!this.paused&&A.buffered.length>1&&G===ai&&zt-de>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),G!==ai&&(G=ai,de=zt);let mi=this._getBufferSizeSec();if(mi>30)D(`Buffered ${mi} seconds; delaying appendBuffer`),Ft(2e3);else try{this.sourceBuffer.appendBuffer(fe),this.videoPlayStarted?(this.bufferStates.push({ts:zt,buf:mi}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Fe&&Fe()}catch(zi){if(zi.name==="QuotaExceededError")D("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(Ne=this.sourceBuffer.buffered.start(0),Ue=ai,Ue-Ne>4&&this.sourceBuffer.remove(Ne,Ue-3)),Ft(1e3);else throw zi}}},B=()=>{N&&H&&(D([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(L)]),V(N,function(){N=null,_()}))},z=fe=>e.fragUrlTemplate.replace("%%id%%",fe.chunkIdx),Ee=fe=>{c()&&p(z(fe),(Fe,Ne)=>{if(c()){if(Ne/=1e3,N=Fe,L=fe,n=fe.startTS,Ne){let Ue=Math.min(10,fe.dur/Ne);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ue:Ue}B()}},()=>this._handleNetworkError())},et=fe=>{c()&&((0,Ot.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(z(fe),!1)))},ve=fe=>{c()&&(e.cachedHeader=fe,V(fe,()=>{H=!0,B()}))};a=!0,j.seek(fe=>{if(c()){if(O=Je(),!fe){$();return}Q=fe,!(0,Ot.isNullable)(E)||fe.startTS>E?Ee(fe):(L=fe,_())}},E),e.cachedHeader?ve(e.cachedHeader):f(e.headerUrl,ve,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,Ot.isNonNullable)(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Ot.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ot.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let f,p,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),h=c/this.bitrate,p>10&&h>.8||p>15&&h>.5||p>20&&h>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}f=this._selectQuality(c),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(f,p)=>{let h=Je();if(this.chunkRateEstimator.addInterval(f,h,p)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:h-f,speed:S}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&id(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,f)=>{let p=a.updateChunk(c,f);return p&&l(),p},notifySwitch:c=>{let f=Je();c<o&&(n=f),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=es(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(au).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;It(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var d,c;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((c=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&c.call(d,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},QR))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var FS=Z(mr(),1),$e=require("@vkontakte/videoplayer-shared/es2015"),ad=class{constructor(){this.onDroopedVideoFramesLimit$=new $e.Subject;this.subscription=new $e.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new $e.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,$e.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&(0,$e.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,$e.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,$e.interval)(this.droppedFramesChecker.checkTime).pipe((0,$e.filter)(()=>this.playing),(0,$e.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,$e.debounce)(this.droppedFramesChecker.checkTime)),i=(0,$e.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,FS.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>(0,$e.isLower)(a,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ts=ad;var nu=require("@vkontakte/videoplayer-shared/es2015"),NS=require("@vkontakte/videoplayer-shared/es2015");var $a=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var KR=(s,e)=>new nu.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||$a()))},P(P({},i),e));r.observe(s);let a=(0,NS.fromEvent)(document,"visibilitychange").pipe((0,nu.map)(n=>!document.hidden||$a())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),qt=KR;var XR=["paused","playing","ready"],JR=["paused","playing","ready"],Da=class{constructor(e){this.subscription=new ee.Subscription;this.videoState=new ce("stopped");this.representations$=new ee.ValueSubject([]);this.droppedFramesManager=new ts;this.maxSeekBackTime$=new ee.ValueSubject(1/0);this.zeroTime$=new ee.ValueSubject(void 0);this.liveOffset=new Ir;this._dashCb=e=>{var t,i,r,a;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:ee.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),d=(i=Xi(u.name))!=null?i:(0,ee.videoSizeToQuality)(u.video),c=u.bitrate/1e3,f=P({},u.video);if(!d)continue;let p={id:l,quality:d,bitrate:c,size:f};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(a=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:a.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,ee.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,nd.default)(JR,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,nd.default)(XR,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Oe(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Oe(this.params.source.url,u))}return;default:return(0,ee.assertNever)(e)}};this.textTracksManager=new Ut(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:ee.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,ee.merge)(this.videoState.stateChangeStarted$.pipe((0,ee.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ee.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=St(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(st(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=Tt(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,ee.map)(r=>r.map(({track:a})=>a)),(0,ee.filter)(r=>!!r.length),(0,ee.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,ee.filterChanged)(),(0,ee.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,ee.combine)({zeroTime:this.zeroTime$.pipe((0,ee.filter)(ee.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(ci(this.video,this.params.desiredState.isLooped,t)).add(yt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Nt(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(qt(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&(0,ee.videoQualityToHeight)(r),min:a&&(0,ee.videoQualityToHeight)(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,ee.assertNever)(r.to)}},t)).add((0,ee.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,ee.observableFrom)(["init"])).pipe((0,ee.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),vt(this.video)}createLiveDashPlayer(){let e=new Ba({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(){var l,d,c,f,p,h;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(f=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?f:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,ee.isNonNullable)(t)?t:di(e.map(({track:b})=>b),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let b=(h=e.find(({track:S})=>S.id===a))==null?void 0:h.representation;(0,ee.assertNonNullable)(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;(0,ee.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Oe(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var US=Da;var qy=Z(Dt(),1);var Ze=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var re=require("@vkontakte/videoplayer-shared/es2015");var ou=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}},is=class extends ou{constructor(){super(),this.listeners||ou.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)}},Ca=class{constructor(){Object.defineProperty(this,"signal",{value:new is,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ca.prototype[Symbol.toStringTag]="AbortController",is.prototype[Symbol.toStringTag]="AbortSignal");function uu(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 od(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!uu({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 f=new t(l,d);return c&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),f},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(p){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let f=new Promise((p,h)=>{d.addEventListener("abort",()=>h(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,n(u,l)])}return n(u,l)},Request:a}}var ZR=()=>"fetch"in window,Va=ZR()&&uu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),qS=Va?od({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,jt=Va?qS.fetch:window.fetch,l_=Va?qS.Request:window.Request,ye=Va?Ca:window.AbortController,c_=Va?is:window.AbortSignal;var Dd=Z(Oa(),1);var kv=Z(Pv(),1),rs=require("@vkontakte/videoplayer-shared/es2015"),lu=s=>{if(!s)return{id:"EmptyResponse",category:rs.ErrorCategory.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:rs.ErrorCategory.NETWORK,message:`UV Error ${s}`};let e=(0,kv.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:rs.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:rs.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:rs.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var at=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};var I=require("@vkontakte/videoplayer-shared/es2015");var du=Z(Dt(),1),ls=Z(ii(),1),pu=Z(Oa(),1);var _M=(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)},FM=s=>window.clearTimeout(s),Rv=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),Mv=!Rv(window.requestIdleCallback)||!Rv(window.cancelIdleCallback),ss=Mv?_M:window.requestIdleCallback,hi=Mv?FM:window.cancelIdleCallback;var By=Z(qo(),1);var Zi=require("@vkontakte/videoplayer-shared/es2015");var NM=18,Lv=!1;try{Lv=te.browser.isSafari&&!!te.browser.safariVersion&&te.browser.safariVersion<=NM}catch(s){console.error(s)}var hd=class{constructor(e){this.bufferFull$=new Zi.Subject;this.error$=new Zi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Zi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return k(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return k(this,null,function*(){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()})})}abort(e){return k(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};Lv&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Zi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Zi.assertNever)(t)}}},Bv=hd;var as=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};var R=require("@vkontakte/videoplayer-shared/es2015");var me=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 ns=class extends me{};var Fa=class extends me{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 Na=class extends me{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 Ua=class extends me{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var we=class extends me{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var qa=class extends we{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 ja=class extends me{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ha=class extends me{constructor(e,t){super(e,t),this.data=this.content}};var Er=class extends we{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 za=class extends me{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Qa=class extends me{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ga=class extends we{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 Wa=class extends we{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Ya=class extends we{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Ka=class extends me{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xa=class extends we{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 Ja=class extends me{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Za=class extends me{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var en=class extends we{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var tn=class extends me{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rn=class extends we{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 sn=class extends we{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 an=class extends we{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 nn=class extends me{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var on=class extends we{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 un=class extends me{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var qM={ftyp:Na,moov:Ua,mvhd:qa,moof:ja,mdat:Ha,sidx:Er,trak:za,mdia:Ka,mfhd:en,tkhd:Xa,traf:tn,tfhd:rn,tfdt:sn,trun:an,minf:Ja,sv3d:Qa,st3d:Ga,prhd:Wa,proj:Za,equi:Ya,uuid:Fa,stbl:nn,stsd:on,avc1:un,unknown:ns},Di=class s{constructor(e={}){this.options=P({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=qM[e];return i?new i(t,new s):new ns(t,new s)}};var er=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var HM=new TextDecoder("ascii"),zM=s=>HM.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",QM=s=>{let e=new Er(s,new Di),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})},GM=(s,e)=>{let i=new Di().parse(s),r=new er(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)},WM=s=>{let t=new Di().parse(s),i=new er(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},YM=s=>{var r;let t=new Di().parse(s);return(r=new er(t).find("sidx"))==null?void 0:r.timescale},KM=(s,e)=>{let i=new Di().parse(s),a=new er(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,f)=>c+f,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},XM=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 Di().parse(s),r=new er(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},$v={validateData:zM,parseInit:XM,getIndexRange:()=>{},parseSegments:QM,parseFeedableSegmentChunk:GM,getChunkEndTime:KM,getServerLatencyTimestamps:WM,getTimescaleFromIndex:YM};var cn=Z(Dt(),1),Ci=require("@vkontakte/videoplayer-shared/es2015");var Cv=require("@vkontakte/videoplayer-shared/es2015");var Dv={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"}},Vv=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=ln(s,t),r=i in Dv,a=r?Dv[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=ln(u),c=l*pt(2,(o-1)*8)+d,f=t+o,p;return f+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:f,tagSize:f+c,value:p,valueSize:c}},ln=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*pt(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*pt(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*pt(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},ri=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return ln(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,Cv.assertNever)(e)}},wr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Vv(i);if(!e(r))return;r.type==="master"&&wr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Ov=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Vv(s);return wr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=ri(o,n):a===17026?t=ri(o,n):a===17029&&(i=ri(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var _v=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],JM=[231,22612,22743,167,171,163,160,175],ZM=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return wr(s,({tag:f,type:p,value:h,valueSize:b})=>{if(f===21419){let S=ri(h,p);l=ln(S)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+b):f===357149030?a=!0:f===290298740?n=!0:f===2807729?i=ri(h,p):f===17545?r=ri(h,p):f===21420&&l===475249515?u=ri(h,p):f===374648427?wr(h,({tag:S,type:v,value:y})=>S===30321?(d=ri(y,v)===1,!1):!0):a&&n&&(0,cn.default)(_v,f)&&(o=!0),!o}),(0,Ci.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Ci.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Ci.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},eL=s=>{if((0,Ci.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},tL=(s,e)=>{let t=!1,i=!1,r=o=>(0,Ci.isNonNullable)(o.time)&&(0,Ci.isNonNullable)(o.position),a=[],n;return wr(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=ri(l,u));break;case 183:break;case 241:n&&(n.position=ri(l,u));break;default:t&&(0,cn.default)(_v,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}}})},iL=s=>{let e=0,t=!1;try{wr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,cn.default)(JM,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,cn.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Fv={validateData:Ov,parseInit:ZM,getIndexRange:eL,parseSegments:tL,parseFeedableSegmentChunk:iL};var dn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Fv;case"mp4":return $v}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Pd=Z(yd(),1),ky=Z(mr(),1),Ry=Z(Td(),1),My=Z(ii(),1),kd=Z(Tr(),1);var yy=Z(Dt(),1),us=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,yy.default)(["6E","7A","F4"],o)}}return!1};var hn=require("@vkontakte/videoplayer-shared/es2015");var cu=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Ty=s=>{var e;try{let t=XL(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function XL(){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] ${T==null?void 0:T.id}
117
+ `}),T};var Ne=a=>new URL(a).hostname;var K=require("@vkontakte/videoplayer-shared/es2015");var jg=J(xt(),1);var Fg=J(dt(),1);var Og=a=>{if(a instanceof DOMException&&(0,Fg.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"))},Xe=(a,e)=>R(null,null,function*(){let t=a.muted;try{yield a.play()}catch(i){if(!Og(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{yield a.play()}catch(r){return Og(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});var nt=require("@vkontakte/videoplayer-shared/es2015");var Ng=J(Tr(),1),Vt=require("@vkontakte/videoplayer-shared/es2015");function Ce(){return(0,Vt.now)()}function Dl(a){return Ce()-a}function Cl(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 Ug(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function xr(a,e,t,i){let r=window.XMLHttpRequest,s,n,u,o=!1,l=0,d,c,f=!1,p="arraybuffer",h=7e3,b=2e3,v=()=>{if(o)return;(0,Vt.assertNonNullable)(d);let q=Dl(d),Y;if(q<b){Y=b-q,setTimeout(v,Y);return}b*=2,b>h&&(b=h),n&&n.abort(),n=new r,O()},S=q=>(s=q,G),T=q=>(c=q,G),E=()=>(p="json",G),w=()=>{if(!o){if(--l>=0){v(),i&&i();return}o=!0,c&&c(),t&&t()}},A=q=>(f=q,G),O=()=>{d=Ce(),n=new r,n.open("get",a);let q=0,Y,le=0,he=()=>((0,Vt.assertNonNullable)(d),Math.max(d,Math.max(Y||0,le||0)));if(s&&n.addEventListener("progress",F=>{let $=Ce();s.updateChunk&&F.loaded>q&&(s.updateChunk(he(),F.loaded-q),q=F.loaded,Y=$)}),u&&(n.timeout=u,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(o)return;(0,Vt.assertNonNullable)(n);let F=n.status;if(F>=200&&F<300){let{response:$,responseType:P}=n,B=$==null?void 0:$.byteLength;if(typeof B=="number"&&s){let N=B-q;N&&s.updateChunk&&s.updateChunk(he(),N)}P==="json"&&(!$||!(0,Ng.default)($).length)?w():(c&&c(),e($))}else w()}),n.addEventListener("error",()=>{w()}),f){let F=()=>{(0,Vt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(le=Ce(),n.removeEventListener("readystatechange",F))};n.addEventListener("readystatechange",F)}return n.responseType=p,n.send(),G},G={withBitrateReporting:S,withParallel:A,withJSONResponse:E,withRetryCount:q=>(l=q,G),withRetryInterval:(q,Y)=>((0,Vt.isNonNullable)(q)&&(b=q),(0,Vt.isNonNullable)(Y)&&(h=Y),G),withTimeout:q=>(u=q,G),withFinally:T,send:O,abort:()=>{n&&(n.abort(),n=void 0),o=!0,c&&c()}};return G}var Ia=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 qg=J(Tr(),1);var Ea=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=Ce(),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=Ce()-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=xr(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=Ce()}_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=Ce();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,qg.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}};var Hg=require("@vkontakte/videoplayer-shared/es2015");var Mn=1e4,Bl=3;var ek=6e4,tk=10,ik=1,rk=500,xa=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 Hg.Subject,this.chunkRateEstimator=new Ia(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Cl(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=Cl(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r,s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(s=e.error)==null?void 0:s.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*(X.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||{};!$g({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,jg.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||(0,nt.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Ug(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 Ea(Bl,Mn,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,d=!1,c=()=>{let w=s&&(!d||d===this.rep);return w||t("Not running!"),w},f=(w,A,O)=>{o&&o.abort(),o=xr(this.urlResolver.resolve(w,!1),A,O,()=>this._retryCallback()).withTimeout(Mn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Bl).withFinally(()=>{o=null}).send()},p=(w,A,O)=>{(0,nt.assertNonNullable)(this.filesFetcher),u==null||u.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),A,O,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},h=w=>{let A=i.playbackRate;i.playbackRate!==w&&(t(`Playback rate switch: ${A}=>${w}`),i.playbackRate=w)},b=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let O=Ce()-1e4,H=0;for(let U=0;U<this.bufferStates.length;U++){let M=this.bufferStates[U];w=Math.min(w,M.buf),M.ts<O&&H++}this.bufferStates.splice(0,H),t(`update playback rate; minBuffer=${w} drop=${H} jitter=${this.sourceJitter}`);let _=w-ik;this.sourceJitter>=0?_-=this.sourceJitter/2:this.sourceJitter-=1,_>3?h(1.15):_>1?h(1.1):_>.3?h(1.05):h(1)}},S=w=>{let A,O=()=>A&&A.start?A.start.length:0,H=F=>A.start[F]/1e3,_=F=>A.dur[F]/1e3,U=F=>A.fragIndex+F,M=(F,$)=>({chunkIdx:U(F),startTS:H(F),dur:_(F),discontinuity:$}),G=()=>{let F=0;if(A&&A.dur){let $=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,P=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,B=$;this.sourceJitter>1&&(B+=this.sourceJitter-1);let N=A.dur.length-1;for(;N>=0&&(B-=A.dur[N],!(B<=0));--N);F=Math.min(N,A.dur.length-1-P),F=Math.max(F,0)}return M(F,!0)},q=F=>{let $=O();if(!($<=0)){if((0,nt.isNonNullable)(F)){for(let P=0;P<$;P++)if(H(P)>F)return M(P)}return G()}},Y=F=>{let $=O(),P=F?F.chunkIdx+1:0,B=P-A.fragIndex;if(!($<=0)){if(!F||B<0||B-$>tk)return t(`Resync: offset=${B} bChunks=${$} chunk=`+JSON.stringify(F)),G();if(!(B>=$))return M(P-A.fragIndex,!1)}},le=(F,$,P)=>{l&&l.abort(),l=xr(this.urlResolver.resolve(F,!0,this.lowLatency),$,P,()=>this._retryCallback()).withTimeout(Mn).withRetryCount(Bl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(F,$)=>{le(w,P=>{if(!c())return;A=P;let B=!!A.lowLatency;B!==this.lowLatency&&b(B);let N=0;for(let we=0;we<A.dur.length;++we)N+=A.dur[we];N>0&&((0,nt.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(N/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,F(q($))},()=>this._handleNetworkError())},nextChunk:Y}},T=()=>{s=!1,u&&u.abort(),o&&o.abort(),l&&l.abort(),(0,nt.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:w=>{let{videoElement:A,logger:O}=this.params,H=S(e.jidxUrl),_,U,M,G,q=0,Y,le,he,F=()=>{Y&&(clearTimeout(Y),Y=void 0);let de=Math.max(rk,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ve=q+de,_e=Ce(),Oe=Math.min(1e4,Ve-_e);q=_e;let tt=()=>{l||c()&&H.seek(()=>{c()&&(q=Ce(),$(),F())})};Oe>0?Y=window.setTimeout(()=>{this.paused?F():tt()},Oe):tt()},$=()=>{let de;for(;de=H.nextChunk(G);)G=de,et(de);let Ve=H.nextChunk(M);if(Ve){if(M&&Ve.discontinuity){O("Detected discontinuity; restarting playback"),this.paused?F():(T(),this._initPlayerWith(e));return}we(Ve)}else F()},P=(de,Ve)=>{if(!c()||!this.sourceBuffer)return;let _e,Oe,tt,Ut=ti=>{window.setTimeout(()=>{c()&&P(de,Ve)},ti)};if(this.sourceBuffer.updating)O("Source buffer is updating; delaying appendBuffer"),Ut(100);else{let ti=Ce(),yi=A.currentTime;!this.paused&&A.buffered.length>1&&le===yi&&ti-he>500&&(O("Stall suspected; trying to fix"),this._fixupStall()),le!==yi&&(le=yi,he=ti);let Yi=this._getBufferSizeSec();if(Yi>30)O(`Buffered ${Yi} seconds; delaying appendBuffer`),Ut(2e3);else try{this.sourceBuffer.appendBuffer(de),this.videoPlayStarted?(this.bufferStates.push({ts:ti,buf:Yi}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ve&&Ve()}catch(_r){if(_r.name==="QuotaExceededError")O("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(_e=this.sourceBuffer.buffered.start(0),Oe=yi,Oe-_e>4&&this.sourceBuffer.remove(_e,Oe-3)),Ut(1e3);else throw _r}}},B=()=>{U&&_&&(O([`Appending chunk, sz=${U.byteLength}:`,JSON.stringify(M)]),P(U,function(){U=null,$()}))},N=de=>e.fragUrlTemplate.replace("%%id%%",de.chunkIdx),we=de=>{c()&&p(N(de),(Ve,_e)=>{if(c()){if(_e/=1e3,U=Ve,M=de,n=de.startTS,_e){let Oe=Math.min(10,de.dur/_e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Oe:Oe}B()}},()=>this._handleNetworkError())},et=de=>{c()&&((0,nt.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(N(de),!1)))},ve=de=>{c()&&(e.cachedHeader=de,P(de,()=>{_=!0,B()}))};s=!0,H.seek(de=>{if(c()){if(q=Ce(),!de){F();return}G=de,!(0,nt.isNullable)(w)||de.startTS>w?we(de):(M=de,$())}},w),e.cachedHeader?ve(e.cachedHeader):f(e.headerUrl,ve,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,nt.isNonNullable)(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,nt.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,nt.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let f,p,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),h=c/this.bitrate,p>10&&h>.8||p>15&&h>.5||p>20&&h>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}f=this._selectQuality(c),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(f,p)=>{let h=Ce();if(this.chunkRateEstimator.addInterval(f,h,p)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:h-f,speed:v}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}},n=-1/0,u,o=!0,l=()=>{let c=s.get();if(c&&u&&this.autoQuality){if(o&&c>u&&Dl(n)<3e4)return;i(c)}o=this.autoQuality};return{updateChunk:(c,f)=>{let p=s.updateChunk(c,f);return p&&l(),p},notifySwitch:c=>{let f=Ce();c<u&&(n=f),u=c}}}_fetchManifest(e,t,i){this.manifestRequest=xr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Mn).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,s=n=>{let u=[];return n!=null&&n.length?(n.forEach((o,l)=>{var d,c;o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&((c=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&c.call(d,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))},ek))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Qg=J(lr(),1),xe=require("@vkontakte/videoplayer-shared/es2015"),Vl=class{constructor(){this.onDroopedVideoFramesLimit$=new xe.Subject;this.subscription=new xe.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new xe.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,xe.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,xe.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,xe.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,xe.interval)(this.droppedFramesChecker.checkTime).pipe((0,xe.filter)(()=>this.playing),(0,xe.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,xe.debounce)(this.droppedFramesChecker.checkTime)),i=(0,xe.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,Qg.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,xe.isLower)(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},wr=Vl;var Dn=require("@vkontakte/videoplayer-shared/es2015"),Gg=require("@vkontakte/videoplayer-shared/es2015");var wa=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var ak=(a,e)=>new Dn.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,u)=>{n.forEach(o=>t.next(o.isIntersecting||wa()))},C(C({},i),e));r.observe(a);let s=(0,Gg.fromEvent)(document,"visibilitychange").pipe((0,Dn.map)(n=>!document.hidden||wa())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),ft=ak;var sk=["paused","playing","ready"],nk=["paused","playing","ready"],Aa=class{constructor(e){this.subscription=new K.Subscription;this.videoState=new ne("stopped");this.representations$=new K.ValueSubject([]);this.droppedFramesManager=new wr;this.maxSeekBackTime$=new K.ValueSubject(1/0);this.zeroTime$=new K.ValueSubject(void 0);this.liveOffset=new Oi;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:K.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,u=[];for(let o of n){let l=(t=o.name)!=null?t:o.index.toString(10),d=(i=hi(o.name))!=null?i:(0,K.videoSizeToQuality)(o.video),c=o.bitrate/1e3,f=C({},o.video);if(!d)continue;let p={id:l,quality:d,bitrate:c,size:f};u.push({track:p,representation:o})}this.representations$.next(u),this.params.output.availableVideoTracks$.next(u.map(({track:o})=>o)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,u=(s=this.representations$.getValue().find(({representation:o})=>o===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,K.isNonNullable)(u)&&this.params.output.currentVideoTrack$.next(u);break}case"bandwidth":{let{size:n,duration:u}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,u);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,_l.default)(nk,e)&&(n||u)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,_l.default)(sk,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Re(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==null?void 0: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(Re(this.params.source.url,o))}return;default:return(0,K.assertNever)(e)}};this.textTracksManager=new ht(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:K.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,K.merge)(this.videoState.stateChangeStarted$.pipe((0,K.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,K.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=We(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(Ne(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((0,K.map)(r=>r.map(({track:s})=>s)),(0,K.filter)(r=>!!r.length),(0,K.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,K.filterChanged)(),(0,K.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,K.combine)({zeroTime:this.zeroTime$.pipe((0,K.filter)(K.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(Ct(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(pt(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(ft(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&(0,K.videoQualityToHeight)(r),min:s&&(0,K.videoQualityToHeight)(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,K.assertNever)(r.to)}},t)).add((0,K.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,K.observableFrom)(["init"])).pipe((0,K.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ze(this.video)}createLiveDashPlayer(){let e=new xa({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(){var l,d,c,f,p,h;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(f=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?f:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,K.isNonNullable)(t)?t:Bt(e.map(({track:b})=>b),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),u=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==u)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),n||o||s!==u){let b=(h=e.find(({track:v})=>v.id===s))==null?void 0:h.representation;(0,K.assertNonNullable)(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;(0,K.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Re(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Wg=Aa;var iy=J(dt(),1);var Be=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var ee=require("@vkontakte/videoplayer-shared/es2015");var{NativeAbortSignal:ZV,NativeAbortController:e_}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self!="undefined"?self:global);function zg(a){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?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 Yg(a){if(a===void 0)if(typeof document=="undefined")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(e){a=new Error("This operation was aborted"),a.name="AbortError"}return a}var Cn=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}},Ar=class extends Cn{constructor(){super(),this.listeners||Cn.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 Ni;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Ni;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}},Ni=class{constructor(){Object.defineProperty(this,"signal",{value:new Ar,writable:!0,configurable:!0})}abort(e){let t=Yg(e),i=zg(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ni.prototype[Symbol.toStringTag]="AbortController",Ar.prototype[Symbol.toStringTag]="AbortSignal");function Bn(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 Ol(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Bn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let f=new t(l,d);return c&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),f},s.prototype=t.prototype);let n=e;return{fetch:(o,l)=>{let d=s&&s.prototype.isPrototypeOf(o)?o.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(p){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let f=new Promise((p,h)=>{d.addEventListener("abort",()=>h(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,n(o,l)])}return n(o,l)},Request:s}}var ok=()=>"fetch"in window,Pa=ok()&&Bn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Kg=Pa?Ol({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,mt=Pa?Kg.fetch:window.fetch,c_=Pa?Kg.Request:window.Request,fe=Pa?Ni:window.AbortController,d_=Pa?Ar:window.AbortSignal;var oc=J(Ra(),1);var VS=J(BS(),1),Pr=require("@vkontakte/videoplayer-shared/es2015"),Vn=a=>{if(!a)return{id:"EmptyResponse",category:Pr.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Pr.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,VS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Pr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Pr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Pr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Ue=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};var I=require("@vkontakte/videoplayer-shared/es2015");var Fn=J(dt(),1),ji=J(xt(),1),Nn=J(Ra(),1);var Gk=(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)},Wk=a=>window.clearTimeout(a),_S=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),OS=!_S(window.requestIdleCallback)||!_S(window.cancelIdleCallback),Rr=OS?Gk:window.requestIdleCallback,_t=OS?Wk:window.cancelIdleCallback;var Wv=J(mn(),1);var mi=require("@vkontakte/videoplayer-shared/es2015");var zk=18,FS=!1;try{FS=X.browser.isSafari&&!!X.browser.safariVersion&&X.browser.safariVersion<=zk}catch(a){console.error(a)}var Hl=class{constructor(e){this.bufferFull$=new mi.Subject;this.error$=new mi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:mi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return R(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return R(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};FS&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:mi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,mi.assertNever)(t)}}},NS=Hl;var kr=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var k=require("@vkontakte/videoplayer-shared/es2015");var qS=J(xt(),1);var _n=a=>a.valid,ce=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 Lr=class extends ce{};var US=require("@vkontakte/videoplayer-shared/es2015");var La=class extends ce{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:(0,US.assertNever)(e)}}};var $a=class extends ce{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 Ma=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ye=class extends ce{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 Da=class extends ye{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 Ca=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ba=class extends ce{constructor(e,t){super(e,t),this.data=this.content}};var Ui=class extends ye{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 Va=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var _a=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Oa=class extends ye{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 Fa=class extends ye{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Na=class extends ye{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 Ua=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qa=class extends ye{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ja=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ha=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Qa=class extends ye{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Ga=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wa=class extends ye{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var za=class extends ye{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Ya=class extends ye{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Ka=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xa=class extends ye{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 Ja=class extends ce{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 Kk={ftyp:$a,moov:Ma,mvhd:Da,moof:Ca,mdat:Ba,sidx:Ui,trak:Va,mdia:Ua,mfhd:Qa,tkhd:qa,traf:Ga,tfhd:Wa,tfdt:za,trun:Ya,minf:ja,sv3d:_a,st3d:Oa,prhd:Fa,proj:Ha,equi:Na,uuid:La,stbl:Ka,stsd:Xa,avc1:Ja,unknown:Lr},zt=class a{constructor(e={}){this.options=C({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||!_n(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=Kk[e];return i?new i(t,new a):new Lr(t,new a)}};var bi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;_n(t)&&((s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Jk=new TextDecoder("ascii"),Zk=a=>Jk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",eL=a=>{let e=new Ui(a,new zt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,u={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,u})},tL=(a,e)=>{let i=new zt().parse(a),r=new bi(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,c=o.source.byteOffset-u.source.byteOffset+o.size;return new DataView(a.buffer,l,c)},iL=a=>{let t=new zt().parse(a),i=new bi(t),r={},s=i.findAll("uuid"),n=(0,qS.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},rL=a=>{var r;let t=new zt().parse(a);return(r=new bi(t).find("sidx"))==null?void 0:r.timescale},aL=(a,e)=>{let i=new zt().parse(a),s=new bi(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),u=s[s.length-1].children.find(c=>c.type==="tfdt"),o=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return o.sampleDuration.length?l=o.sampleDuration.reduce((c,f)=>c+f,0):l=n.defaultSampleDuration*o.sampleCount,(Number(u.baseMediaDecodeTime)+l)/e*1e3},sL=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new zt().parse(a),r=new bi(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},jS={validateData:Zk,parseInit:sL,getIndexRange:()=>{},parseSegments:eL,parseFeedableSegmentChunk:tL,getChunkEndTime:aL,getServerLatencyTimestamps:iL,getTimescaleFromIndex:rL};var ts=J(dt(),1),Yt=require("@vkontakte/videoplayer-shared/es2015");var QS=require("@vkontakte/videoplayer-shared/es2015");var HS={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"}},GS=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=es(a,t),r=i in HS,s=r?HS[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,d=es(o),c=l*kt(2,(u-1)*8)+d,f=t+u,p;return f+c>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:f,tagSize:f+c,value:p,valueSize:c}},es=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*kt(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*kt(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*kt(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},wt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return es(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:(0,QS.assertNever)(e)}},qi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=GS(i);if(!e(r))return;r.type==="master"&&qi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},WS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=GS(a);return qi(r.value,({tag:s,type:n,value:u})=>(s===17143?e=wt(u,n):s===17026?t=wt(u,n):s===17029&&(i=wt(u,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var zS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],nL=[231,22612,22743,167,171,163,160,175],oL=a=>{let e,t,i,r,s=!1,n=!1,u=!1,o,l,d=!1,c=0;return qi(a,({tag:f,type:p,value:h,valueSize:b})=>{if(f===21419){let v=wt(h,p);l=es(v)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+b):f===357149030?s=!0:f===290298740?n=!0:f===2807729?i=wt(h,p):f===17545?r=wt(h,p):f===21420&&l===475249515?o=wt(h,p):f===374648427?qi(h,({tag:v,type:S,value:T})=>v===30321?(d=wt(T,S)===1,!1):!0):s&&n&&(0,ts.default)(zS,f)&&(u=!0),!u}),(0,Yt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Yt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Yt.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},uL=a=>{if((0,Yt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},lL=(a,e)=>{let t=!1,i=!1,r=u=>(0,Yt.isNonNullable)(u.time)&&(0,Yt.isNonNullable)(u.position),s=[],n;return qi(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=wt(l,o));break;case 183:break;case 241:n&&(n.position=wt(l,o));break;default:t&&(0,ts.default)(zS,u)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((u,o)=>{let{time:l,position:d}=u,c=s[o+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}}})},cL=a=>{let e=0,t=!1;try{qi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ts.default)(nL,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,ts.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},YS={validateData:WS,parseInit:oL,getIndexRange:uL,parseSegments:lL,parseFeedableSegmentChunk:cL};var Ot=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return YS;case"mp4":return jS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Ft=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Xl=J(Sv(),1),Fv=J(lr(),1),Nv=J(Cv(),1),Uv=J(xt(),1),Jl=J(Tr(),1);var Bv=J(dt(),1),Kl=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,Bv.default)(["6E","7A","F4"],u)}}return!1};var is=require("@vkontakte/videoplayer-shared/es2015");var Vv=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var _v=a=>{var e;try{let t=l$(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let o=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(o=>o!==""),u={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(u).forEach(o=>{let l=u[o];(typeof l=="undefined"||l==="")&&delete u[o]}),u}return null}catch(t){return null}};function l$(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<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 xd=Z(ii(),1);var Iy=require("@vkontakte/videoplayer-shared/es2015"),xy=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Xi(a):void 0)!=null?u:(0,Iy.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Ey=({id:s,bitrate:e})=>({id:s,bitrate:e}),wy=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Ay=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Ed=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,xd.default)(i.split("."),0),isDefault:r}),wd=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,xd.default)(r.split("."),0)}),Ad=s=>"url"in s,bt=s=>s.type==="template",pn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Py=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Vi=(s,e)=>{let t=s;t=(0,Pd.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,ky.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Pd.default)(t,n,(o,u)=>(0,hn.isNullable)(a)?o:(0,hn.isNullable)(u)?a:(0,Ry.default)(a,parseInt(u,10),"0"))}return t},Ly=(s,e)=>{var N,L,Q,O,J,G,de,$,_,V,B,z,Ee,et,ve,fe,Fe,Ne,Ue,tt,Ft,zt,ai,mi,zi,ms,bs,gs,Ss,vs,ys,Ts,Is,xs,Es,ws,As,Ps,ks,Rs,Ms,Ls,Bs,$s,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,zs,Qs,Gs,Ws,Ys,Ks;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(Re=>{var Y,nt;return(nt=(Y=Re.textContent)==null?void 0:Y.trim())!=null?nt:""}),o=(N=(0,My.default)(n,0))!=null?N:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],f=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let v,y=a.getAttribute("mediaPresentationDuration"),x=[...a.getElementsByTagName("Period")],E=x.reduce((Re,Y)=>F(P({},Re),{[Y.id]:Y.children}),{}),A=x.reduce((Re,Y)=>F(P({},Re),{[Y.id]:Y.getAttribute("duration")}),{});y?v=Py(y):(0,kd.default)(A).filter(Re=>Re).length&&!u?v=(0,kd.default)(A).reduce((Re,Y)=>{var nt;return Re+((nt=Py(Y))!=null?nt:0)},0):b&&(v=parseInt(b,10));let D=0,j=(Q=(L=a.getAttribute("profiles"))==null?void 0:L.split(","))!=null?Q:[];for(let Re of x.map(Y=>Y.id))for(let Y of E[Re]){let nt=(O=Y.getAttribute("id"))!=null?O:"id"+(D++).toString(10),Qt=(J=Y.getAttribute("mimeType"))!=null?J:"",ar=(G=Y.getAttribute("codecs"))!=null?G:"",nr=(de=Y.getAttribute("contentType"))!=null?de:Qt==null?void 0:Qt.split("/")[0],Qu=(_=($=Y.getAttribute("profiles"))==null?void 0:$.split(","))!=null?_:[],Xs=(B=Ty((V=Y.getAttribute("lang"))!=null?V:""))!=null?B:{},bi=(et=(Ee=(z=Y.querySelector("Label"))==null?void 0:z.textContent)==null?void 0:Ee.trim())!=null?et:void 0,Gu=Y.querySelectorAll("Representation"),Wu=Y.querySelector("SegmentTemplate"),Yu=(fe=(ve=Y.querySelector("Role"))==null?void 0:ve.getAttribute("value"))!=null?fe:void 0,wt=nr,ue={id:nt,language:Xs.language,isDefault:Yu==="main",label:bi,codecs:ar,hdr:wt==="video"&&us(ar),mime:Qt,representations:[]};for(let W of Gu){let ze=(Fe=W.getAttribute("lang"))!=null?Fe:void 0,Gt=(Ue=(Ne=bi!=null?bi:Y.getAttribute("label"))!=null?Ne:W.getAttribute("label"))!=null?Ue:void 0,gi=(zt=(Ft=(tt=W.querySelector("BaseURL"))==null?void 0:tt.textContent)==null?void 0:Ft.trim())!=null?zt:"",ot=new URL(gi||o,e).toString(),Qe=(ai=W.getAttribute("mimeType"))!=null?ai:Qt,Si=(zi=(mi=W.getAttribute("codecs"))!=null?mi:ar)!=null?zi:"",vi;if(nr==="text"){let Ge=W.getAttribute("id")||"",yi=((ms=Xs.privateuse)==null?void 0:ms.includes("x-auto"))||Ge.includes("_auto"),ut=W.querySelector("SegmentTemplate");if(ut){let Wt={representationId:(bs=W.getAttribute("id"))!=null?bs:void 0,bandwidth:(gs=W.getAttribute("bandwidth"))!=null?gs:void 0},Ti=parseInt((Ss=W.getAttribute("bandwidth"))!=null?Ss:"",10)/1e3,Ii=(ys=parseInt((vs=ut.getAttribute("startNumber"))!=null?vs:"",10))!=null?ys:1,At=parseInt((Ts=ut.getAttribute("timescale"))!=null?Ts:"",10),or=(Is=ut.querySelectorAll("SegmentTimeline S"))!=null?Is:[],Pt=ut.getAttribute("media");if(!Pt)continue;let xi=[],Ei=0,wi="",kt=0,Yt=Ii,ge=0;for(let Me of or){let lt=parseInt((xs=Me.getAttribute("d"))!=null?xs:"",10),Te=parseInt((Es=Me.getAttribute("r"))!=null?Es:"",10)||0,We=parseInt((ws=Me.getAttribute("t"))!=null?ws:"",10);ge=Number.isFinite(We)?We:ge;let ct=lt/At*1e3,Ye=ge/At*1e3;for(let De=0;De<Te+1;De++){let Ke=Vi(Pt,F(P({},Wt),{segmentNumber:Yt.toString(10),segmentTime:(ge+De*lt).toString(10)})),Rt=(Ye!=null?Ye:0)+De*ct,Xt=Rt+ct;Yt++,xi.push({time:{from:Rt,to:Xt},url:Ke})}ge+=(Te+1)*lt,Ei+=(Te+1)*ct}kt=ge/At*1e3,wi=Vi(Pt,F(P({},Wt),{segmentNumber:Yt.toString(10),segmentTime:ge.toString(10)}));let Kt={time:{from:kt,to:1/0},url:wi},qe={type:"template",baseUrl:ot,segmentTemplateUrl:Pt,initUrl:"",totalSegmentsDurationMs:Ei,segments:xi,nextSegmentBeyondManifest:Kt,timescale:At};vi={id:Ge,kind:"text",segmentReference:qe,profiles:[],duration:v,bitrate:Ti,mime:"",codecs:"",width:0,height:0,isAuto:yi}}else vi={id:Ge,isAuto:yi,kind:"text",url:ot}}else{let Ge=(Ps=(As=W.getAttribute("contentType"))!=null?As:Qe==null?void 0:Qe.split("/")[0])!=null?Ps:nr,yi=(Rs=(ks=Y.getAttribute("profiles"))==null?void 0:ks.split(","))!=null?Rs:[],ut=parseInt((Ms=W.getAttribute("width"))!=null?Ms:"",10),Wt=parseInt((Ls=W.getAttribute("height"))!=null?Ls:"",10),Ti=parseInt((Bs=W.getAttribute("bandwidth"))!=null?Bs:"",10)/1e3,Ii=($s=W.getAttribute("frameRate"))!=null?$s:"",At=(Ds=W.getAttribute("quality"))!=null?Ds:void 0,or=Ii?cu(Ii):void 0,Pt=(Cs=W.getAttribute("id"))!=null?Cs:"id"+(D++).toString(10),xi=Ge==="video"?`${Wt}p`:Ge==="audio"?`${Ti}Kbps`:Si,Ei=`${Pt}@${xi}`,wi=[...j,...Qu,...yi],kt,Yt=W.querySelector("SegmentBase"),ge=(Vs=W.querySelector("SegmentTemplate"))!=null?Vs:Wu;if(Yt){let qe=(_s=(Os=W.querySelector("SegmentBase Initialization"))==null?void 0:Os.getAttribute("range"))!=null?_s:"",[Me,lt]=qe.split("-").map(Ke=>parseInt(Ke,10)),Te={from:Me,to:lt},We=(Fs=W.querySelector("SegmentBase"))==null?void 0:Fs.getAttribute("indexRange"),[ct,Ye]=We?We.split("-").map(Ke=>parseInt(Ke,10)):[],De=We?{from:ct,to:Ye}:void 0;kt={type:"byteRange",url:ot,initRange:Te,indexRange:De}}else if(ge){let qe={representationId:(Ns=W.getAttribute("id"))!=null?Ns:void 0,bandwidth:(Us=W.getAttribute("bandwidth"))!=null?Us:void 0},Me=parseInt((qs=ge.getAttribute("timescale"))!=null?qs:"",10),lt=(js=ge.getAttribute("initialization"))!=null?js:"",Te=ge.getAttribute("media"),We=(zs=parseInt((Hs=ge.getAttribute("startNumber"))!=null?Hs:"",10))!=null?zs:1,ct=Vi(lt,qe);if(!Te)throw new ReferenceError("No media attribute in SegmentTemplate");let Ye=(Qs=ge.querySelectorAll("SegmentTimeline S"))!=null?Qs:[],De=[],Ke=0,Rt="",Xt=0;if(Ye.length){let Ai=We,Le=0;for(let Mt of Ye){let Ce=parseInt((Gs=Mt.getAttribute("d"))!=null?Gs:"",10),dt=parseInt((Ws=Mt.getAttribute("r"))!=null?Ws:"",10)||0,Pi=parseInt((Ys=Mt.getAttribute("t"))!=null?Ys:"",10);Le=Number.isFinite(Pi)?Pi:Le;let ur=Ce/Me*1e3,lr=Le/Me*1e3;for(let ki=0;ki<dt+1;ki++){let Xu=Vi(Te,F(P({},qe),{segmentNumber:Ai.toString(10),segmentTime:(Le+ki*Ce).toString(10)})),Js=(lr!=null?lr:0)+ki*ur,Ju=Js+ur;Ai++,De.push({time:{from:Js,to:Ju},url:Xu})}Le+=(dt+1)*Ce,Ke+=(dt+1)*ur}Xt=Le/Me*1e3,Rt=Vi(Te,F(P({},qe),{segmentNumber:Ai.toString(10),segmentTime:Le.toString(10)}))}else if((0,hn.isNonNullable)(v)){let Le=parseInt((Ks=ge.getAttribute("duration"))!=null?Ks:"",10)/Me*1e3,Mt=Math.ceil(v/Le),Ce=0;for(let dt=1;dt<Mt;dt++){let Pi=Vi(Te,F(P({},qe),{segmentNumber:dt.toString(10),segmentTime:Ce.toString(10)}));De.push({time:{from:Ce,to:Ce+Le},url:Pi}),Ce+=Le}Xt=Ce,Rt=Vi(Te,F(P({},qe),{segmentNumber:Mt.toString(10),segmentTime:Ce.toString(10)}))}let Ku={time:{from:Xt,to:1/0},url:Rt};kt={type:"template",baseUrl:ot,segmentTemplateUrl:Te,initUrl:ct,totalSegmentsDurationMs:Ke,segments:De,nextSegmentBeyondManifest:Ku,timescale:Me}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ge||!Qe)continue;let Kt={video:"video",audio:"audio",text:"text"}[Ge];if(!Kt)continue;wt||(wt=Kt),vi={id:Ei,kind:Kt,segmentReference:kt,profiles:wi,duration:v,bitrate:Ti,mime:Qe,codecs:Si,width:ut,height:Wt,fps:or,quality:At}}ue.language||(ue.language=ze),ue.label||(ue.label=Gt),ue.mime||(ue.mime=Qe),ue.codecs||(ue.codecs=Si),ue.hdr||(ue.hdr=wt==="video"&&us(Si)),ue.representations.push(vi)}if(wt){let W=r[wt].find(ze=>ze.id===ue.id);if(W&&ue.representations.every(ze=>bt(ze.segmentReference)))for(let ze of W.representations){let Gt=ue.representations.find(Qe=>Qe.id===ze.id),gi=Gt==null?void 0:Gt.segmentReference,ot=ze.segmentReference;ot.segments.push(...gi.segments),ot.nextSegmentBeyondManifest=gi.nextSegmentBeyondManifest}else r[wt].push(ue)}}return{duration:v,streams:r,baseUrls:n,live:S}};var Md=require("@vkontakte/videoplayer-shared/es2015"),ie=(s,e)=>(0,Md.isNonNullable)(s)&&(0,Md.isNonNullable)(e)&&s.readyState==="open"&&JL(s,e);function JL(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var fn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new R.ValueSubject(0);this.currentLowLatencySegmentLength$=new R.ValueSubject(0);this.currentSegmentLength$=new R.ValueSubject(0);this.onLastSegment$=new R.ValueSubject(!1);this.fullyBuffered$=new R.ValueSubject(!1);this.playingRepresentation$=new R.ValueSubject(void 0);this.playingRepresentationInit$=new R.ValueSubject(void 0);this.error$=new R.Subject;this.gaps=[];this.subscription=new R.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ye;this.switchAbortController=new ye;this.destroyAbortController=new ye;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,R.abortable)(this.destroyAbortController.signal,function(e){return pe(this,null,function*(){let t=this.representations.get(e);(0,R.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Bv(this.sourceBuffer),this.subscription.add((0,R.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:R.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:R.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,R.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:R.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ie(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,as(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);(0,R.assertNonNullable)(i,"No init buffer for starting representation"),(0,R.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))})}.bind(this));this.switchTo=(0,R.abortable)(this.destroyAbortController.signal,function(e,t=!1){return pe(this,null,function*(){if(!ie(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,R.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,R.isNullable)(a)||(0,R.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,R.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!ie(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,R.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new cr(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=(0,R.abortable)(this.destroyAbortController.signal,function(e,t=!1){return pe(this,null,function*(){if(!ie(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,R.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,R.isNullable)(a)||(0,R.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,R.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!ie(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,R.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new cr(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,R.abortable)(this.destroyAbortController.signal,function(e){return pe(this,null,function*(){var u,l;let t=(u=(0,pu.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(h=>h.id===d);c&&this.representations.set(d,c);let f=this.representations.get(d);if(!f||!bt(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,R.assertNonNullable)(r);let a=this.segments.get(i);(0,R.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,R.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!ie(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ye,(0,R.abortable)(this.switchAbortController.signal,function(i,r=!1){return pe(this,null,function*(){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,R.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,R.isNullable)(o)||(0,R.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,R.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ie(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,R.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!(0,R.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return k(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ye,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if((0,R.isNullable)(e)||(0,R.isNullable)(this.downloadingRepresentationId)||(0,R.isNullable)(this.playingRepresentationId)||(0,R.isNullable)(this.sourceBuffer)||!ie(this.mediaSource,this.sourceBuffer)||(0,R.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,R.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);(0,R.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=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)&&as(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(f=>{this.handleAsyncError(f,"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,du.default)(u,r))d="high";else{let c=(0,ls.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,ls.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;(0,R.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,pu.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,pu.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!bt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>F(P({},p),{status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,ls.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,R.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!bt(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),d=Vi(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&hi&&hi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&hi&&hi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:f,time:{from:p,to:h}},b)=>{let S=p<=i&&h>=i,v=p>i||S||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&p<=i+y||r<y&&h-p>=y||h<=i+y;return(f==="none"||f==="partially_ejected"&&v&&x&&this.sourceBuffer&&ie(this.mediaSource,this.sourceBuffer)&&!(at(this.sourceBuffer.buffered,p)&&at(this.sourceBuffer.buffered,h)))&&v&&x});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 f=a;f<n.length&&(o<=d||u<=c);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}loadSegments(e,t,i="auto"){return k(this,null,function*(){bt(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return k(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,R.abortable)(o,function(){return pe(this,null,function*(){let d=(0,R.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,R.now)(),!d)return;let c=new DataView(d),f=dn(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(c,b)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(c);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),pn(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())bt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return k(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,R.abortable)(n,function(){return pe(this,null,function*(){let u=(0,R.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,R.fromEvent)(window,"online").pipe((0,R.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,R.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),pn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(bt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,ls.default)(e,0).byte.from,to:(0,ls.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>k(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,R.now)(),yield 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:R.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!bt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,R.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:R.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,du.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return k(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!ie(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){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=dn(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return k(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!ie(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:d}=l;if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let c=d.byte.from-i,f=d.byte.to-i,p=f-c+1,h=c<r,b=f<=r;if(!h)continue;let S=dn(u.mime);if(d.status==="downloading"&&b){d.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+c,p);(yield this.sourceBufferTaskQueue.append(v,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-c),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),y=l.loadedBytes===p?v:S.parseFeedableSegmentChunk(v);y!=null&&y.byteLength&&(d.status="partially_fed",l.feedingBytes+=y.byteLength,(yield this.sourceBufferTaskQueue.append(y,a))&&!a.aborted?(l.fedBytes+=y.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!((0,R.isNullable)(this.sourceBuffer)||!ie(this.mediaSource,this.sourceBuffer))){!this.isLive&&te.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(at(this.sourceBuffer.buffered,e.segment.time.from,100)&&at(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:R.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ad(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])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.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=ss(()=>(0,By.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return k(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,R.abortable)(this.destroyAbortController.signal,function(){return pe(this,null,function*(){let o=(0,R.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,dn(e.mime),r)).then(o=>k(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let f=d;this.isLive&&bt(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),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:R.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return k(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return k(this,null,function*(){if(!this.sourceBuffer||!ie(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,R.isNullable)(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:f}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,f):l.push(u[d])}return l},o=u=>{var d;if(a>=t)return r;r.push(P({},u.time)),r=n(r);let l=Ad(u)?(d=u.size)!=null?d: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 f of this.segments.values())for(let p of f)(0,du.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let f={time:{from:l,to:d},url:"",status:"none"};o(f)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1})}abortBuffer(){return k(this,null,function*(){if(!this.sourceBuffer||!ie(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||!ie(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||!ie(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,R.isNullable)(e)?0:Ze(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ie(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||!ie(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=ss(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:R.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,R.isNullable)(this.sourceBuffer)||!ie(this.mediaSource,this.sourceBuffer)||(0,R.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:R.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var tr=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var hu=s=>{var a;let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};var ne=require("@vkontakte/videoplayer-shared/es2015");var fu=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var bu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new ne.ValueSubject(void 0);this.lastConnectionReused$=new ne.ValueSubject(void 0);this.lastRequestFirstBytes$=new ne.ValueSubject(void 0);this.recoverableError$=new ne.Subject;this.error$=new ne.Subject;this.abortAllController=new ye;this.subscription=new ne.Subscription;this.fetchManifest=(0,ne.abortable)(this.abortAllController.signal,function(e){return pe(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=tr(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=fu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(mu);return r?(t.log("success",(0,ne.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,ne.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,ne.abortable)(this.abortAllController.signal,function(l){return pe(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var O,J;let d=e,c=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let G=new URL(d,location.href);G.searchParams.append("bytes",`${i.from}-${i.to}`),d=G.toString();break}default:(0,ne.assertNever)(t)}this.requestQuic&&(d=tr(d));let p=this.abortAllController.signal,h;if(n){let G=new ye;if(h=(0,ne.merge)((0,ne.fromEvent)(this.abortAllController.signal,"abort"),(0,ne.fromEvent)(n,"abort")).subscribe(()=>{try{G.abort()}catch(de){mu(de)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{G.abort()}catch(de){mu(de)}p=G.signal}let b=(0,ne.now)();f.log("startRequest",(0,ne.flattenObject)({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:b}));let S=yield this.doFetch(d,{priority:a,headers:c,signal:p}),v=(0,ne.now)();if(!S)return f.error("error",{message:"No response in request"}),f.end(),h==null||h.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(v-b),!S.ok||!S.body){h==null||h.unsubscribe();let G=`Fetch error ${S.status}: ${S.statusText}`;return f.error("error",{message:G}),f.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!o){h==null||h.unsubscribe();let G=(0,ne.now)(),de={requestStartedAt:b,requestEndedAt:G,duration:G-b};return f.log("endRequest",(0,ne.flattenObject)(de)),f.end(),S.arrayBuffer()}let[y,x]=S.body.tee(),E=y.getReader();o&&((J=this.throughputEstimator)==null||J.trackStream(x,u));let A=0,D=new Uint8Array(0),j=!1,H=G=>{h==null||h.unsubscribe(),j=!0,mu(G)},N=(0,ne.abortable)(p,function($){return pe(this,arguments,function*({done:G,value:de}){if(A===0&&this.lastRequestFirstBytes$.next((0,ne.now)()-b),p.aborted){h==null||h.unsubscribe();return}if(!G&&de){let _=new Uint8Array(D.length+de.length);_.set(D),_.set(de,D.length),D=_,A+=de.byteLength,r==null||r(new DataView(D.buffer),A),yield E==null?void 0:E.read().then(N,H)}})}.bind(this));yield E==null?void 0:E.read().then(N,H),h==null||h.unsubscribe();let L=(0,ne.now)(),Q={failed:j,requestStartedAt:b,requestEndedAt:L,duration:L-b};return j?(f.error("endRequest",(0,ne.flattenObject)(Q)),f.end(),null):(f.log("endRequest",(0,ne.flattenObject)(Q)),f.end(),D.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,ne.abortable)(this.abortAllController.signal,function(e,t,i){return pe(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let f=new DataView(c,r-n,a-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(v=e.indexRange)!=null?v:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,h.from-n,h.to-h.from+1);else{let y=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,p,h);return{init:p,dataView:new DataView(c),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,ne.abortable)(this.abortAllController.signal,function(e,t){return pe(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>F(P({},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}=hu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return k(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,ne.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return k(this,null,function*(){let i=yield jt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:ne.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ne.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ne.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ne.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:ne.ErrorCategory.FATAL})}})}},mu=s=>{if(!pn(s))throw s};var Oi=(s,e,t)=>t*e+(1-t)*s,Ld=(s,e)=>s.reduce((t,i)=>t+i,0)/e,$y=(s,e,t,i)=>{let r=0,a=t,n=Ld(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};var mn=require("@vkontakte/videoplayer-shared/es2015");var ir=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new mn.ValueSubject(e.initial),this.debounced$=new mn.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ft(`raw_${t}`),this.smoothedSeries$=new ft(`smoothed_${t}`),this.reportedSeries$=new ft(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=pt(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&((0,mn.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var gu=class extends ir{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Oi(this.slow,e,this.params.emaAlphaSlow),this.fast=Oi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Su=class extends ir{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ld(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Oi(this.emaSmoothed,e,this.params.emaAlpha);let i=$y(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var vu=class extends ir{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?Oi(this.smoothed,t,this.params.emaAlpha):t}};var _i=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new gu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Su({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 vu(P({initial:e,label:"liveEdgeDelay"},t))}};var cs=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};var yu=require("@vkontakte/videoplayer-shared/es2015");var bn=class s{constructor(e,t){this.currentRepresentation$=new yu.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,yu.isNullable)(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(F(P({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&bt(t.segmentReference))}};var Iu=Z(ii(),1);var gn=require("@vkontakte/videoplayer-shared/es2015");var Dy=(s,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:a,nativeHlsSupported:n}=te.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(0,gn.assertNever)(l)}})},Tu=s=>{let{webmDecodingInfo:e}=te.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:(0,gn.assertNever)(s)}return[t,i]},Cy=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Tu(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(te.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",...Tu(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Tu(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Tu(s),...r,"HLS","HLS_ONDEMAND"];default:(0,gn.assertNever)(e)}return te.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Vy=({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=te.device.isMac&&te.browser.isSafari;if(te.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:(0,gn.assertNever)(s)}else te.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"]},Bd=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],xu=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Iu.default)(t.value.split("."),0)}for(let t of s){let i=(0,Iu.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Iu.default)(e.value.split("."),0)};var rB=["timeupdate","progress","play","seeked","stalled","waiting"],sB=["timeupdate","progress","loadeddata","playing","seeked"];var Eu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new I.Subscription;this.representationSubscription=new I.Subscription;this.state$=new ce("none");this.currentVideoRepresentation$=new I.ValueSubject(void 0);this.currentVideoRepresentationInit$=new I.ValueSubject(void 0);this.currentAudioRepresentation$=new I.ValueSubject(void 0);this.currentVideoSegmentLength$=new I.ValueSubject(0);this.currentAudioSegmentLength$=new I.ValueSubject(0);this.error$=new I.Subject;this.lastConnectionType$=new I.ValueSubject(void 0);this.lastConnectionReused$=new I.ValueSubject(void 0);this.lastRequestFirstBytes$=new I.ValueSubject(void 0);this.currentLiveTextRepresentation$=new I.ValueSubject(null);this.isLive$=new I.ValueSubject(!1);this.isActiveLive$=new I.ValueSubject(!1);this.isLowLatency$=new I.ValueSubject(!1);this.liveDuration$=new I.ValueSubject(0);this.liveSeekableDuration$=new I.ValueSubject(0);this.liveAvailabilityStartTime$=new I.ValueSubject(0);this.liveStreamStatus$=new I.ValueSubject(void 0);this.bufferLength$=new I.ValueSubject(0);this.liveLatency$=new I.ValueSubject(void 0);this.liveLoadBufferLength$=new I.ValueSubject(0);this.livePositionFromPlayer$=new I.ValueSubject(0);this.currentStallDuration$=new I.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new I.ValueSubject(0);this.fetcherRecoverableError$=new I.Subject;this.fetcherError$=new I.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new I.Subject;this.gapWatchdogActive=!1;this.destroyController=new ye;this.initManifest=(0,I.abortable)(this.destroyController.signal,function(e,t,i){return pe(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Oe(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:I.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,I.abortable)(this.destroyController.signal,function(){return pe(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Ly(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=lu(e))!=null?n:{id:"ManifestParsing",category:I.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,f,p,h;return!!((f=(c=this.element)==null?void 0:c.canPlayType)!=null&&f.call(c,l)&&((h=(p=Vt())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,f=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h)),c=new Set(d.map(({codecs:p})=>p)),f=xu(c);if(f&&(r[u]=d.filter(({codecs:p})=>p.startsWith(f))),u==="video"){let p=this.tuning.preferHDR,h=r.video.some(S=>S.hdr),b=r.video.some(S=>!S.hdr);te.display.isHDR&&p&&h?r.video=r.video.filter(S=>S.hdr):b&&(r.video=r.video.filter(S=>!S.hdr))}}let a=F(P({},t),{streams:r});return this.tracer.log("updateManifestEnd",(0,I.flattenObject)(a)),a})}.bind(this));this.initRepresentations=(0,I.abortable)(this.destroyController.signal,function(e,t,i){return pe(this,null,function*(){var f;this.tracer.log("initRepresentationsStart",(0,I.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,I.assertNonNullable)(this.manifest),(0,I.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,I.fromEvent)(p,"error").pipe((0,I.filter)(h=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Wo():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Xr())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 fn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,I.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,b)=>[...h,...b.representations],[]);this.audioBufferManager=new fn("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}bn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new bn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,I.merge)(...sB.map(p=>(0,I.fromEvent)(this.element,p))).pipe((0,I.map)(p=>this.element?Ze(this.element.buffered,this.element.currentTime*1e3):0),(0,I.filterChanged)(),(0,I.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,I.merge)((0,I.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,I.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,I.now)())),this.subscription.add((0,I.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,I.interval)(1e3).subscribe(h=>{let b=Yi(this.manifestUrlString,2);this.manifestUrlString=Oe(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,I.fromEvent)(this.element,"play").subscribe(h=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add((0,I.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,I.map)(({isActiveLive:h,isLowLatency:b})=>h&&b),(0,I.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||cs(this.element,1)})),this.representationSubscription.add((0,I.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,I.filter)(({bufferLength:h,isActiveLive:b,isLowLatency:S})=>b&&S&&!!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 b=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,I.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,I.filter)(({isLive:h})=>h),(0,I.filterChanged)((h,b)=>b.bufferLength<h.bufferLength),(0,I.map)(({rtt:h,bufferLength:b,segmentServerLatency:S})=>{let v=Yi(this.manifestUrlString,2);return(h/2+b+S+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,I.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:b,isLowLatency:S})=>{if(!S||!b)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=h-v;if(this.isManualDecreasePlaybackInLive())return;let A=1;Math.abs(E)>y&&(A=1+Math.sign(E)*x),cs(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var S,v;let b=0;if(h){let y=((v=(S=this.element)==null?void 0:S.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var A,D;return(D=(A=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:A.to)!=null?D:y}))-y}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add((0,I.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,I.throttle)(1e3)).subscribe(S=>k(this,[S],function*({liveLoadBufferLength:h,bufferLength:b}){if(!this.element||this.isUpdatingLive)return;let v=this.element.playbackRate,y=Yi(this.manifestUrlString,2),x=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(x,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),A=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,D=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,j=isFinite(h)?h:b,H=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),N=x<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(N);let L="none";if(H?L="active_low_latency":this.isLowLatency$.getValue()&&N?(this.bufferManagers.forEach(Q=>Q.proceedLowLatencyLive()),L="active_low_latency"):y!==0&&j<E?L="live_forward_buffering":j<E+D&&(L="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),L==="live_forward_buffering"||L==="live_with_target_offset"){let Q=p-(E+A),O=this.normolizeLiveOffset(Math.trunc(y+Q/v)),J=Math.abs(O-y),G=0;!h||J<=this.tuning.dashCmafLive.offsetCalculationError?G=y:O>0&&J>this.tuning.dashCmafLive.offsetCalculationError&&(G=O),this.manifestUrlString=Oe(this.manifestUrlString,G,2)}(L==="live_with_target_offset"||L==="live_forward_buffering")&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:I.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,I.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,I.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=(0,I.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,I.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=(0,I.combine)({allBuffersFull:l,someBufferEnded:d}).pipe((0,I.filterChanged)(),(0,I.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,I.filter)(p=>p));if(this.representationSubscription.add((0,I.merge)(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,I.merge)(...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=>{var b;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var S;if(((S=this.source)==null?void 0:S.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(b=this.source)==null||b.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,Dd.default)((0,Dd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let b=[];return h.duration&&b.push(h.duration),bt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&b.push(h.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,I.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,I.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:I.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new bu({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=_i.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,P({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return k(this,null,function*(){var r,a,n;(0,I.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,I.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Oe(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){(0,I.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,I.merge)(...rB.map(e=>(0,I.fromEvent)(this.element,e)),(0,I.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:I.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,I.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,I.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&at(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,h,b,S,v,y,x,E,A,D,j;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=(0,I.now)(),n=100,o=(b=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?v:0,l=(x=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?x:0,d=(A=(E=this.audioBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?A:0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,f=this.audioBufferManager&&d<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||f)&&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(N=>{this.error$.next({id:"stallIntervalCallback",category:I.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:N})}),r.liveLastOffset=H}else{let H=this.element.currentTime*1e3;(D=this.videoBufferManager)==null||D.maintain(H),(j=this.audioBufferManager)==null||j.maintain(H),r.position=H}this.tracer.log("stallIntervalCallback",(0,I.flattenObject)(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,I.interval)(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:I.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return k(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return k(this,null,function*(){var r,a,n,o,u;(0,I.assertNonNullable)(this.element),(0,I.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),at(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!((0,I.isNullable)(this.element)||(0,I.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,I.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,I.isNonNullable)(this.element)&&(0,I.isNonNullable)(this.source)&&(0,I.isNonNullable)(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,I.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){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}updateLive(){return k(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=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=F(P({},i),{gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,I.flattenObject)(i)))}}};var wu=class{constructor(e,t){this.fov=e,this.orientation=t}};var Au=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/pt(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed=P({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*pt(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Fy=`attribute vec2 a_vertex;
124
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Ov=a=>{if(!(a!=null&&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==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},At=(a,e)=>{let t=a;t=(0,Xl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,Fv.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Xl.default)(t,n,(u,o)=>(0,is.isNullable)(s)?u:(0,is.isNullable)(o)?s:(0,Nv.default)(s,parseInt(o,10),"0"))}return t},On=(a,e)=>{var U,M,G,q,Y,le,he,F,$,P,B,N,we,et,ve,de,Ve,_e,Oe,tt,Ut,ti,yi,Yi,_r,wc,Ac,Pc,Rc,kc,Lc,$c,Mc,Dc,Cc,Bc,Vc,_c,Oc,Fc,Nc,Uc,qc,jc,Hc,Qc,Gc,Wc,zc,Yc,Kc,Xc,Jc,Zc,ed,td,id,rd,ad,sd,nd;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(gt=>{var Se,Ti;return(Ti=(Se=gt.textContent)==null?void 0:Se.trim())!=null?Ti:""}),u=(U=(0,Uv.default)(n,0))!=null?U:"",o=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],f=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,v;o&&(v={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let S,T=s.getAttribute("mediaPresentationDuration"),E=[...s.getElementsByTagName("Period")],w=E.reduce((gt,Se)=>Q(C({},gt),{[Se.id]:Se.children}),{}),A=E.reduce((gt,Se)=>Q(C({},gt),{[Se.id]:Se.getAttribute("duration")}),{});T?S=Ov(T):(0,Jl.default)(A).filter(gt=>gt).length&&!o?S=(0,Jl.default)(A).reduce((gt,Se)=>{var Ti;return gt+((Ti=Ov(Se))!=null?Ti:0)},0):b&&(S=parseInt(b,10));let O=0,H=(G=(M=s.getAttribute("profiles"))==null?void 0:M.split(","))!=null?G:[];for(let gt of E.map(Se=>Se.id))for(let Se of w[gt]){let Ti=(q=Se.getAttribute("id"))!=null?q:"id"+(O++).toString(10),Or=(Y=Se.getAttribute("mimeType"))!=null?Y:"",Io=(le=Se.getAttribute("codecs"))!=null?le:"",Eo=(he=Se.getAttribute("contentType"))!=null?he:Or==null?void 0:Or.split("/")[0],By=($=(F=Se.getAttribute("profiles"))==null?void 0:F.split(","))!=null?$:[],od=(B=_v((P=Se.getAttribute("lang"))!=null?P:""))!=null?B:{},ys=(et=(we=(N=Se.querySelector("Label"))==null?void 0:N.textContent)==null?void 0:we.trim())!=null?et:void 0,Vy=Se.querySelectorAll("Representation"),_y=Se.querySelector("SegmentTemplate"),Oy=(de=(ve=Se.querySelector("Role"))==null?void 0:ve.getAttribute("value"))!=null?de:void 0,Ki=Eo,ke={id:Ti,language:od.language,isDefault:Oy==="main",label:ys,codecs:Io,hdr:Ki==="video"&&Kl(Io),mime:Or,representations:[]};for(let me of Vy){let ii=(Ve=me.getAttribute("lang"))!=null?Ve:void 0,Fr=(Oe=(_e=ys!=null?ys:Se.getAttribute("label"))!=null?_e:me.getAttribute("label"))!=null?Oe:void 0,Ts=(ti=(Ut=(tt=me.querySelector("BaseURL"))==null?void 0:tt.textContent)==null?void 0:Ut.trim())!=null?ti:"",Ii=new URL(Ts||u,e).toString(),ri=(yi=me.getAttribute("mimeType"))!=null?yi:Or,Is=(_r=(Yi=me.getAttribute("codecs"))!=null?Yi:Io)!=null?_r:"",Es;if(Eo==="text"){let ai=me.getAttribute("id")||"",xs=((wc=od.privateuse)==null?void 0:wc.includes("x-auto"))||ai.includes("_auto"),Ei=me.querySelector("SegmentTemplate");if(Ei){let Nr={representationId:(Ac=me.getAttribute("id"))!=null?Ac:void 0,bandwidth:(Pc=me.getAttribute("bandwidth"))!=null?Pc:void 0},ws=parseInt((Rc=me.getAttribute("bandwidth"))!=null?Rc:"",10)/1e3,As=(Lc=parseInt((kc=Ei.getAttribute("startNumber"))!=null?kc:"",10))!=null?Lc:1,Xi=parseInt(($c=Ei.getAttribute("timescale"))!=null?$c:"",10),xo=(Mc=Ei.querySelectorAll("SegmentTimeline S"))!=null?Mc:[],Ji=Ei.getAttribute("media");if(!Ji)continue;let Ps=[],Rs=0,ks="",Zi=0,Ur=As,qe=0;for(let St of xo){let xi=parseInt((Dc=St.getAttribute("d"))!=null?Dc:"",10),ct=parseInt((Cc=St.getAttribute("r"))!=null?Cc:"",10)||0,si=parseInt((Bc=St.getAttribute("t"))!=null?Bc:"",10);qe=Number.isFinite(si)?si:qe;let wi=xi/Xi*1e3,ni=qe/Xi*1e3;for(let Pt=0;Pt<ct+1;Pt++){let oi=At(Ji,Q(C({},Nr),{segmentNumber:Ur.toString(10),segmentTime:(qe+Pt*xi).toString(10)})),er=(ni!=null?ni:0)+Pt*wi,jr=er+wi;Ur++,Ps.push({time:{from:er,to:jr},url:oi})}qe+=(ct+1)*xi,Rs+=(ct+1)*wi}Zi=qe/Xi*1e3,ks=At(Ji,Q(C({},Nr),{segmentNumber:Ur.toString(10),segmentTime:qe.toString(10)}));let qr={time:{from:Zi,to:1/0},url:ks},qt={type:"template",baseUrl:Ii,segmentTemplateUrl:Ji,initUrl:"",totalSegmentsDurationMs:Rs,segments:Ps,nextSegmentBeyondManifest:qr,timescale:Xi};Es={id:ai,kind:"text",segmentReference:qt,profiles:[],duration:S,bitrate:ws,mime:"",codecs:"",width:0,height:0,isAuto:xs}}else Es={id:ai,isAuto:xs,kind:"text",url:Ii}}else{let ai=(_c=(Vc=me.getAttribute("contentType"))!=null?Vc:ri==null?void 0:ri.split("/")[0])!=null?_c:Eo,xs=(Fc=(Oc=Se.getAttribute("profiles"))==null?void 0:Oc.split(","))!=null?Fc:[],Ei=parseInt((Nc=me.getAttribute("width"))!=null?Nc:"",10),Nr=parseInt((Uc=me.getAttribute("height"))!=null?Uc:"",10),ws=parseInt((qc=me.getAttribute("bandwidth"))!=null?qc:"",10)/1e3,As=(jc=me.getAttribute("frameRate"))!=null?jc:"",Xi=(Hc=me.getAttribute("quality"))!=null?Hc:void 0,xo=As?Vv(As):void 0,Ji=(Qc=me.getAttribute("id"))!=null?Qc:"id"+(O++).toString(10),Ps=ai==="video"?`${Nr}p`:ai==="audio"?`${ws}Kbps`:Is,Rs=`${Ji}@${Ps}`,ks=[...H,...By,...xs],Zi,Ur=me.querySelector("SegmentBase"),qe=(Gc=me.querySelector("SegmentTemplate"))!=null?Gc:_y;if(Ur){let qt=(zc=(Wc=me.querySelector("SegmentBase Initialization"))==null?void 0:Wc.getAttribute("range"))!=null?zc:"",[St,xi]=qt.split("-").map(oi=>parseInt(oi,10)),ct={from:St,to:xi},si=(Yc=me.querySelector("SegmentBase"))==null?void 0:Yc.getAttribute("indexRange"),[wi,ni]=si?si.split("-").map(oi=>parseInt(oi,10)):[],Pt=si?{from:wi,to:ni}:void 0;Zi={type:"byteRange",url:Ii,initRange:ct,indexRange:Pt}}else if(qe){let qt={representationId:(Kc=me.getAttribute("id"))!=null?Kc:void 0,bandwidth:(Xc=me.getAttribute("bandwidth"))!=null?Xc:void 0},St=parseInt((Jc=qe.getAttribute("timescale"))!=null?Jc:"",10),xi=(Zc=qe.getAttribute("initialization"))!=null?Zc:"",ct=qe.getAttribute("media"),si=(td=parseInt((ed=qe.getAttribute("startNumber"))!=null?ed:"",10))!=null?td:1,wi=At(xi,qt);if(!ct)throw new ReferenceError("No media attribute in SegmentTemplate");let ni=(id=qe.querySelectorAll("SegmentTimeline S"))!=null?id:[],Pt=[],oi=0,er="",jr=0;if(ni.length){let Ls=si,vt=0;for(let tr of ni){let Rt=parseInt((rd=tr.getAttribute("d"))!=null?rd:"",10),Ai=parseInt((ad=tr.getAttribute("r"))!=null?ad:"",10)||0,$s=parseInt((sd=tr.getAttribute("t"))!=null?sd:"",10);vt=Number.isFinite($s)?$s:vt;let wo=Rt/St*1e3,Ao=vt/St*1e3;for(let Ms=0;Ms<Ai+1;Ms++){let Ny=At(ct,Q(C({},qt),{segmentNumber:Ls.toString(10),segmentTime:(vt+Ms*Rt).toString(10)})),ud=(Ao!=null?Ao:0)+Ms*wo,Uy=ud+wo;Ls++,Pt.push({time:{from:ud,to:Uy},url:Ny})}vt+=(Ai+1)*Rt,oi+=(Ai+1)*wo}jr=vt/St*1e3,er=At(ct,Q(C({},qt),{segmentNumber:Ls.toString(10),segmentTime:vt.toString(10)}))}else if((0,is.isNonNullable)(S)){let vt=parseInt((nd=qe.getAttribute("duration"))!=null?nd:"",10)/St*1e3,tr=Math.ceil(S/vt),Rt=0;for(let Ai=1;Ai<tr;Ai++){let $s=At(ct,Q(C({},qt),{segmentNumber:Ai.toString(10),segmentTime:Rt.toString(10)}));Pt.push({time:{from:Rt,to:Rt+vt},url:$s}),Rt+=vt}jr=Rt,er=At(ct,Q(C({},qt),{segmentNumber:tr.toString(10),segmentTime:Rt.toString(10)}))}let Fy={time:{from:jr,to:1/0},url:er};Zi={type:"template",baseUrl:Ii,segmentTemplateUrl:ct,initUrl:wi,totalSegmentsDurationMs:oi,segments:Pt,nextSegmentBeyondManifest:Fy,timescale:St}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ai||!ri)continue;let qr={video:"video",audio:"audio",text:"text"}[ai];if(!qr)continue;Ki||(Ki=qr),Es={id:Rs,kind:qr,segmentReference:Zi,profiles:ks,duration:S,bitrate:ws,mime:ri,codecs:Is,width:Ei,height:Nr,fps:xo,quality:Xi}}ke.language||(ke.language=ii),ke.label||(ke.label=Fr),ke.mime||(ke.mime=ri),ke.codecs||(ke.codecs=Is),ke.hdr||(ke.hdr=Ki==="video"&&Kl(Is)),ke.representations.push(Es)}if(Ki){let me=r[Ki].find(ii=>ii.id===ke.id);if(me&&ke.representations.every(ii=>ii.segmentReference.type==="template"))for(let ii of me.representations){let Fr=ke.representations.find(ri=>ri.id===ii.id),Ts=Fr==null?void 0:Fr.segmentReference,Ii=ii.segmentReference;Ii.segments.push(...Ts.segments),Ii.nextSegmentBeyondManifest=Ts.nextSegmentBeyondManifest}else r[Ki].push(ke)}}return{duration:S,streams:r,baseUrls:n,live:v}};var Zl=J(xt(),1);var qv=require("@vkontakte/videoplayer-shared/es2015"),jv=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var o;let u=(o=s?hi(s):void 0)!=null?o:(0,qv.videoSizeToQuality)({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Hv=({id:a,bitrate:e})=>({id:a,bitrate:e}),Qv=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Gv=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),ec=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Zl.default)(i.split("."),0),isDefault:r}),tc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Zl.default)(r.split("."),0)}),ic=a=>"url"in a,ot=a=>a.type==="template";var rc=require("@vkontakte/videoplayer-shared/es2015"),Z=(a,e)=>(0,rc.isNonNullable)(a)&&(0,rc.isNonNullable)(e)&&a.readyState==="open"&&c$(a,e);function c$(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var rs=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new k.ValueSubject(0);this.currentLowLatencySegmentLength$=new k.ValueSubject(0);this.currentSegmentLength$=new k.ValueSubject(0);this.onLastSegment$=new k.ValueSubject(!1);this.fullyBuffered$=new k.ValueSubject(!1);this.playingRepresentation$=new k.ValueSubject(void 0);this.playingRepresentationInit$=new k.ValueSubject(void 0);this.error$=new k.Subject;this.gaps=[];this.subscription=new k.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new fe;this.switchAbortController=new fe;this.destroyAbortController=new fe;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,k.abortable)(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){let t=this.representations.get(e);(0,k.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new NS(this.sourceBuffer),this.subscription.add((0,k.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let u,o=this.mediaSource.readyState;o!=="open"&&(u={id:`SegmentEjection_source_${o}`,category:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),u!=null||(u={id:"SegmentEjection",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(u)})),this.subscription.add((0,k.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:k.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!Z(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,kr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=this.getForwardBufferDuration(u),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,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),s=this.parsedInitData.get(t.id);(0,k.assertNonNullable)(i,"No init buffer for starting representation"),(0,k.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=(0,k.abortable)(this.destroyAbortController.signal,function(e,t=!1){return oe(this,null,function*(){if(!Z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,k.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,k.isNullable)(s)||(0,k.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,k.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,k.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new Pi(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=(0,k.abortable)(this.destroyAbortController.signal,function(e,t=!1){return oe(this,null,function*(){if(!Z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,k.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,k.isNullable)(s)||(0,k.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,k.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,k.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Pi(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,k.abortable)(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){var o,l;let t=(o=(0,Nn.default)(e,d=>d.representations))!=null?o:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(h=>h.id===d);c&&this.representations.set(d,c);let f=this.representations.get(d);if(!f||!ot(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,k.assertNonNullable)(r);let s=this.segments.get(i);(0,k.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,k.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let 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));var d;this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new fe,(0,k.abortable)(this.switchAbortController.signal,function(i,r=!1){return oe(this,null,function*(){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,k.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if((0,k.isNullable)(u)||(0,k.isNullable)(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),(0,k.assertNonNullable)(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!Z(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();(0,k.isNonNullable)(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(){!(0,k.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return R(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new fe,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if((0,k.isNullable)(e)||(0,k.isNullable)(this.downloadingRepresentationId)||(0,k.isNullable)(this.playingRepresentationId)||(0,k.isNullable)(this.sourceBuffer)||!Z(this.mediaSource,this.sourceBuffer)||(0,k.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,k.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);(0,k.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=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&&(s=c)}if(isFinite(this.bufferLimit)&&kr(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(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Fn.default)(o,r))d="high";else{let c=(0,ji.default)(o,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,ji.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;(0,k.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Nn.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,Nn.default)(e==null?void 0:e.streams[this.kind],u=>u.representations))!=null?i:[];if(![...this.segments.values()].every(u=>!u.length))for(let u of t){if(!u||!ot(u.segmentReference))return;let o=u.segmentReference.segments.map(p=>Q(C({},p),{status:"none",size:void 0})),l=100,d=(r=this.segments.get(u.id))!=null?r:[],c=(n=(s=(0,ji.default)(d,-1))==null?void 0:s.time.to)!=null?n:0,f=o==null?void 0:o.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(u.segmentReference);this.segments.set(u.id,p)}else{let p=o.slice(f+1);this.segments.set(u.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,k.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,ji.default)(e,-1))==null?void 0:t.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!ot(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],u=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(u&&!isFinite(u.time.to)&&(u.time.to=e.time.to,t=u.time.to-u.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),d=At(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,u;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(o=>o.time.from<=e&&o.time.to>=e);return(u=r==null?void 0:r.time.from)!=null?u:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&_t&&_t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&_t&&_t(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:f,time:{from:p,to:h}},b)=>{let v=p<=i&&h>=i,S=p>i||v||b===0&&i===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&p<=i+T||r<T&&h-p>=T||h<=i+T;return(f==="none"||f==="partially_ejected"&&S&&E&&this.sourceBuffer&&Z(this.mediaSource,this.sourceBuffer)&&!(Ue(this.sourceBuffer.buffered,p)&&Ue(this.sourceBuffer.buffered,h)))&&S&&E});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let f=s;f<n.length&&(u<=d||o<=c);f++){let p=n[f];if(u+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}loadSegments(e,t,i="auto"){return R(this,null,function*(){ot(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return R(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(yield(0,k.abortable)(u,function(){return oe(this,null,function*(){let d=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,k.now)(),!d)return;let c=new DataView(d),f=Ot(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(c,b)}o&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,u);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(c);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Ft(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())ot(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return R(this,null,function*(){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&&(yield(0,k.abortable)(n,function(){return oe(this,null,function*(){let o=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),(0,k.fromEvent)(window,"online").pipe((0,k.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,k.now)(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Ft(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(ot(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,ji.default)(e,0).byte.from,to:(0,ji.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(u,o)=>R(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,k.now)(),yield 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:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!ot(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,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,k.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Fn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!Z(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){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Ot(u.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",o.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(u){return R(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Z(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let l of this.activeSegments){let{segment:d}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let c=d.byte.from-i,f=d.byte.to-i,p=f-c+1,h=c<r,b=f<=r;if(!h)continue;let v=Ot(o.mime);if(d.status==="downloading"&&b){d.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,p);(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-c),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),T=l.loadedBytes===p?S:v.parseFeedableSegmentChunk(S);T!=null&&T.byteLength&&(d.status="partially_fed",l.feedingBytes+=T.byteLength,(yield this.sourceBufferTaskQueue.append(T,s))&&!s.aborted?(l.fedBytes+=T.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!((0,k.isNullable)(this.sourceBuffer)||!Z(this.mediaSource,this.sourceBuffer))){!this.isLive&&X.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ue(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ue(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ic(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Rr(()=>(0,Wv.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return R(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,k.abortable)(this.destroyAbortController.signal,function(){return oe(this,null,function*(){let u=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ot(e.mime),r)).then(u=>R(this,null,function*(){if(!u)return;let{init:o,dataView:l,segments:d}=u,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let f=d;this.isLive&&ot(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),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:k.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,n),n})}dropBuffer(){return R(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return R(this,null,function*(){if(!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,k.isNullable)(e))return!1;let r=[],s=0,n=o=>{o.sort((d,c)=>d.from-c.from);let l=[o[0]];for(let d=1;d<o.length;d++){let{from:c,to:f}=o[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,f):l.push(o[d])}return l},u=o=>{var d;if(s>=t)return r;r.push(C({},o.time)),r=n(r);let l=ic(o)?(d=o.size)!=null?d:0:o.byte.to-o.byte.from;s+=l};for(let o of this.segments.values())for(let l of o){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"&&u(l)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let l=this.sourceBuffer.buffered.start(o)*1e3,d=this.sourceBuffer.buffered.end(o)*1e3,c=0;for(let f of this.segments.values())for(let p of f)(0,Fn.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let f={time:{from:l,to:d},url:"",status:"none"};u(f)}}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 d of l)d.time.from>=e+o&&d.status==="fed"&&u(d)}return r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1})}abortBuffer(){return R(this,null,function*(){if(!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,k.isNullable)(e)?0:Be(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));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||!Z(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Rr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:k.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,k.isNullable)(this.sourceBuffer)||!Z(this.mediaSource,this.sourceBuffer)||(0,k.isNullable)(this.playingRepresentationId))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(d=>d.from-t<=n&&d.to+t>=u),l=e.filter(d=>n>=d.from&&n<d.to-t||u>d.from+t&&u<=d.to);o||(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:k.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var gi=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Un=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};var re=require("@vkontakte/videoplayer-shared/es2015");var qn=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Hn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new re.ValueSubject(void 0);this.lastConnectionReused$=new re.ValueSubject(void 0);this.lastRequestFirstBytes$=new re.ValueSubject(void 0);this.recoverableError$=new re.Subject;this.error$=new re.Subject;this.abortAllController=new fe;this.subscription=new re.Subscription;this.fetchManifest=(0,re.abortable)(this.abortAllController.signal,function(e){return oe(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=gi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=qn(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(jn);return r?(t.log("success",(0,re.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,re.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,re.abortable)(this.abortAllController.signal,function(d){return oe(this,arguments,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}={}){var le,he,F;let c=e,f=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{f.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let $=new URL(c,location.href);$.searchParams.append("bytes",`${i.from}-${i.to}`),c=$.toString();break}default:(0,re.assertNever)(t)}this.requestQuic&&(c=gi(c));let h=this.abortAllController.signal,b;if(n){let $=new fe;if(b=(0,re.merge)((0,re.fromEvent)(this.abortAllController.signal,"abort"),(0,re.fromEvent)(n,"abort")).subscribe(()=>{try{$.abort()}catch(P){jn(P)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(P){jn(P)}h=$.signal}let v=(0,re.now)();p.log("startRequest",(0,re.flattenObject)({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:v}));let S=yield this.doFetch(c,{priority:s,headers:f,signal:h}),T=(0,re.now)();if(!S)return p.error("error",{message:"No response in request"}),p.end(),b==null||b.unsubscribe(),null;if((le=this.throughputEstimator)==null||le.addRawRtt(T-v),!S.ok||!S.body){b==null||b.unsubscribe();let $=`Fetch error ${S.status}: ${S.statusText}`;return p.error("error",{message:$}),p.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!u){b==null||b.unsubscribe();let $=(0,re.now)(),P={requestStartedAt:v,requestEndedAt:$,duration:$-v};return p.log("endRequest",(0,re.flattenObject)(P)),p.end(),S.arrayBuffer()}let E=S.body;if(u){let $;[E,$]=S.body.tee(),(he=this.throughputEstimator)==null||he.trackStream($,o)}let w=E.getReader(),A,O=parseInt((F=S.headers.get("content-length"))!=null?F:"",10);Number.isFinite(O)&&(A=O),!A&&i&&(A=i.to-i.from+1);let H=0,_=A?new Uint8Array(A):new Uint8Array(0),U=!1,M=$=>{b==null||b.unsubscribe(),U=!0,jn($)},G=(0,re.abortable)(h,function(B){return oe(this,arguments,function*({done:$,value:P}){if(H===0&&this.lastRequestFirstBytes$.next((0,re.now)()-v),h.aborted){b==null||b.unsubscribe();return}if(!$&&P){if(l&&A)_.set(P,H),H+=P.byteLength;else{let N=new Uint8Array(_.length+P.length);N.set(_),N.set(P,_.length),_=N,H+=P.byteLength}r==null||r(new DataView(_.buffer),H),yield w==null?void 0:w.read().then(G,M)}})}.bind(this));yield w==null?void 0:w.read().then(G,M),b==null||b.unsubscribe();let q=(0,re.now)(),Y={failed:U,requestStartedAt:v,requestEndedAt:q,duration:q-v};return U?(p.error("endRequest",(0,re.flattenObject)(Y)),p.end(),null):(p.log("endRequest",(0,re.flattenObject)(Y)),p.end(),_.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,re.abortable)(this.abortAllController.signal,function(e,t,i){return oe(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!c)return null;let f=new DataView(c,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(c,h.from-n,h.to-h.from+1);else{let T=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!T)return null;b=new DataView(T)}let v=t.parseSegments(b,p,h);return{init:p,dataView:new DataView(c),segments:v}})}.bind(this));this.fetchTemplateRepresentation=(0,re.abortable)(this.abortAllController.signal,function(e,t){return oe(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>Q(C({},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}=Un(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return R(this,null,function*(){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,re.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return R(this,null,function*(){let i=yield mt(e,t);if(i.ok)return i;let r=yield i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:re.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:re.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:re.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:re.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:re.ErrorCategory.FATAL})}})}},jn=a=>{if(!Ft(a))throw a};var Kt=(a,e,t)=>t*e+(1-t)*a,ac=(a,e)=>a.reduce((t,i)=>t+i,0)/e,zv=(a,e,t,i)=>{let r=0,s=t,n=ac(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};var as=require("@vkontakte/videoplayer-shared/es2015");var Si=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new as.ValueSubject(e.initial),this.debounced$=new as.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new He(`raw_${t}`),this.smoothedSeries$=new He(`smoothed_${t}`),this.reportedSeries$=new He(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=kt(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)&&((0,as.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Qn=class extends Si{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Kt(this.slow,e,this.params.emaAlphaSlow),this.fast=Kt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Gn=class extends Si{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ac(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Kt(this.emaSmoothed,e,this.params.emaAlpha);let i=zv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Wn=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?Kt(this.smoothed,t,this.params.emaAlpha):t}};var Xt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Qn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Gn({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 Wn(C({initial:e,label:"liveEdgeDelay"},t))}};var Cr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var zn=require("@vkontakte/videoplayer-shared/es2015");var ss=class a{constructor(e,t){this.currentRepresentation$=new zn.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,zn.isNullable)(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,u=s.segments[0].time.from,o=s.segments[n-1].time.to;if(e<u||e>o)continue;let l=s.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(Q(C({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ot(t.segmentReference))}};var Kn=J(xt(),1),Xn=require("@vkontakte/videoplayer-shared/es2015");var Yn=a=>{let{webmDecodingInfo:e}=X.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:(0,Xn.assertNever)(a)}return[t,i]},Yv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Yn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(X.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",...Yn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Yn(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Yn(a),...r,"HLS","HLS_ONDEMAND"];default:(0,Xn.assertNever)(e)}return X.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Kv=({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=X.device.isMac&&X.browser.isSafari;if(X.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:(0,Xn.assertNever)(a)}else X.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"]},sc=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Jn=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Kn.default)(t.value.split("."),0)}for(let t of a){let i=(0,Kn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Kn.default)(e.value.split("."),0)};var m$=["timeupdate","progress","play","seeked","stalled","waiting"],b$=["timeupdate","progress","loadeddata","playing","seeked"];var Zn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new I.Subscription;this.representationSubscription=new I.Subscription;this.state$=new ne("none");this.currentVideoRepresentation$=new I.ValueSubject(void 0);this.currentVideoRepresentationInit$=new I.ValueSubject(void 0);this.currentAudioRepresentation$=new I.ValueSubject(void 0);this.currentVideoSegmentLength$=new I.ValueSubject(0);this.currentAudioSegmentLength$=new I.ValueSubject(0);this.error$=new I.Subject;this.lastConnectionType$=new I.ValueSubject(void 0);this.lastConnectionReused$=new I.ValueSubject(void 0);this.lastRequestFirstBytes$=new I.ValueSubject(void 0);this.currentLiveTextRepresentation$=new I.ValueSubject(null);this.isLive$=new I.ValueSubject(!1);this.isActiveLive$=new I.ValueSubject(!1);this.isLowLatency$=new I.ValueSubject(!1);this.liveDuration$=new I.ValueSubject(0);this.liveSeekableDuration$=new I.ValueSubject(0);this.liveAvailabilityStartTime$=new I.ValueSubject(0);this.liveStreamStatus$=new I.ValueSubject(void 0);this.bufferLength$=new I.ValueSubject(0);this.liveLatency$=new I.ValueSubject(void 0);this.liveLoadBufferLength$=new I.ValueSubject(0);this.livePositionFromPlayer$=new I.ValueSubject(0);this.currentStallDuration$=new I.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new I.ValueSubject(0);this.fetcherRecoverableError$=new I.Subject;this.fetcherError$=new I.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new I.Subject;this.gapWatchdogActive=!1;this.destroyController=new fe;this.initManifest=(0,I.abortable)(this.destroyController.signal,function(e,t,i){return oe(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Re(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:I.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,I.abortable)(this.destroyController.signal,function(){return oe(this,null,function*(){var n,u;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=On(e!=null?e:"",this.manifestUrlString)}catch(o){let l=(n=Vn(e))!=null?n:{id:"ManifestParsing",category:I.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,d)=>{var c,f,p,h;return!!((f=(c=this.element)==null?void 0:c.canPlayType)!=null&&f.call(c,l)&&((h=(p=st())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${d}"`))||o==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,f=((u=t.duration)!=null?u:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let o of["video","audio"]){let d=t.streams[o].filter(({mime:p,codecs:h})=>i(o,p,h)),c=new Set(d.map(({codecs:p})=>p)),f=Jn(c);if(f&&(r[o]=d.filter(({codecs:p})=>p.startsWith(f))),o==="video"){let p=this.tuning.preferHDR,h=r.video.some(v=>v.hdr),b=r.video.some(v=>!v.hdr);X.display.isHDR&&p&&h?r.video=r.video.filter(v=>v.hdr):b&&(r.video=r.video.filter(v=>!v.hdr))}}let s=Q(C({},t),{streams:r});return this.tracer.log("updateManifestEnd",(0,I.flattenObject)(s)),s})}.bind(this));this.initRepresentations=(0,I.abortable)(this.destroyController.signal,function(e,t,i){return oe(this,null,function*(){var f;this.tracer.log("initRepresentationsStart",(0,I.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,I.assertNonNullable)(this.manifest),(0,I.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,I.fromEvent)(p,"error").pipe((0,I.filter)(h=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?vn():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&yr())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},u=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new rs("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],(0,I.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,b)=>[...h,...b.representations],[]);this.audioBufferManager=new rs("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}ss.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ss(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=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,I.merge)(...b$.map(p=>(0,I.fromEvent)(this.element,p))).pipe((0,I.map)(p=>this.element?Be(this.element.buffered,this.element.currentTime*1e3):0),(0,I.filterChanged)(),(0,I.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,I.merge)((0,I.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,I.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,I.now)())),this.subscription.add((0,I.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,I.interval)(1e3).subscribe(h=>{let b=di(this.manifestUrlString,2);this.manifestUrlString=Re(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,I.fromEvent)(this.element,"play").subscribe(h=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add((0,I.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,I.map)(({isActiveLive:h,isLowLatency:b})=>h&&b),(0,I.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Cr(this.element,1)})),this.representationSubscription.add((0,I.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,I.filter)(({bufferLength:h,isActiveLive:b,isLowLatency:v})=>b&&v&&!!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 b=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,I.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,I.filter)(({isLive:h})=>h),(0,I.filterChanged)((h,b)=>b.bufferLength<h.bufferLength),(0,I.map)(({rtt:h,bufferLength:b,segmentServerLatency:v})=>{let S=di(this.manifestUrlString,2);return(h/2+b+v+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,I.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:b,isLowLatency:v})=>{if(!v||!b)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,T=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,E=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,w=h-S;if(this.isManualDecreasePlaybackInLive())return;let A=1;Math.abs(w)>T&&(A=1+Math.sign(w)*E),Cr(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var v,S;let b=0;if(h){let T=((S=(v=this.element)==null?void 0:v.currentTime)!=null?S:0)*1e3;b=Math.min(...this.bufferManagers.map(w=>{var A,O;return(O=(A=w.getLiveSegmentsToLoadState(this.manifest))==null?void 0:A.to)!=null?O:T}))-T}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add((0,I.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,I.throttle)(1e3)).subscribe(v=>R(this,[v],function*({liveLoadBufferLength:h,bufferLength:b}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,T=di(this.manifestUrlString,2),E=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,w=Math.min(E,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),A=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,O=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,H=isFinite(h)?h:b,_=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),U=E<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(U);let M="none";if(_?M="active_low_latency":this.isLowLatency$.getValue()&&U?(this.bufferManagers.forEach(G=>G.proceedLowLatencyLive()),M="active_low_latency"):T!==0&&H<w?M="live_forward_buffering":H<w+O&&(M="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let G=p-(w+A),q=this.normolizeLiveOffset(Math.trunc(T+G/S)),Y=Math.abs(q-T),le=0;!h||Y<=this.tuning.dashCmafLive.offsetCalculationError?le=T:q>0&&Y>this.tuning.dashCmafLive.offsetCalculationError&&(le=q),this.manifestUrlString=Re(this.manifestUrlString,le,2)}(M==="live_with_target_offset"||M==="live_forward_buffering")&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:I.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,I.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,I.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=(0,I.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,I.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=(0,I.combine)({allBuffersFull:l,someBufferEnded:d}).pipe((0,I.filterChanged)(),(0,I.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,I.filter)(p=>p));if(this.representationSubscription.add((0,I.merge)(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,I.merge)(...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=>{var b;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var v;if(((v=this.source)==null?void 0:v.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(b=this.source)==null||b.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,oc.default)((0,oc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let b=[];return h.duration&&b.push(h.duration),ot(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&b.push(h.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,I.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,I.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:I.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Hn({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=Xt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,C({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return R(this,null,function*(){var r,s,n;(0,I.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,I.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Re(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){(0,I.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,I.merge)(...m$.map(e=>(0,I.fromEvent)(this.element,e)),(0,I.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:I.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,I.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,I.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ue(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,h,b,v,S,T,E,w,A,O,H;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=(0,I.now)(),n=100,u=(b=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(u);let o=(S=(v=this.audioBufferManager)==null?void 0:v.lastDataObtainedTimestamp)!=null?S:0,l=(E=(T=this.videoBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?E:0,d=(A=(w=this.audioBufferManager)==null?void 0:w.getForwardBufferDuration())!=null?A:0,c=l<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,f=this.audioBufferManager&&d<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||f)&&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 _=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(_).catch(U=>{this.error$.next({id:"stallIntervalCallback",category:I.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:U})}),r.liveLastOffset=_}else{let _=this.element.currentTime*1e3;(O=this.videoBufferManager)==null||O.maintain(_),(H=this.audioBufferManager)==null||H.maintain(_),r.position=_}this.tracer.log("stallIntervalCallback",(0,I.flattenObject)(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,I.interval)(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:I.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return R(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return R(this,null,function*(){var r,s,n,u,o;(0,I.assertNonNullable)(this.element),(0,I.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ue(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(u=this.audioBufferManager)==null?void 0:u.abort()])),!((0,I.isNullable)(this.element)||(0,I.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(o=this.audioBufferManager)==null||o.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,I.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,I.isNonNullable)(this.element)&&(0,I.isNonNullable)(this.source)&&(0,I.isNonNullable)(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,I.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){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}updateLive(){return R(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=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=Q(C({},i),{gapEnds:s,jumpTo:u,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,I.flattenObject)(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var eo=class{constructor(e,t){this.fov=e,this.orientation=t}};var to=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/kt(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed=C({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,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*kt(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 Zv=`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 Ny=`#ifdef GL_ES
135
+ `;var ey=`#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 ds=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 wu(this.params.fov,this.params.orientation),this.cameraRotationManager=new Au(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(Fy,this.gl.VERTEX_SHADER),i=this.createShader(Ny,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,f=t+r;return[a,n,o,u,l,d,c,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Ae=require("@vkontakte/videoplayer-shared/es2015");var Pu="stalls_manager_metrics",Cd="stalls_manager_abr_params",Uy="stalls_manager_default_tuning_abr_params",Vd=class{constructor(){this.isSeeked$=new Ae.ValueSubject(!1);this.isBuffering$=new Ae.ValueSubject(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Ae.Subscription;this.severeStallOccurred$=new Ae.ValueSubject(!1)}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(Cd):{};return P(P({},this.abrParams),e)}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,Ae.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=((0,Ae.now)()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}=P({},this.getStoredData(Uy)),{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}=P({},this.abrParams);this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(Cd),this.setStoredData(Uy,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Pu,"[]");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(Pu,[]),this.setStoredData(Cd,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="{}"){var i;return JSON.parse((i=Ae.safeStorage.get(e))!=null?i:t)}setStoredData(e,t){Ae.safeStorage.set(e,JSON.stringify(t))}removeStoredData(e){Ae.safeStorage.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Pu,"[]"),r=t/e,a=i.length?Oi(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(Pu,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe((0,Ae.once)()).subscribe(t=>this.providerStartWatchingTimestamp=(0,Ae.now)())),this.subscription.add(this.currentStallDuration$.pipe((0,Ae.filterChanged)()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if((0,Ae.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=(0,Ae.now)(),c=r&&this.currentStallsCount>=r,f=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||f)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Ae.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&(0,Ae.now)()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},ku=Vd;var xt=require("@vkontakte/videoplayer-shared/es2015"),Ru=class{constructor(){this.subscription=new xt.Subscription;this.pipSize$=new xt.ValueSubject(void 0);this.videoSize$=new xt.ValueSubject(void 0);this.elementSize$=new xt.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=xt.noop}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add((0,xt.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,xt.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,xt.map)(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Ar=class{constructor(e){this.subscription=new re.Subscription;this.videoState=new ce("stopped");this.observableVideo=null;this.droppedFramesManager=new ts;this.stallsManager=new ku;this.elementSizeManager=new Ru;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ji;this.audioTrackSwitchHistory=new Ji;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),q(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"),q(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&q(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&q(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&q(this.params.desiredState.playbackState,"paused");return;default:return(0,re.assertNever)(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new ds(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ut(e.source.url),this.params=e,this.video=St(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(st(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 Eu({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;(0,re.isNullable)(this.observableVideo)&&(this.observableVideo=Tt(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:re.ErrorCategory.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((0,re.filter)(l=>!!l.length),(0,re.once)()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,re.map)(l=>l.to.state!=="none"),(0,re.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,re.filter)(re.isNonNullable),(0,re.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,re.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ci(this.video,t.isLooped,r)),this.subscription.add(yt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Nt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(qt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),q(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),q(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,re.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let p of d.audio){f.push(Ed(p));let h=[];for(let b of p.representations){let S=Ey(b);h.push(S),this.audioTracksMap.set(S,{stream:p,representation:b})}this.audioStreamsMap.set(p,h)}this.params.output.availableAudioStreams$.next(f)}let c=[];for(let f of d.video){c.push(wd(f));let p=[];for(let h of f.representations){let b=xy(F(P({},h),{streamId:f.id}));b&&(p.push(b),this.videoTracksMap.set(b,{stream:f,representation:h}))}this.videoStreamsMap.set(f,p)}this.params.output.availableVideoStreams$.next(c);for(let f of d.text)for(let p of f.representations){let h=wy(f,p);this.textTracksMap.set(h,{stream:f,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add((0,re.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,re.fromEvent)(this.video,"progress")).pipe((0,re.filter)(()=>this.videoTracksMap.size>0)).subscribe(()=>k(this,null,function*(){let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,qy.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[f,p]=c,h=[...this.videoTracksMap.keys()].find(S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===f.id});(0,re.isNonNullable)(h)&&(this.stallsManager.lastVideoTrackSelected=h);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")yield this.player.initRepresentations(f.id,p==null?void 0:p.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",f.id),p){let S=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",p.id,S)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,re.filterChanged)()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:f}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(wd(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,re.filterChanged)()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:f}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Ed(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,re.map)(({to:l})=>l==="ready"),(0,re.filterChanged)());this.subscription.add((0,re.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,re.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add((0,re.merge)(o,this.player.state$.stateChangeEnded$,(0,re.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,re.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var L,Q,O,J,G,de,$,_,V,B,z,Ee,et;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ra:ka,t=this.params.tuning.useNewAutoSelectVideoTrack?su:ru,i=this.params.tuning.useNewAutoSelectVideoTrack?di:iu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(L=r.videoTrack.getState())==null?void 0:L.id,l=[...this.videoTracksMap.keys()].find(({id:ve})=>ve===o),d=a.currentVideoTrack$.getValue(),c=((J=(O=r.videoStream.getState())!=null?O:l&&((Q=this.videoTracksMap.get(l))==null?void 0:Q.stream))!=null?J:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let f=[...this.videoStreamsMap.keys()].find(({id:ve})=>ve===c.id),p=f&&this.videoStreamsMap.get(f);if(!p)return;let h=Ze(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 S=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,v=Math.min(h/Math.min(b,S||1/0),1),y=(G=r.audioStream.getState())!=null?G:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,x=(de=[...this.audioStreamsMap.keys()].find(({id:ve})=>ve===(y==null?void 0:y.id)))!=null?de:this.audioStreamsMap.keys().next().value,E=0;if(x){if(l&&!n){let ve=e(l,p,($=this.audioStreamsMap.get(x))!=null?$:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);E=Math.max(E,(_=ve==null?void 0:ve.bitrate)!=null?_:-1/0)}if(d){let ve=e(d,p,(V=this.audioStreamsMap.get(x))!=null?V:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);E=Math.max(E,(B=ve==null?void 0:ve.bitrate)!=null?B:-1/0)}}let A=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:E,forwardBufferHealth:v,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}),D=n?A!=null?A:l:l!=null?l:A,j=x&&t(D,p,(z=this.audioStreamsMap.get(x))!=null?z:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),H=(Ee=this.videoTracksMap.get(D))==null?void 0:Ee.representation,N=j&&((et=this.audioTracksMap.get(j))==null?void 0:et.representation);if(H&&N)return[H,N];if(H&&!N&&this.audioTracksMap.size===0)return[H,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){It(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),q(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),vt(this.video),this.tracer.end()}};var Sn=class extends Ar{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Ie=require("@vkontakte/videoplayer-shared/es2015");var vn=class extends Ar{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 Ie.ValueSubject(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe((0,Ie.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,Ie.combine)({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Ie.map)(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,Ie.filter)(o=>(0,Ie.isNonNullable)(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add((0,Ie.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,Ie.merge)(i.playbackRateState$,new Ie.ValueSubject(1))}).pipe((0,Ie.filter)(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||(0,Ie.isNullable)(l)||(e=o-l)})).add((0,Ie.combine)({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,Ie.merge)(i.playbackRateState$,new Ie.ValueSubject(1))}).pipe((0,Ie.filterChanged)((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||(0,Ie.isNullable)(o)||(0,Ie.isNullable)(u))return;let f=-1*(u-o-e);t.position$.next(Math.min(f,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Ay(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 se=require("@vkontakte/videoplayer-shared/es2015");var Wd=Z(Oa(),1);var T=require("@vkontakte/videoplayer-shared/es2015");var Du=Z(Dt(),1),hs=Z(ii(),1),Cu=Z(Oa(),1);var cT=Z(qo(),1);var rr=require("@vkontakte/videoplayer-shared/es2015");var uB=18,jy=!1;try{jy=te.browser.isSafari&&!!te.browser.safariVersion&&te.browser.safariVersion<=uB}catch(s){console.error(s)}var Od=class{constructor(e){this.bufferFull$=new rr.Subject;this.error$=new rr.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:rr.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return k(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return k(this,null,function*(){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()})})}abort(e){return k(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};jy&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:rr.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,rr.assertNever)(t)}}},Hy=Od;var M=require("@vkontakte/videoplayer-shared/es2015");var be=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 ps=class extends be{};var yn=class extends be{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 Tn=class extends be{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 In=class extends be{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pe=class extends be{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var xn=class extends Pe{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 En=class extends be{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wn=class extends be{constructor(e,t){super(e,t),this.data=this.content}};var Pr=class extends Pe{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 An=class extends be{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pn=class extends be{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var kn=class extends Pe{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 Rn=class extends Pe{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Mn=class extends Pe{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Ln=class extends be{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Bn=class extends Pe{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 $n=class extends be{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Dn=class extends be{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Cn=class extends Pe{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Vn=class extends be{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var On=class extends Pe{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 _n=class extends Pe{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 Fn=class extends Pe{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 Nn=class extends be{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Un=class extends Pe{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 qn=class extends be{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var cB={ftyp:Tn,moov:In,mvhd:xn,moof:En,mdat:wn,sidx:Pr,trak:An,mdia:Ln,mfhd:Cn,tkhd:Bn,traf:Vn,tfhd:On,tfdt:_n,trun:Fn,minf:$n,sv3d:Pn,st3d:kn,prhd:Rn,proj:Dn,equi:Mn,uuid:yn,stbl:Nn,stsd:Un,avc1:qn,unknown:ps},Fi=class s{constructor(e={}){this.options=P({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=cB[e];return i?new i(t,new s):new ps(t,new s)}};var sr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var pB=new TextDecoder("ascii"),hB=s=>pB.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",fB=s=>{let e=new Pr(s,new Fi),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})},mB=(s,e)=>{let i=new Fi().parse(s),r=new sr(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)},bB=s=>{let t=new Fi().parse(s),i=new sr(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},gB=s=>{var r;let t=new Fi().parse(s);return(r=new sr(t).find("sidx"))==null?void 0:r.timescale},SB=(s,e)=>{let i=new Fi().parse(s),a=new sr(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,f)=>c+f,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},vB=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 Fi().parse(s),r=new sr(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},zy={validateData:hB,parseInit:vB,getIndexRange:()=>{},parseSegments:fB,parseFeedableSegmentChunk:mB,getChunkEndTime:SB,getServerLatencyTimestamps:bB,getTimescaleFromIndex:gB};var Hn=Z(Dt(),1),Ni=require("@vkontakte/videoplayer-shared/es2015");var Gy=require("@vkontakte/videoplayer-shared/es2015");var Qy={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"}},Wy=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=jn(s,t),r=i in Qy,a=r?Qy[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=jn(u),c=l*pt(2,(o-1)*8)+d,f=t+o,p;return f+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:f,tagSize:f+c,value:p,valueSize:c}},jn=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*pt(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*pt(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*pt(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},si=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return jn(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,Gy.assertNever)(e)}},kr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Wy(i);if(!e(r))return;r.type==="master"&&kr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Yy=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Wy(s);return kr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=si(o,n):a===17026?t=si(o,n):a===17029&&(i=si(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Ky=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],yB=[231,22612,22743,167,171,163,160,175],TB=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return kr(s,({tag:f,type:p,value:h,valueSize:b})=>{if(f===21419){let S=si(h,p);l=jn(S)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+b):f===357149030?a=!0:f===290298740?n=!0:f===2807729?i=si(h,p):f===17545?r=si(h,p):f===21420&&l===475249515?u=si(h,p):f===374648427?kr(h,({tag:S,type:v,value:y})=>S===30321?(d=si(y,v)===1,!1):!0):a&&n&&(0,Hn.default)(Ky,f)&&(o=!0),!o}),(0,Ni.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Ni.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Ni.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},IB=s=>{if((0,Ni.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},xB=(s,e)=>{let t=!1,i=!1,r=o=>(0,Ni.isNonNullable)(o.time)&&(0,Ni.isNonNullable)(o.position),a=[],n;return kr(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=si(l,u));break;case 183:break;case 241:n&&(n.position=si(l,u));break;default:t&&(0,Hn.default)(Ky,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}}})},EB=s=>{let e=0,t=!1;try{kr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Hn.default)(yB,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,Hn.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Xy={validateData:Yy,parseInit:TB,getIndexRange:IB,parseSegments:xB,parseFeedableSegmentChunk:EB};var zn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Xy;case"mp4":return zy}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Hd=Z(yd(),1),nT=Z(mr(),1),oT=Z(Td(),1),uT=Z(ii(),1),zd=Z(Tr(),1);var Gn=require("@vkontakte/videoplayer-shared/es2015");var Jy=s=>{var e;try{let t=wB(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function wB(){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 Nd=Z(ii(),1);var Mu=require("@vkontakte/videoplayer-shared/es2015"),Zy=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Xi(a):void 0)!=null?u:(0,Mu.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},eT=({id:s,bitrate:e})=>({id:s,bitrate:e}),tT=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),iT=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Ud=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Nd.default)(i.split("."),0),isDefault:r}),qd=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Nd.default)(r.split("."),0)}),jd=s=>"url"in s,gt=s=>s.type==="template",Qn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var rT=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},Rr=(s,e)=>{for(let t of s)if(e(t))return t;return null},sT=s=>{let e=!1,t=(0,Mu.throttleFn)(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var aT=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Ui=(s,e)=>{let t=s;t=(0,Hd.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,nT.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Hd.default)(t,n,(o,u)=>(0,Gn.isNullable)(a)?o:(0,Gn.isNullable)(u)?a:(0,oT.default)(a,parseInt(u,10),"0"))}return t},lT=(s,e)=>{var N,L,Q,O,J,G,de,$,_,V,B,z,Ee,et,ve,fe,Fe,Ne,Ue,tt,Ft,zt,ai,mi,zi,ms,bs,gs,Ss,vs,ys,Ts,Is,xs,Es,ws,As,Ps,ks,Rs,Ms,Ls,Bs,$s,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,zs,Qs,Gs,Ws,Ys,Ks;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(Re=>{var Y,nt;return(nt=(Y=Re.textContent)==null?void 0:Y.trim())!=null?nt:""}),o=(N=(0,uT.default)(n,0))!=null?N:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],f=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let v,y=a.getAttribute("mediaPresentationDuration"),x=[...a.getElementsByTagName("Period")],E=x.reduce((Re,Y)=>F(P({},Re),{[Y.id]:Y.children}),{}),A=x.reduce((Re,Y)=>F(P({},Re),{[Y.id]:Y.getAttribute("duration")}),{});y?v=aT(y):(0,zd.default)(A).filter(Re=>Re).length&&!u?v=(0,zd.default)(A).reduce((Re,Y)=>{var nt;return Re+((nt=aT(Y))!=null?nt:0)},0):b&&(v=parseInt(b,10));let D=0,j=(Q=(L=a.getAttribute("profiles"))==null?void 0:L.split(","))!=null?Q:[];for(let Re of x.map(Y=>Y.id))for(let Y of E[Re]){let nt=(O=Y.getAttribute("id"))!=null?O:"id"+(D++).toString(10),Qt=(J=Y.getAttribute("mimeType"))!=null?J:"",ar=(G=Y.getAttribute("codecs"))!=null?G:"",nr=(de=Y.getAttribute("contentType"))!=null?de:Qt==null?void 0:Qt.split("/")[0],Qu=(_=($=Y.getAttribute("profiles"))==null?void 0:$.split(","))!=null?_:[],Xs=(B=Jy((V=Y.getAttribute("lang"))!=null?V:""))!=null?B:{},bi=(et=(Ee=(z=Y.querySelector("Label"))==null?void 0:z.textContent)==null?void 0:Ee.trim())!=null?et:void 0,Gu=Y.querySelectorAll("Representation"),Wu=Y.querySelector("SegmentTemplate"),Yu=(fe=(ve=Y.querySelector("Role"))==null?void 0:ve.getAttribute("value"))!=null?fe:void 0,wt=nr,ue={id:nt,language:Xs.language,isDefault:Yu==="main",label:bi,codecs:ar,hdr:wt==="video"&&us(ar),mime:Qt,representations:[]};for(let W of Gu){let ze=(Fe=W.getAttribute("lang"))!=null?Fe:void 0,Gt=(Ue=(Ne=bi!=null?bi:Y.getAttribute("label"))!=null?Ne:W.getAttribute("label"))!=null?Ue:void 0,gi=(zt=(Ft=(tt=W.querySelector("BaseURL"))==null?void 0:tt.textContent)==null?void 0:Ft.trim())!=null?zt:"",ot=new URL(gi||o,e).toString(),Qe=(ai=W.getAttribute("mimeType"))!=null?ai:Qt,Si=(zi=(mi=W.getAttribute("codecs"))!=null?mi:ar)!=null?zi:"",vi;if(nr==="text"){let Ge=W.getAttribute("id")||"",yi=((ms=Xs.privateuse)==null?void 0:ms.includes("x-auto"))||Ge.includes("_auto"),ut=W.querySelector("SegmentTemplate");if(ut){let Wt={representationId:(bs=W.getAttribute("id"))!=null?bs:void 0,bandwidth:(gs=W.getAttribute("bandwidth"))!=null?gs:void 0},Ti=parseInt((Ss=W.getAttribute("bandwidth"))!=null?Ss:"",10)/1e3,Ii=(ys=parseInt((vs=ut.getAttribute("startNumber"))!=null?vs:"",10))!=null?ys:1,At=parseInt((Ts=ut.getAttribute("timescale"))!=null?Ts:"",10),or=(Is=ut.querySelectorAll("SegmentTimeline S"))!=null?Is:[],Pt=ut.getAttribute("media");if(!Pt)continue;let xi=[],Ei=0,wi="",kt=0,Yt=Ii,ge=0;for(let Me of or){let lt=parseInt((xs=Me.getAttribute("d"))!=null?xs:"",10),Te=parseInt((Es=Me.getAttribute("r"))!=null?Es:"",10)||0,We=parseInt((ws=Me.getAttribute("t"))!=null?ws:"",10);ge=Number.isFinite(We)?We:ge;let ct=lt/At*1e3,Ye=ge/At*1e3;for(let De=0;De<Te+1;De++){let Ke=Ui(Pt,F(P({},Wt),{segmentNumber:Yt.toString(10),segmentTime:(ge+De*lt).toString(10)})),Rt=(Ye!=null?Ye:0)+De*ct,Xt=Rt+ct;Yt++,xi.push({time:{from:Rt,to:Xt},url:Ke})}ge+=(Te+1)*lt,Ei+=(Te+1)*ct}kt=ge/At*1e3,wi=Ui(Pt,F(P({},Wt),{segmentNumber:Yt.toString(10),segmentTime:ge.toString(10)}));let Kt={time:{from:kt,to:1/0},url:wi},qe={type:"template",baseUrl:ot,segmentTemplateUrl:Pt,initUrl:"",totalSegmentsDurationMs:Ei,segments:xi,nextSegmentBeyondManifest:Kt,timescale:At};vi={id:Ge,kind:"text",segmentReference:qe,profiles:[],duration:v,bitrate:Ti,mime:"",codecs:"",width:0,height:0,isAuto:yi}}else vi={id:Ge,isAuto:yi,kind:"text",url:ot}}else{let Ge=(Ps=(As=W.getAttribute("contentType"))!=null?As:Qe==null?void 0:Qe.split("/")[0])!=null?Ps:nr,yi=(Rs=(ks=Y.getAttribute("profiles"))==null?void 0:ks.split(","))!=null?Rs:[],ut=parseInt((Ms=W.getAttribute("width"))!=null?Ms:"",10),Wt=parseInt((Ls=W.getAttribute("height"))!=null?Ls:"",10),Ti=parseInt((Bs=W.getAttribute("bandwidth"))!=null?Bs:"",10)/1e3,Ii=($s=W.getAttribute("frameRate"))!=null?$s:"",At=(Ds=W.getAttribute("quality"))!=null?Ds:void 0,or=Ii?cu(Ii):void 0,Pt=(Cs=W.getAttribute("id"))!=null?Cs:"id"+(D++).toString(10),xi=Ge==="video"?`${Wt}p`:Ge==="audio"?`${Ti}Kbps`:Si,Ei=`${Pt}@${xi}`,wi=[...j,...Qu,...yi],kt,Yt=W.querySelector("SegmentBase"),ge=(Vs=W.querySelector("SegmentTemplate"))!=null?Vs:Wu;if(Yt){let qe=(_s=(Os=W.querySelector("SegmentBase Initialization"))==null?void 0:Os.getAttribute("range"))!=null?_s:"",[Me,lt]=qe.split("-").map(Ke=>parseInt(Ke,10)),Te={from:Me,to:lt},We=(Fs=W.querySelector("SegmentBase"))==null?void 0:Fs.getAttribute("indexRange"),[ct,Ye]=We?We.split("-").map(Ke=>parseInt(Ke,10)):[],De=We?{from:ct,to:Ye}:void 0;kt={type:"byteRange",url:ot,initRange:Te,indexRange:De}}else if(ge){let qe={representationId:(Ns=W.getAttribute("id"))!=null?Ns:void 0,bandwidth:(Us=W.getAttribute("bandwidth"))!=null?Us:void 0},Me=parseInt((qs=ge.getAttribute("timescale"))!=null?qs:"",10),lt=(js=ge.getAttribute("initialization"))!=null?js:"",Te=ge.getAttribute("media"),We=(zs=parseInt((Hs=ge.getAttribute("startNumber"))!=null?Hs:"",10))!=null?zs:1,ct=Ui(lt,qe);if(!Te)throw new ReferenceError("No media attribute in SegmentTemplate");let Ye=(Qs=ge.querySelectorAll("SegmentTimeline S"))!=null?Qs:[],De=[],Ke=0,Rt="",Xt=0;if(Ye.length){let Ai=We,Le=0;for(let Mt of Ye){let Ce=parseInt((Gs=Mt.getAttribute("d"))!=null?Gs:"",10),dt=parseInt((Ws=Mt.getAttribute("r"))!=null?Ws:"",10)||0,Pi=parseInt((Ys=Mt.getAttribute("t"))!=null?Ys:"",10);Le=Number.isFinite(Pi)?Pi:Le;let ur=Ce/Me*1e3,lr=Le/Me*1e3;for(let ki=0;ki<dt+1;ki++){let Xu=Ui(Te,F(P({},qe),{segmentNumber:Ai.toString(10),segmentTime:(Le+ki*Ce).toString(10)})),Js=(lr!=null?lr:0)+ki*ur,Ju=Js+ur;Ai++,De.push({time:{from:Js,to:Ju},url:Xu})}Le+=(dt+1)*Ce,Ke+=(dt+1)*ur}Xt=Le/Me*1e3,Rt=Ui(Te,F(P({},qe),{segmentNumber:Ai.toString(10),segmentTime:Le.toString(10)}))}else if((0,Gn.isNonNullable)(v)){let Le=parseInt((Ks=ge.getAttribute("duration"))!=null?Ks:"",10)/Me*1e3,Mt=Math.ceil(v/Le),Ce=0;for(let dt=1;dt<Mt;dt++){let Pi=Ui(Te,F(P({},qe),{segmentNumber:dt.toString(10),segmentTime:Ce.toString(10)}));De.push({time:{from:Ce,to:Ce+Le},url:Pi}),Ce+=Le}Xt=Ce,Rt=Ui(Te,F(P({},qe),{segmentNumber:Mt.toString(10),segmentTime:Ce.toString(10)}))}let Ku={time:{from:Xt,to:1/0},url:Rt};kt={type:"template",baseUrl:ot,segmentTemplateUrl:Te,initUrl:ct,totalSegmentsDurationMs:Ke,segments:De,nextSegmentBeyondManifest:Ku,timescale:Me}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ge||!Qe)continue;let Kt={video:"video",audio:"audio",text:"text"}[Ge];if(!Kt)continue;wt||(wt=Kt),vi={id:Ei,kind:Kt,segmentReference:kt,profiles:wi,duration:v,bitrate:Ti,mime:Qe,codecs:Si,width:ut,height:Wt,fps:or,quality:At}}ue.language||(ue.language=ze),ue.label||(ue.label=Gt),ue.mime||(ue.mime=Qe),ue.codecs||(ue.codecs=Si),ue.hdr||(ue.hdr=wt==="video"&&us(Si)),ue.representations.push(vi)}if(wt){let W=r[wt].find(ze=>ze.id===ue.id);if(W&&ue.representations.every(ze=>gt(ze.segmentReference)))for(let ze of W.representations){let Gt=ue.representations.find(Qe=>Qe.id===ze.id),gi=Gt==null?void 0:Gt.segmentReference,ot=ze.segmentReference;ot.segments.push(...gi.segments),ot.nextSegmentBeyondManifest=gi.nextSegmentBeyondManifest}else r[wt].push(ue)}}return{duration:v,streams:r,baseUrls:n,live:S}};var $u=require("@vkontakte/videoplayer-shared/es2015");var Lu=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var Bu=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new $u.Subscription;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add((0,$u.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!ie(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Lu(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Wn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new M.ValueSubject(0);this.currentLowLatencySegmentLength$=new M.ValueSubject(0);this.currentSegmentLength$=new M.ValueSubject(0);this.onLastSegment$=new M.ValueSubject(!1);this.fullyBuffered$=new M.ValueSubject(!1);this.playingRepresentation$=new M.ValueSubject(void 0);this.playingRepresentationInit$=new M.ValueSubject(void 0);this.error$=new M.Subject;this.gaps=[];this.subscription=new M.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ye;this.switchAbortController=new ye;this.destroyAbortController=new ye;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=(0,M.abortable)(this.destroyAbortController.signal,function(e){return pe(this,null,function*(){let t=this.representations.get(e);(0,M.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Hy(this.sourceBuffer),this.sourceBufferBufferedDiff=new Bu(this.mediaSource,this.sourceBuffer),this.subscription.add((0,M.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add((0,M.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:M.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ie(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,as(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Ze(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,M.assertNonNullable)(i,"No init buffer for starting representation"),(0,M.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))})}.bind(this));this.switchTo=(0,M.abortable)(this.destroyAbortController.signal,function(e,t=!1){return pe(this,null,function*(){if(!ie(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,M.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,M.isNullable)(a)||(0,M.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,M.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!ie(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,M.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new cr(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=(0,M.abortable)(this.destroyAbortController.signal,function(e,t=!1){return pe(this,null,function*(){if(!ie(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,M.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,M.isNullable)(a)||(0,M.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,M.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!ie(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,M.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new cr(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,M.abortable)(this.destroyAbortController.signal,function(e){return pe(this,null,function*(){var u,l;let t=(u=(0,Cu.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(h=>h.id===d);c&&this.representations.set(d,c);let f=this.representations.get(d);if(!f||!gt(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,M.assertNonNullable)(r);let a=this.segments.get(i);(0,M.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,M.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!ie(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ye,(0,M.abortable)(this.switchAbortController.signal,function(i,r=!1){return pe(this,null,function*(){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,M.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,M.isNullable)(o)||(0,M.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,M.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ie(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,M.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!(0,M.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return k(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ye,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if((0,M.isNullable)(e)||(0,M.isNullable)(this.downloadingRepresentationId)||(0,M.isNullable)(this.playingRepresentationId)||(0,M.isNullable)(this.sourceBuffer)||!ie(this.mediaSource,this.sourceBuffer)||(0,M.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,M.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);(0,M.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=Ze(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)&&as(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Ze(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u!=null&&u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Du.default)(u,r))d="high";else{let c=(0,hs.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&Ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,hs.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Ze(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;(0,M.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Cu.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,Cu.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!gt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>F(P({},p),{status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,hs.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,M.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!gt(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=Ui(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&hi&&hi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&hi&&hi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:f,time:{from:p,to:h}},b)=>{let S=p<=i&&h>=i,v=p>i||S||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&p<=i+y||r<y&&h-p>=y||h<=i+y;return(f==="none"||f==="partially_ejected"&&v&&x&&this.sourceBuffer&&ie(this.mediaSource,this.sourceBuffer)&&!(at(this.sourceBuffer.buffered,p)&&at(this.sourceBuffer.buffered,h)))&&v&&x});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 f=a;f<n.length&&(o<=d||u<=c);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}loadSegments(e,t,i="auto"){return k(this,null,function*(){gt(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return k(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,M.abortable)(o,function(){return pe(this,null,function*(){let d=(0,M.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,M.now)(),!d)return;let c=new DataView(d),f=zn(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(c,b)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(c);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Qn(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())gt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return k(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,M.abortable)(n,function(){return pe(this,null,function*(){let u=(0,M.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,M.fromEvent)(window,"online").pipe((0,M.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,M.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Qn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(gt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,hs.default)(e,0).byte.from,to:(0,hs.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>k(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,M.now)(),yield 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:M.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!gt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,M.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:M.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Du.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return k(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!ie(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){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=zn(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return k(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!ie(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let{segment:d}=l,c=d.byte.from-i,f=d.byte.to-i,p=f-c+1,h=c<r,b=f<=r;if(h){if(d.status==="downloading"&&b){d.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,p);(yield this.sourceBufferTaskQueue.append(S,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-c),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===p?S:zn(u.mime).parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(d.status="partially_fed",l.feedingBytes+=v.byteLength,(yield this.sourceBufferTaskQueue.append(v,a))&&!a.aborted?(l.fedBytes+=v.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}}})}onSegmentFullyAppended(e,t){if(!((0,M.isNullable)(this.sourceBuffer)||!ie(this.mediaSource,this.sourceBuffer))){!this.isLive&&te.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(at(this.sourceBuffer.buffered,e.segment.time.from,100)&&at(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:M.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",jd(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=ss(()=>(0,cT.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return k(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,M.abortable)(this.destroyAbortController.signal,function(){return pe(this,null,function*(){let o=(0,M.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,zn(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 f=d;this.isLive&&gt(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),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:M.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return k(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return k(this,null,function*(){if(!this.sourceBuffer||!ie(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,M.isNullable)(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push(P({},o.time));let u=jd(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let f of c)(0,Du.default)(["none","partially_ejected"],f.status)&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.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=rT(r),(yield Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1})}abortBuffer(){return k(this,null,function*(){if(!this.sourceBuffer||!ie(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||!ie(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||!ie(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||!ie(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,M.isNullable)(e)?0:Ze(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!ie(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||!ie(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=ss(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:M.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,M.isNullable)(this.sourceBuffer)||!ie(this.mediaSource,this.sourceBuffer)||(0,M.isNullable)(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Lu(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],f=e[d+1];u||(u=c-t<=n&&f+t>=o),(n>=c&&n<f-t||o>c+t&&o<=f)&&(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:M.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var oe=require("@vkontakte/videoplayer-shared/es2015");var Ou=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new oe.ValueSubject(void 0);this.lastConnectionReused$=new oe.ValueSubject(void 0);this.lastRequestFirstBytes$=new oe.ValueSubject(void 0);this.recoverableError$=new oe.Subject;this.error$=new oe.Subject;this.abortAllController=new ye;this.subscription=new oe.SubscriptionRemovable;this.fetchManifest=(0,oe.abortable)(this.abortAllController.signal,function(e){return pe(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=tr(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=fu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Vu);return r?(t.log("success",(0,oe.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,oe.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,oe.abortable)(this.abortAllController.signal,function(l){return pe(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var J,G,de;let d=e,c=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let $=new URL(d,location.href);$.searchParams.append("bytes",`${i.from}-${i.to}`),d=$.toString();break}default:(0,oe.assertNever)(t)}this.requestQuic&&(d=tr(d));let p=this.abortAllController.signal,h;if(n){let $=new ye;if(h=(0,oe.merge)((0,oe.fromEvent)(this.abortAllController.signal,"abort"),(0,oe.fromEvent)(n,"abort")).subscribe(()=>{try{$.abort()}catch(_){Vu(_)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(_){Vu(_)}p=$.signal}let b=(0,oe.now)();f.log("startRequest",(0,oe.flattenObject)({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:b}));let S=yield this.doFetch(d,{priority:a,headers:c,signal:p}),v=(0,oe.now)();if(!S)return f.error("error",{message:"No response in request"}),f.end(),this.unsubscribeAbortSubscription(h),null;if((J=this.throughputEstimator)==null||J.addRawRtt(v-b),!S.ok||!S.body){this.unsubscribeAbortSubscription(h);let $=`Fetch error ${S.status}: ${S.statusText}`;return f.error("error",{message:$}),f.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let $=(0,oe.now)(),_={requestStartedAt:b,requestEndedAt:$,duration:$-b};return f.log("endRequest",(0,oe.flattenObject)(_)),f.end(),S.arrayBuffer()}let y=S.body;if(o){let $;[y,$]=S.body.tee(),(G=this.throughputEstimator)==null||G.trackStream($,u)}let x=y.getReader(),E,A=parseInt((de=S.headers.get("content-length"))!=null?de:"",10);Number.isFinite(A)&&(E=A),!E&&i&&(E=i.to-i.from+1);let D=0,j=E?new Uint8Array(E):new Uint8Array(0),H=!1,N=$=>{this.unsubscribeAbortSubscription(h),H=!0,Vu($)},L=(0,oe.abortable)(p,function(V){return pe(this,arguments,function*({done:$,value:_}){if(D===0&&this.lastRequestFirstBytes$.next((0,oe.now)()-b),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!$&&_){if(E)j.set(_,D),D+=_.byteLength;else{let B=new Uint8Array(j.length+_.length);B.set(j),B.set(_,j.length),j=B,D+=_.byteLength}r==null||r(new DataView(j.buffer),D),yield x==null?void 0:x.read().then(L,N)}})}.bind(this));yield x==null?void 0:x.read().then(L,N),this.unsubscribeAbortSubscription(h);let Q=(0,oe.now)(),O={failed:H,requestStartedAt:b,requestEndedAt:Q,duration:Q-b};return H?(f.error("endRequest",(0,oe.flattenObject)(O)),f.end(),null):(f.log("endRequest",(0,oe.flattenObject)(O)),f.end(),j.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,oe.abortable)(this.abortAllController.signal,function(e,t,i){return pe(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let f=new DataView(c,r-n,a-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(v=e.indexRange)!=null?v:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,h.from-n,h.to-h.from+1);else{let y=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,p,h);return{init:p,dataView:new DataView(c),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,oe.abortable)(this.abortAllController.signal,function(e,t){return pe(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>F(P({},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}=hu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return k(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,oe.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}doFetch(e,t){return k(this,null,function*(){let i=yield jt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:oe.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:oe.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:oe.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:oe.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:oe.ErrorCategory.FATAL})}})}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Vu=s=>{if(!Qn(s))throw s};var _u=require("@vkontakte/videoplayer-shared/es2015");var Yn=class s{constructor(e,t){this.currentRepresentation$=new _u.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,_u.isNullable)(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(F(P({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&gt(t.segmentReference))}};var kB=["progress","play","seeked","stalled","waiting"],RB=["timeupdate","progress","loadeddata","playing","seeked"];var Fu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new T.Subscription;this.representationSubscription=new T.Subscription;this.state$=new ce("none");this.currentVideoRepresentation$=new T.ValueSubject(void 0);this.currentVideoRepresentationInit$=new T.ValueSubject(void 0);this.currentAudioRepresentation$=new T.ValueSubject(void 0);this.currentVideoSegmentLength$=new T.ValueSubject(0);this.currentAudioSegmentLength$=new T.ValueSubject(0);this.error$=new T.Subject;this.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=new T.ValueSubject(void 0);this.currentLiveTextRepresentation$=new T.ValueSubject(null);this.isLive$=new T.ValueSubject(!1);this.isActiveLive$=new T.ValueSubject(!1);this.isLowLatency$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveSeekableDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(0);this.liveStreamStatus$=new T.ValueSubject(void 0);this.bufferLength$=new T.ValueSubject(0);this.liveLatency$=new T.ValueSubject(void 0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.currentStallDuration$=new T.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new T.ValueSubject(0);this.fetcherRecoverableError$=new T.Subject;this.fetcherError$=new T.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.destroyController=new ye;this.initManifest=(0,T.abortable)(this.destroyController.signal,function(e,t,i){return pe(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Oe(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:T.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,T.abortable)(this.destroyController.signal,function(){return pe(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=lT(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=lu(e))!=null?n:{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,f,p,h;return!!((f=(c=this.element)==null?void 0:c.canPlayType)!=null&&f.call(c,l)&&((h=(p=Vt())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,f=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h)),c=new Set(d.map(({codecs:p})=>p)),f=xu(c);if(f&&(r[u]=d.filter(({codecs:p})=>p.startsWith(f))),u==="video"){let p=this.tuning.preferHDR,h=r.video.some(S=>S.hdr),b=r.video.some(S=>!S.hdr);te.display.isHDR&&p&&h?r.video=r.video.filter(S=>S.hdr):b&&(r.video=r.video.filter(S=>!S.hdr))}}let a=F(P({},t),{streams:r});return this.tracer.log("updateManifestEnd",(0,T.flattenObject)(a)),a})}.bind(this));this.initRepresentations=(0,T.abortable)(this.destroyController.signal,function(e,t,i){return pe(this,null,function*(){var f;this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new T.Subscription,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,T.fromEvent)(p,"error").pipe((0,T.filter)(h=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Wo():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Xr())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 Wn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,b)=>[...h,...b.representations],[]);this.audioBufferManager=new Wn("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Yn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Yn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,T.merge)(...RB.map(p=>(0,T.fromEvent)(this.element,p))).pipe((0,T.map)(p=>this.element?Ze(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,T.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,T.now)())),this.subscription.add((0,T.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,T.interval)(1e3).subscribe(h=>{let b=Yi(this.manifestUrlString,2);this.manifestUrlString=Oe(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,T.fromEvent)(this.element,"play").subscribe(h=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add((0,T.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.map)(({isActiveLive:h,isLowLatency:b})=>h&&b),(0,T.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||cs(this.element,1)})),this.representationSubscription.add((0,T.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.filter)(({bufferLength:h,isActiveLive:b,isLowLatency:S})=>b&&S&&!!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 b=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,T.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,T.filter)(({isLive:h})=>h),(0,T.filterChanged)((h,b)=>b.bufferLength<h.bufferLength),(0,T.map)(({rtt:h,bufferLength:b,segmentServerLatency:S})=>{let v=Yi(this.manifestUrlString,2);return(h/2+b+S+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,T.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:b,isLowLatency:S})=>{if(!S||!b)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=h-v;if(this.isManualDecreasePlaybackInLive())return;let A=1;Math.abs(E)>y&&(A=1+Math.sign(E)*x),cs(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var S,v;let b=0;if(h){let y=((v=(S=this.element)==null?void 0:S.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var A,D;return(D=(A=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:A.to)!=null?D:y}))-y}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(1e3)).subscribe(S=>k(this,[S],function*({liveLoadBufferLength:h,bufferLength:b}){if(!this.element||this.isUpdatingLive)return;let v=this.element.playbackRate,y=Yi(this.manifestUrlString,2),x=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(x,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),A=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,D=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,j=isFinite(h)?h:b,H=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),N=x<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(N);let L="none";if(H?L="active_low_latency":this.isLowLatency$.getValue()&&N?(this.bufferManagers.forEach(Q=>Q.proceedLowLatencyLive()),L="active_low_latency"):y!==0&&j<E?L="live_forward_buffering":j<E+D&&(L="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),L==="live_forward_buffering"||L==="live_with_target_offset"){let Q=p-(E+A),O=this.normolizeLiveOffset(Math.trunc(y+Q/v)),J=Math.abs(O-y),G=0;!h||J<=this.tuning.dashCmafLive.offsetCalculationError?G=y:O>0&&J>this.tuning.dashCmafLive.offsetCalculationError&&(G=O),this.manifestUrlString=Oe(this.manifestUrlString,G,2)}(L==="live_with_target_offset"||L==="live_forward_buffering")&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:T.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,T.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=(0,T.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=(0,T.combine)({allBuffersFull:l,someBufferEnded:d}).pipe((0,T.filterChanged)(),(0,T.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,T.filter)(p=>p));if(this.representationSubscription.add((0,T.merge)(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,T.merge)(...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=>{var b;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var S;if(((S=this.source)==null?void 0:S.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(b=this.source)==null||b.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,Wd.default)((0,Wd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let b=[];return h.duration&&b.push(h.duration),gt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&b.push(h.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,T.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,T.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:T.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Ou({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=_i.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,P({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return k(this,null,function*(){var r,a,n;(0,T.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,T.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Oe(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running");let e=(0,T.fromEvent)(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe((0,T.throttle)(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add((0,T.merge)(...kB.map(t=>(0,T.fromEvent)(this.element,t)),(0,T.fromEvent)(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&at(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var h,b,S,v,y,x,E,A,D,j,H;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let a={timeInWaiting:r},n=(0,T.now)(),o=100,u=(S=(b=this.videoBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?S:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(y=(v=this.audioBufferManager)==null?void 0:v.lastDataObtainedTimestamp)!=null?y:0,d=(E=(x=this.videoBufferManager)==null?void 0:x.getForwardBufferDuration())!=null?E:0,c=(D=(A=this.audioBufferManager)==null?void 0:A.getForwardBufferDuration())!=null?D:0,f=d<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((f||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let N=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(N).catch(L=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:L})}),a.liveLastOffset=N}else{let N=this.element.currentTime*1e3;(j=this.videoBufferManager)==null||j.maintain(N),(H=this.audioBufferManager)==null||H.maintain(N),a.position=N}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(a))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=(0,T.interval)(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return k(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return k(this,null,function*(){var r,a,n,o,u;(0,T.assertNonNullable)(this.element),(0,T.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),at(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!((0,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.isNonNullable)(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,T.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return k(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",(0,T.flattenObject)({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};var Et=require("@vkontakte/videoplayer-shared/es2015"),Nu=class{constructor(){this.subscription=new Et.Subscription;this.pipSize$=new Et.ValueSubject(void 0);this.videoSize$=new Et.ValueSubject(void 0);this.elementSize$=new Et.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Et.noop}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add((0,Et.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,Et.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Et.map)(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Mr=class{constructor(e){this.subscription=new se.Subscription;this.videoState=new ce("stopped");this.observableVideo=null;this.droppedFramesManager=new ts;this.stallsManager=new ku;this.elementSizeManager=new Nu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ji;this.audioTrackSwitchHistory=new Ji;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),q(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"),q(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&q(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&q(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&q(this.params.desiredState.playbackState,"paused");return;default:return(0,se.assertNever)(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new ds(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ut(e.source.url),this.params=e,this.video=St(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(st(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 Fu({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;(0,se.isNullable)(this.observableVideo)&&(this.observableVideo=Tt(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:se.ErrorCategory.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((0,se.filter)(c=>!!c.length),(0,se.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,se.map)(c=>c.to.state!=="none"),(0,se.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,se.filter)(se.isNonNullable),(0,se.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,se.map)(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(ci(this.video,t.isLooped,r)),this.subscription.add(yt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Nt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(qt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),q(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),q(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 f=this.player.getStreams();if((0,se.assertNonNullable)(f,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let b of f.audio){h.push(Ud(b));let S=[];for(let v of b.representations){let y=eT(v);S.push(y),this.audioTracksMap.set(y,{stream:b,representation:v})}this.audioStreamsMap.set(b,S)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of f.video){p.push(qd(h));let b=[];for(let S of h.representations){let v=Zy(F(P({},S),{streamId:h.id}));v&&(b.push(v),this.videoTracksMap.set(v,{stream:h,representation:S}))}this.videoStreamsMap.set(h,b)}this.params.output.availableVideoStreams$.next(p);for(let h of f.text)for(let b of h.representations){let S=tT(h,b);this.textTracksMap.set(S,{stream:h,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&&sT(o)||null;this.subscription.add((0,se.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,se.fromEvent)(this.video,"progress")).pipe((0,se.filter)(()=>this.videoTracksMap.size>0)).subscribe(()=>k(this,null,function*(){let c=this.player.state$.getState(),f=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||f||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:h}=this.selectedRepresentations;if(!p)return;let b=Rr(this.videoTracksMap.keys(),v=>{var y;return((y=this.videoTracksMap.get(v))==null?void 0:y.representation.id)===p.id});(0,se.isNonNullable)(b)&&(this.stallsManager.lastVideoTrackSelected=b);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),c==="manifest_ready")yield this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",p.id),h){let v=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",h.id,v)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,se.filterChanged)()).subscribe(c=>{let f=Rr(this.videoTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!f){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=f,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===h.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(qd(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,se.filterChanged)()).subscribe(c=>{let f=Rr(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!f){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=f,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===h.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Ud(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var f,p;if(c!=null&&c.is3dVideo&&((f=this.params.tuning.spherical)!=null&&f.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe((0,se.map)(({to:c})=>c==="ready"),(0,se.filterChanged)());this.subscription.add((0,se.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,se.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add((0,se.merge)(l,this.player.state$.stateChangeEnded$,(0,se.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=(0,se.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,se.observableFrom)(["init"])).pipe((0,se.debounce)(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var H,N,L,Q,O,J,G,de,$,_,V,B;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ra:ka,t=this.params.tuning.useNewAutoSelectVideoTrack?su:ru,i=this.params.tuning.useNewAutoSelectVideoTrack?di:iu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(H=r.videoTrack.getState())==null?void 0:H.id,u=Rr(this.videoTracksMap.keys(),z=>z.id===o),l=a.currentVideoTrack$.getValue(),d=((Q=(L=r.videoStream.getState())!=null?L:u&&((N=this.videoTracksMap.get(u))==null?void 0:N.stream))!=null?Q:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=Rr(this.videoStreamsMap.keys(),z=>z.id===d.id),f=c&&this.videoStreamsMap.get(c);if(!f)return;let p=Ze(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(p/Math.min(h,b||1/0),1),v=(O=r.audioStream.getState())!=null?O:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(v==null?void 0:v.id)&&Rr(this.audioStreamsMap.keys(),z=>z.id===v.id)||this.audioStreamsMap.keys().next().value,x=0;if(y){if(u&&!n){let z=e(u,f,(J=this.audioStreamsMap.get(y))!=null?J:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(G=z==null?void 0:z.bitrate)!=null?G:-1/0)}if(l){let z=e(l,f,(de=this.audioStreamsMap.get(y))!=null?de:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,($=z==null?void 0:z.bitrate)!=null?$:-1/0)}}let E=u;(n||!E)&&(E=i(f,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:x,forwardBufferHealth:S,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let A=y&&t(E,f,(_=this.audioStreamsMap.get(y))!=null?_:[],{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}),D=(V=this.videoTracksMap.get(E))==null?void 0:V.representation,j=A&&((B=this.audioTracksMap.get(A))==null?void 0:B.representation);D&&j?(this.selectedRepresentations.video=D,this.selectedRepresentations.audio=j):D&&!j&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=D,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){It(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),q(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:se.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),vt(this.video),this.tracer.end()}};var Kn=class extends Mr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var xe=require("@vkontakte/videoplayer-shared/es2015");var Xn=class extends Mr{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 xe.ValueSubject(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe((0,xe.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,xe.combine)({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,xe.map)(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,xe.filter)(o=>(0,xe.isNonNullable)(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add((0,xe.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,xe.merge)(i.playbackRateState$,new xe.ValueSubject(1))}).pipe((0,xe.filter)(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||(0,xe.isNullable)(l)||(e=o-l)})).add((0,xe.combine)({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,xe.merge)(i.playbackRateState$,new xe.ValueSubject(1))}).pipe((0,xe.filterChanged)((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||(0,xe.isNullable)(o)||(0,xe.isNullable)(u))return;let f=-1*(u-o-e);t.position$.next(Math.min(f,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=iT(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 pT="X-Playback-Duration",Yd=s=>k(void 0,null,function*(){var r;let e=yield jt(s),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(pT)?parseInt(e.headers.get(pT),10):void 0});var he=require("@vkontakte/videoplayer-shared/es2015");var Xd=Z(sc(),1);var Uu=require("@vkontakte/videoplayer-shared/es2015");var LB=s=>{let e=null;if(s.QUALITY&&(e=Xi(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,Uu.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},BB=(s,e)=>{var a,n;let t=s.split(`
186
- `),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,Xd.default)(l[1].split(",").map(y=>y.split("="))),f=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,p=LB(c),h;c.BANDWIDTH&&(h=parseInt(c.BANDWIDTH,10)/1e3||void 0),!h&&c["AVERAGE-BANDWIDTH"]&&(h=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,S;if(c.RESOLUTION){let[y,x]=c.RESOLUTION.split("x").map(E=>parseInt(E,10));y&&x&&(S={width:y,height:x})}let v=new URL(t[++o],e).toString();p&&i.push({id:f,quality:p,url:v,bandwidth:h,size:S,fps:b})}if(d){let c=(0,Xd.default)(d[1].split(",").map(b=>{let S=b.indexOf("=");return[b.substring(0,S),b.substring(S+1)]}).map(([b,S])=>[b,S.replace(/^"|"$/g,"")])),f=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=c.LANGUAGE,h=c.NAME;f&&p&&r.push({type:"internal",id:p,label:h,language:p,url:f,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},$B=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),Kd=0,hT=(r,...a)=>k(void 0,[r,...a],function*(s,e=s,t,i){let o=yield(yield jt(s,i)).text();Kd+=1;try{let{qualityManifests:u,textTracks:l}=BB(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(Kd<=t.manifestRetryMaxCount)return yield $B((0,Uu.getExponentialDelay)(Kd-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),hT(s,e,t)}return{qualityManifests:[],textTracks:[]}}),qu=hT;var _t=require("@vkontakte/videoplayer-shared/es2015");var ju=class{constructor(e,t,i,r,a){this.subscription=new _t.Subscription;this.abortControllers={destroy:new ye,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new _t.ValueSubject(null);this.getCurrentTime$=new _t.ValueSubject(null);this.error$=new _t.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe((0,_t.throttle)(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return k(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=yield this.fetchManifestData();yield this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return k(this,null,function*(){try{let i=yield this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}})}parseTextTracks(e,t){return k(this,null,function*(){for(let i of e){let r=new URL(i.url,t).toString(),n=yield(yield jt(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(),f=new Date(i.programDateTime).valueOf();i.segmentStartTime=f-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,_t.isNonNullable)(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([F(P({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return k(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ye;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return k(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:_t.ErrorCategory.WTF,thrown:t,message:e})}};var Jn=class{constructor(e){this.subscription=new he.Subscription;this.videoState=new ce("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new he.ValueSubject([]);this.liveOffset=new Ir;this.manifestStartTime$=new he.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),q(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?q(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),q(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&q(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(q(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,he.assertNever)(t)}};var i;this.params=e,this.video=St(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:he.VideoQuality.INVARIANT,url:this.params.source.url};let t=(r,a)=>qu(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new ju(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ut(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:he.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:he.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(st(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new he.ValueSubject((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:he.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Tt(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(yt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Nt(this.video,t.playbackRate,r.playbackRateState$,i)),a(qt(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"),q(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),q(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,he.filterChanged)(),(0,he.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,he.isNonNullable)(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(p=>p.id===c);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(st(f.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,he.combine)({startTime:this.manifestStartTime$.pipe((0,he.filter)(he.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,he.map)(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:f})=>({id:u,quality:l,size:d,fps:f,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,he.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,he.observableFrom)(["init"])).pipe((0,he.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),vt(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if((0,he.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[f,p]of[[d,"mq"],[c,"lq"]]){let h=String(parseFloat(f||""));p&&f&&r.searchParams.set(p,h)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Oe(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Yd(n).then(d=>{var c;if(!(0,he.isNullable)(d))this.maxSeekBackTime$.next(d);else{let f=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();((0,he.isNullable)(f)||!isFinite(f))&&jt(n).then(p=>p.text()).then(p=>{var b;let h=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:b[1];if(h){let S=new URL(h,n).toString();Yd(S).then(v=>{(0,he.isNullable)(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){It(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),q(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:he.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=Oe(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};var Se=require("@vkontakte/videoplayer-shared/es2015");var Zn=class{constructor(e){this.subscription=new Se.Subscription;this.videoState=new ce("stopped");this.manifests$=new Se.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),q(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?q(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),q(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&q(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&q(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,Se.assertNever)(t)}};this.textTracksManager=new Ut(e.source.url),this.params=e,this.video=St(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Se.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(st(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),qu(Oe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Se.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Se.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Tt(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,Se.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ci(this.video,t.isLooped,i)),this.subscription.add(yt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Nt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),q(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),q(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,Se.isNonNullable)(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(S=>S.id===h);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(st(b.url)))}let c=this.params.desiredState.playbackRate.getState(),f=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(c!==f){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.subscription.add(this.manifests$.pipe((0,Se.map)(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:f})=>({id:u,quality:l,size:d,fps:f,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!te.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,Se.merge)((0,Se.fromEvent)(o,"addtrack"),(0,Se.fromEvent)(o,"removetrack"),(0,Se.fromEvent)(o,"change"),(0,Se.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,Se.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,Se.observableFrom)(["init"])).pipe((0,Se.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),vt(this.video)}prepare(){var a,n;let e=this.selectManifest();if((0,Se.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){It(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),q(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Se.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var fT=Z(mr(),1),Jd=Z(Tr(),1),mT=Z(ii(),1);var ke=require("@vkontakte/videoplayer-shared/es2015");var eo=class{constructor(e){this.subscription=new ke.Subscription;this.videoState=new ce("stopped");this.trackUrls={};this.textTracksManager=new Ut;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"),q(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?q(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),q(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&q(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&q(this.params.desiredState.playbackState,"paused");return;default:return(0,ke.assertNever)(e)}};this.params=e,this.video=St(e.container,e.tuning),this.params.output.element$.next(this.video),(0,fT.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,Jd.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:ke.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Tt(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,ke.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ci(this.video,t.isLooped,i)),this.subscription.add(yt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Nt(this.video,t.playbackRate,r.playbackRateState$,i)),a(qt(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),q(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),q(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,ke.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=(0,ke.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ke.observableFrom)(["init"])).pipe((0,ke.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),vt(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,ke.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,ke.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=tr(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(st(t))}playIfAllowed(){It(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),q(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ke.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let f=di(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(f)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,Jd.default)(this.trackUrls).map(c=>c.track);if(!r||!a||Jr(e,n[0].quality,(d=(0,mT.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?(0,ke.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,ke.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var Be=require("@vkontakte/videoplayer-shared/es2015");var gT=require("@vkontakte/videoplayer-shared/es2015");var bT=["stun:videostun.mycdn.me:80"],DB=1e3,CB=3,Zd=()=>null,Hu=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=Zd;this.externalStopCallback=Zd;this.externalErrorCallback=Zd;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return k(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return k(this,null,function*(){try{let e={iceServers:[{urls:bT}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return k(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return k(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:gT.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return k(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return k(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),DB)}normalizeOptions(e={}){let t={stunServerList:bT,maxRetryNumber:CB,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var to=class{constructor(e){this.videoState=new ce("stopped");this.maxSeekBackTime$=new Be.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),q(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"),q(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&q(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&q(this.params.desiredState.playbackState,"paused");return;default:return(0,Be.assertNever)(e)}};this.subscription=new Be.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=St(e.container,e.tuning),this.liveStreamClient=new Hu(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),vt(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Be.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,Be.merge)(this.videoState.stateChangeStarted$.pipe((0,Be.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Be.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Tt(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(qt(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(yt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,Be.assertNever)(n.to)}},i)).add((0,Be.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Be.observableFrom)(["init"])).pipe((0,Be.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(st(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:Be.VideoQuality.INVARIANT}),this.video.srcObject=e,q(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:Be.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){It(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),q(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Be.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var io=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var w=require("@vkontakte/videoplayer-shared/es2015");var qi=require("@vkontakte/videoplayer-shared/es2015"),ST=s=>new qi.Observable(e=>{let t=new qi.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe((0,qi.map)(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe((0,qi.map)(({type:l})=>l!==void 0)),n=new qi.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Ht=require("@vkontakte/videoplayer-shared/es2015");function vT(){return new(window.AudioContext||window.webkitAudioContext)}var ro=class ro{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ye;this.subscriptions=new Ht.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Ht.filter)(a=>!!a.type),(0,Ht.once)()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){te.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Ht.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Ht.filter)(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),(0,Ht.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return k(this,null,function*(){let{volumeMultiplier:t}=this,i=vT();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:ro.errorId,category:Ht.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${ro.errorId} exception`,thrown:e})}};ro.errorId="VolumeMultiplierManager";var fs=ro;var VB={chunkDuration:5e3,maxParallelRequests:5},so=class{constructor(e){this.current$=new w.ValueSubject({type:void 0});this.providerError$=new w.Subject;this.noAvailableProvidersError$=new w.Subject;this.volumeMultiplierError$=new w.Subject;this.providerOutput={position$:new w.ValueSubject(0),duration$:new w.ValueSubject(1/0),volume$:new w.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new w.ValueSubject([]),currentVideoStream$:new w.ValueSubject(void 0),availableVideoTracks$:new w.ValueSubject([]),currentVideoTrack$:new w.ValueSubject(void 0),availableAudioStreams$:new w.ValueSubject([]),currentAudioStream$:new w.ValueSubject(void 0),availableAudioTracks$:new w.ValueSubject([]),currentVideoSegmentLength$:new w.ValueSubject(0),currentAudioSegmentLength$:new w.ValueSubject(0),isAudioAvailable$:new w.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new w.ValueSubject(!1),autoVideoTrackLimits$:new w.ValueSubject(void 0),currentBuffer$:new w.ValueSubject(void 0),isBuffering$:new w.ValueSubject(!0),error$:new w.Subject,fetcherError$:new w.Subject,fetcherRecoverableError$:new w.Subject,warning$:new w.Subject,willSeekEvent$:new w.Subject,soundProhibitedEvent$:new w.Subject,seekedEvent$:new w.Subject,loopedEvent$:new w.Subject,endedEvent$:new w.Subject,firstBytesEvent$:new w.Subject,loadedMetadataEvent$:new w.Subject,firstFrameEvent$:new w.Subject,canplay$:new w.Subject,isLive$:new w.ValueSubject(void 0),isLiveEnded$:new w.ValueSubject(null),isLowLatency$:new w.ValueSubject(!1),canChangePlaybackSpeed$:new w.ValueSubject(!0),liveTime$:new w.ValueSubject(void 0),liveBufferTime$:new w.ValueSubject(void 0),liveLatency$:new w.ValueSubject(void 0),severeStallOccurred$:new w.Subject,availableTextTracks$:new w.ValueSubject([]),currentTextTrack$:new w.ValueSubject(void 0),hostname$:new w.ValueSubject(void 0),httpConnectionType$:new w.ValueSubject(void 0),httpConnectionReused$:new w.ValueSubject(void 0),inPiP$:new w.ValueSubject(!1),inFullscreen$:new w.ValueSubject(!1),element$:new w.ValueSubject(void 0),elementVisible$:new w.ValueSubject(!0),availableSources$:new w.ValueSubject(void 0),is3DVideo$:new w.ValueSubject(!1),playbackState$:new w.ValueSubject(""),getCurrentTime$:new w.ValueSubject(null)};this.subscription=new w.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Dy([...Vy(this.params.tuning),...Cy(this.params.tuning)],this.params.tuning).filter(l=>(0,w.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,ep.default)(r,l)),...t.filter(l=>(0,ep.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",(0,w.flattenObject)(a)),this.screenFormatsIterator=new io(a);let n=[...Bd(!0),...Bd(!1)];this.chromecastFormatsIterator=new io(n.filter(l=>(0,w.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&fs.isSupported()&&(this.volumeMultiplierManager=new fs(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,w.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:w.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,w.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,w.assertNonNullable)(u),this.params.tuning.useNewDashProvider?new Kn(F(P({},o),{source:u,sourceHls:l})):new Sn(F(P({},o),{source:u,sourceHls:l}))}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(u),this.params.tuning.useNewDashProvider?new Xn(F(P({},o),{source:u})):new vn(F(P({},o),{source:u}))}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(u),new Zn(F(P({},o),{source:u}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(u),new Jn(F(P({},o),{source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let u=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(u),new eo(F(P({},o),{source:u}))}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(u),new US(F(P({},o),{source:u,config:F(P({},VB),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(u),new to({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,w.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,w.assertNonNullable)(o),new wa({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,w.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,w.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,w.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return F(P({},e),{url:i(e.url)})}return(0,TT.default)((0,yT.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new w.Subscription,t=!1,i=0;return e.add((0,w.merge)(this.providerOutput.error$.pipe((0,w.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),ST({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,w.map)(r=>({id:`ProviderHangup:${r}`,category:w.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,w.filter)(({to:a})=>a==="playing"),(0,w.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===w.ErrorCategory.NETWORK,u=r.category===w.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n=F(P({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d}),d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",(0,w.flattenObject)(n)):this.tracer.error("providerError",(0,w.flattenObject)(n))})),e}};var ae=require("@vkontakte/videoplayer-shared/es2015");var OB=5e3,IT="one_video_throughput",xT="one_video_rtt",ji=window.navigator.connection,ET=()=>{let s=ji==null?void 0:ji.downlink;if((0,ae.isNonNullable)(s)&&s!==10)return s*1e3},wT=()=>{let s=ji==null?void 0:ji.rtt;if((0,ae.isNonNullable)(s)&&s!==3e3)return s},AT=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},tp=class s{constructor(e){this.subscription=new ae.Subscription;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(IT)||(e.useBrowserEstimation?ET():void 0)||OB,i=(a=(r=s.load(xT))!=null?r:e.useBrowserEstimation?wT():void 0)!=null?a:0;if(this.throughput$=new ae.ValueSubject(t),this.rtt$=new ae.ValueSubject(i),this.rttAdjustedThroughput$=new ae.ValueSubject(AT(t,i,e.rttPenaltyRequestSize)),this.throughput=_i.getSmoothedValue(t,-1,e),this.rtt=_i.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=ET();u&&this.throughput.next(u);let l=wT();(0,ae.isNonNullable)(l)&&this.rtt.next(l)};ji&&"onchange"in ji&&this.subscription.add((0,ae.fromEvent)(ji,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{ae.safeStorage.set(IT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{ae.safeStorage.set(xT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,ae.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,ae.map)(({throughput:n,rtt:o})=>AT(n,o,e.rttPenaltyRequestSize)),(0,ae.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,ae.now)(),r=new ae.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,ae.fromEvent)(e,"progress").pipe((0,ae.once)()).subscribe(a=>{t=a.loaded,i=(0,ae.now)()}));break;case 1:case 0:r.add((0,ae.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,ae.now)()}));break}r.add((0,ae.fromEvent)(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=(0,ae.now)(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=(0,ae.now)(),n=0,o=(0,ae.now)(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=f=>k(this,[f],function*({done:d,value:c}){if(d)!t&&this.addRawSpeed(r,(0,ae.now)()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=(0,ae.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-a;b&&this.addRawSpeed(n,b,1,t),n=c.byteLength,a=(0,ae.now)()}else n+=c.byteLength;o=(0,ae.now)()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,ae.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,ae.now)()-o,this.concurrentDownloads.size),n=0,o=(0,ae.now)());yield i==null?void 0:i.read().then(l,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=ae.safeStorage.get(e);if((0,ae.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},PT=tp;var Lr=require("@vkontakte/videoplayer-shared/es2015");var kT={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:Lr.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Lr.VideoQuality.Q_720P,trafficSavingLimit:Lr.VideoQuality.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:Lr.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,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},RT=s=>{var e;return F(P({},(0,Lr.fillWithDefault)(s,kT)),{configName:[...(e=s.configName)!=null?e:[],...kT.configName]})};var m=require("@vkontakte/videoplayer-shared/es2015");var Hi=require("@vkontakte/videoplayer-shared/es2015"),ip=({seekState:s,position$:e})=>(0,Hi.merge)(s.stateChangeEnded$.pipe((0,Hi.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,Hi.filter)(Hi.isNonNullable)),e.pipe((0,Hi.filter)(()=>s.getState().state==="none")));var MT=require("@vkontakte/videoplayer-shared/es2015"),LT=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return(0,MT.assertNonNullable)(e,`Wrong container or containerId {${s.container}}`),e};var zu=require("@vkontakte/videoplayer-shared/es2015"),BT=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,zu.filter)(r=>r.length>0),(0,zu.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var ao=class{constructor(e={configName:[]},t=m.TracerFactory.createRootTracer(!1)){this.subscription=new m.Subscription;this.logger=new m.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new m.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new m.ValueSubject(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new ce("stopped"),seekState:new ce({state:"none"}),volume:new ce({volume:1,muted:!1}),videoTrack:new ce(void 0),videoStream:new ce(void 0),audioStream:new ce(void 0),autoVideoTrackSwitching:new ce(!0),autoVideoTrackLimits:new ce({}),isLooped:new ce(!1),isLowLatency:new ce(!1),playbackRate:new ce(1),externalTextTracks:new ce([]),internalTextTracks:new ce([]),currentTextTrack:new ce(void 0),textTrackCuesSettings:new ce({}),cameraOrientation:new ce({x:0,y:0})};this.info={playbackState$:new m.ValueSubject(void 0),position$:new m.ValueSubject(0),duration$:new m.ValueSubject(1/0),muted$:new m.ValueSubject(!1),volume$:new m.ValueSubject(1),availableVideoStreams$:new m.ValueSubject([]),currentVideoStream$:new m.ValueSubject(void 0),availableQualities$:new m.ValueSubject([]),availableQualitiesFps$:new m.ValueSubject({}),currentQuality$:new m.ValueSubject(void 0),isAutoQualityEnabled$:new m.ValueSubject(!0),autoQualityLimitingAvailable$:new m.ValueSubject(!1),autoQualityLimits$:new m.ValueSubject({}),predefinedQualityLimitType$:new m.ValueSubject("unknown"),availableAudioStreams$:new m.ValueSubject([]),currentAudioStream$:new m.ValueSubject(void 0),availableAudioTracks$:new m.ValueSubject([]),isAudioAvailable$:new m.ValueSubject(!0),currentPlaybackRate$:new m.ValueSubject(1),currentBuffer$:new m.ValueSubject({start:0,end:0}),isBuffering$:new m.ValueSubject(!0),isStalled$:new m.ValueSubject(!1),isEnded$:new m.ValueSubject(!1),isLooped$:new m.ValueSubject(!1),isLive$:new m.ValueSubject(void 0),isLiveEnded$:new m.ValueSubject(null),canChangePlaybackSpeed$:new m.ValueSubject(void 0),atLiveEdge$:new m.ValueSubject(void 0),atLiveDurationEdge$:new m.ValueSubject(void 0),liveTime$:new m.ValueSubject(void 0),liveBufferTime$:new m.ValueSubject(void 0),liveLatency$:new m.ValueSubject(void 0),currentFormat$:new m.ValueSubject(void 0),availableTextTracks$:new m.ValueSubject([]),currentTextTrack$:new m.ValueSubject(void 0),throughputEstimation$:new m.ValueSubject(void 0),rttEstimation$:new m.ValueSubject(void 0),videoBitrate$:new m.ValueSubject(void 0),hostname$:new m.ValueSubject(void 0),httpConnectionType$:new m.ValueSubject(void 0),httpConnectionReused$:new m.ValueSubject(void 0),surface$:new m.ValueSubject("none"),chromecastState$:new m.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new m.ValueSubject(void 0),intrinsicVideoSize$:new m.ValueSubject(void 0),availableSources$:new m.ValueSubject(void 0),is3DVideo$:new m.ValueSubject(!1),currentVideoSegmentLength$:new m.ValueSubject(0),currentAudioSegmentLength$:new m.ValueSubject(0)};this.events={inited$:new m.Subject,ready$:new m.Subject,started$:new m.Subject,playing$:new m.Subject,paused$:new m.Subject,stopped$:new m.Subject,willReady$:new m.Subject,willStart$:new m.Subject,willResume$:new m.Subject,willPause$:new m.Subject,willStop$:new m.Subject,willDestruct$:new m.Subject,watchCoverageRecord$:new m.Subject,watchCoverageLive$:new m.Subject,managedError$:new m.Subject,fatalError$:new m.Subject,fetcherRecoverableError$:new m.Subject,ended$:new m.Subject,looped$:new m.Subject,seeked$:new m.Subject,willSeek$:new m.Subject,autoplaySoundProhibited$:new m.Subject,firstBytes$:new m.Subject,loadedMetadata$:new m.Subject,firstFrame$:new m.Subject,canplay$:new m.Subject,log$:new m.Subject,fetcherError$:new m.Subject,severeStallOccured$:new m.Subject};this.experimental={element$:new m.ValueSubject(void 0),tuningConfigName$:new m.ValueSubject([]),enableDebugTelemetry$:new m.ValueSubject(!1),dumpTelemetry:ES,getCurrentTime$:new m.ValueSubject(null)};if(this.initLogs(),this.tuning=RT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new fo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new PT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new m.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let n=Reflect.get(i,r,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(f=>JSON.stringify(f,(p,h)=>{let b=typeof h;return(0,$T.default)(["number","string","boolean"],b)?h:h===null?null:`<${b}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:m.ErrorCategory.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var l,d,c;let u=e,{container:n}=u,o=ap(u,["container"]);this.tracer.log("initVideo",(0,m.flattenObject)(o)),this.domContainer=LT(e),this.chromecastInitializer.contentId=(l=e.meta)==null?void 0:l.videoId,this.providerContainer=new so({sources:e.sources,meta:(d=e.meta)!=null?d:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?te.isInited$.pipe((0,m.filter)(n=>!!n),(0,m.once)()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),(0,m.fromEvent)(document,"visibilitychange").pipe((0,m.once)()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),a=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||a;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition(),n=(o=a==null?void 0:a.to.volume)!=null?o: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((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{(0,m.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,m.filter)(i=>i.length>0),(0,m.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",(0,m.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{var i;(0,m.assertNonNullable)(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",(0,m.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>P({type:"external"},t)))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{var t;BT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",P({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>e),(0,m.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,m.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,m.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(ed(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.filter)(({from:e})=>e==="stopped"),(0,m.once)()).subscribe(()=>{this.initedAt=(0,m.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"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",(0,m.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState(F(P({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:m.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,m.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,m.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,m.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,m.map)(n=>n.destination),(0,m.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,m.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,m.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,m.isInvariantQuality)(u)?1:(0,m.isInvariantQuality)(l)?-1:(0,m.isHigher)(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,m.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe((0,m.filter)(n=>(0,m.isNonNullable)(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,m.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,m.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe((0,m.tap)(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add((0,m.combine)({hasLiveOffsetByPaused:(0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(n=>n.to),(0,m.filterChanged)(),(0,m.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,m.combine)({atLiveEdge:(0,m.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:ip({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,m.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,m.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,m.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,m.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.muted),(0,m.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.volume),(0,m.filterChanged)()).subscribe(this.info.volume$)).add(ip({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,m.merge)(e.providerOutput.endedEvent$.pipe((0,m.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,m.mapTo)(!1))).pipe((0,m.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,m.map)(n=>({id:n?`No${n}`:"NoProviders",category:m.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe((0,m.once)(),(0,m.map)(n=>n!=null?n:(0,m.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new m.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new m.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.filter)(({to:n})=>n==="playing"),(0,m.once)()).subscribe(()=>i.next(!1)));let r=0,a=(0,m.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,m.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,m.filterChanged)());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,m.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,m.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,m.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new m.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,m.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,m.filter)(i=>i.length>0),(0,m.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=di(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,m.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,m.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,m.assertNonNullable)(this.providerContainer),(0,m.assertNonNullable)(e),xS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>IS(i)),this.providerContainer.current$.subscribe(({type:i})=>Pa("provider",i)),e.duration$.subscribe(i=>Pa("duration",i)),e.availableVideoTracks$.pipe((0,m.filter)(i=>!!i.length),(0,m.once)()).subscribe(i=>Pa("tracks",i)),this.events.fatalError$.subscribe(new ft("fatalError")),this.events.managedError$.subscribe(new ft("managedError")),e.position$.subscribe(new ft("position")),e.currentVideoTrack$.pipe((0,m.map)(i=>i==null?void 0:i.quality)).subscribe(new ft("quality")),this.info.currentBuffer$.subscribe(new ft("buffer")),e.isBuffering$.subscribe(new ft("isBuffering"))].forEach(i=>this.subscription.add(i)),Pa("codecs",te.video.supportedCodecs)}initTracerSubscription(){let e=(0,m.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,m.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,m.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,m.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,m.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,m.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,m.filter)(i=>i>0),(0,m.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,m.filter)(i=>i>0),(0,m.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,m.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,m.filter)(i=>i.end>0),(0,m.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,m.filterChanged)())}).pipe((0,m.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,m.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,m.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,m.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,m.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,m.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,m.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,m.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,m.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,m.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,m.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,m.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=()=>k(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:m.ErrorCategory.DOM,message:String(r)})})});this.subscription.add((0,m.merge)((0,m.fromEvent)(document,"visibilitychange"),(0,m.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,m.flattenObject)({quality:t,availableTracks:(0,m.flattenObject)(e),track:(0,m.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!$a()}};var fi=require("@vkontakte/videoplayer-shared/es2015"),_B=`@vkontakte/videoplayer-core@${el}`;
178
+ `;var Br=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 eo(this.params.fov,this.params.orientation),this.cameraRotationManager=new to(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(Zv,this.gl.VERTEX_SHADER),i=this.createShader(ey,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,d=t+r,c=e-i,f=t+r;return[s,n,u,o,l,d,c,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Te=require("@vkontakte/videoplayer-shared/es2015");var io="stalls_manager_metrics",uc="stalls_manager_abr_params",ty="stalls_manager_default_tuning_abr_params",lc=class{constructor(){this.isSeeked$=new Te.ValueSubject(!1);this.isBuffering$=new Te.ValueSubject(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Te.Subscription;this.severeStallOccurred$=new Te.ValueSubject(!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(uc):{};return C(C({},this.abrParams),e)}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,Te.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=((0,Te.now)()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}=C({},this.getStoredData(ty)),{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}=C({},this.abrParams);this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(uc),this.setStoredData(ty,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(io,"[]");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(io,[]),this.setStoredData(uc,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),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>s&&(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="{}"){var i;return JSON.parse((i=Te.safeStorage.get(e))!=null?i:t)}setStoredData(e,t){Te.safeStorage.set(e,JSON.stringify(t))}removeStoredData(e){Te.safeStorage.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(io,"[]"),r=t/e,s=i.length?Kt(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(io,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe((0,Te.once)()).subscribe(t=>this.providerStartWatchingTimestamp=(0,Te.now)())),this.subscription.add(this.currentStallDuration$.pipe((0,Te.filterChanged)()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if((0,Te.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),o=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=(0,Te.now)(),c=r&&this.currentStallsCount>=r,f=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&d-l>=i+u&&t>=i;(c||f)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Te.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&(0,Te.now)()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},ro=lc;var Je=require("@vkontakte/videoplayer-shared/es2015"),ao=class{constructor(){this.subscription=new Je.Subscription;this.pipSize$=new Je.ValueSubject(void 0);this.videoSize$=new Je.ValueSubject(void 0);this.elementSize$=new Je.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Je.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,Je.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,Je.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Je.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Hi=class{constructor(e){this.subscription=new ee.Subscription;this.videoState=new ne("stopped");this.observableVideo=null;this.droppedFramesManager=new wr;this.stallsManager=new ro;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 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==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),j(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"),j(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&j(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&j(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&j(this.params.desiredState.playbackState,"paused");return;default:return(0,ee.assertNever)(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Br(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new ht(e.source.url),this.params=e,this.video=We(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(Ne(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 Zn({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;(0,ee.isNullable)(this.observableVideo)&&(this.observableVideo=Ke(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:ee.ErrorCategory.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((0,ee.filter)(l=>!!l.length),(0,ee.once)()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,ee.map)(l=>l.to.state!=="none"),(0,ee.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,ee.filter)(ee.isNonNullable),(0,ee.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,ee.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ct(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(pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(ft(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),j(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),j(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,ee.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let p of d.audio){f.push(ec(p));let h=[];for(let b of p.representations){let v=Hv(b);h.push(v),this.audioTracksMap.set(v,{stream:p,representation:b})}this.audioStreamsMap.set(p,h)}this.params.output.availableAudioStreams$.next(f)}let c=[];for(let f of d.video){c.push(tc(f));let p=[];for(let h of f.representations){let b=jv(Q(C({},h),{streamId:f.id}));b&&(p.push(b),this.videoTracksMap.set(b,{stream:f,representation:h}))}this.videoStreamsMap.set(f,p)}this.params.output.availableVideoStreams$.next(c);for(let f of d.text)for(let p of f.representations){let h=Qv(f,p);this.textTracksMap.set(h,{stream:f,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add((0,ee.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,ee.fromEvent)(this.video,"progress")).pipe((0,ee.filter)(()=>this.videoTracksMap.size>0)).subscribe(()=>R(this,null,function*(){let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,iy.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[f,p]=c,h=[...this.videoTracksMap.keys()].find(v=>{var S;return((S=this.videoTracksMap.get(v))==null?void 0:S.representation.id)===f.id});(0,ee.isNonNullable)(h)&&(this.stallsManager.lastVideoTrackSelected=h);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")yield this.player.initRepresentations(f.id,p==null?void 0:p.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",f.id),p){let v=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",p.id,v)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,ee.filterChanged)()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:f}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(tc(f));let h=this.player.calculateDurationFromSegments();h&&this.params.output.duration$.next(h/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,ee.filterChanged)()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:f}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(ec(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe((0,ee.map)(({to:l})=>l==="ready"),(0,ee.filterChanged)());this.subscription.add((0,ee.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,ee.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add((0,ee.merge)(u,this.player.state$.stateChangeEnded$,(0,ee.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let o=(0,ee.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,ee.observableFrom)(["init"])).pipe((0,ee.debounce)(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var M,G,q,Y,le,he,F,$,P,B,N,we,et;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ta:ya,t=this.params.tuning.useNewAutoSelectVideoTrack?$n:Ln,i=this.params.tuning.useNewAutoSelectVideoTrack?Bt:kn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=(M=r.videoTrack.getState())==null?void 0:M.id,l=[...this.videoTracksMap.keys()].find(({id:ve})=>ve===u),d=s.currentVideoTrack$.getValue(),c=((Y=(q=r.videoStream.getState())!=null?q:l&&((G=this.videoTracksMap.get(l))==null?void 0:G.stream))!=null?Y:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let f=[...this.videoStreamsMap.keys()].find(({id:ve})=>ve===c.id),p=f&&this.videoStreamsMap.get(f);if(!p)return;let h=Be(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 v=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(b,v||1/0),1),T=(le=r.audioStream.getState())!=null?le:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,E=(he=[...this.audioStreamsMap.keys()].find(({id:ve})=>ve===(T==null?void 0:T.id)))!=null?he:this.audioStreamsMap.keys().next().value,w=0;if(E){if(l&&!n){let ve=e(l,p,(F=this.audioStreamsMap.get(E))!=null?F:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);w=Math.max(w,($=ve==null?void 0:ve.bitrate)!=null?$:-1/0)}if(d){let ve=e(d,p,(P=this.audioStreamsMap.get(E))!=null?P:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);w=Math.max(w,(B=ve==null?void 0:ve.bitrate)!=null?B:-1/0)}}let A=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:w,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}),O=n?A!=null?A:l:l!=null?l:A,H=E&&t(O,p,(N=this.audioStreamsMap.get(E))!=null?N:[],{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}),_=(we=this.videoTracksMap.get(O))==null?void 0:we.representation,U=H&&((et=this.audioTracksMap.get(H))==null?void 0:et.representation);if(_&&U)return[_,U];if(_&&!U&&this.audioTracksMap.size===0)return[_,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"),j(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ee.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),ze(this.video),this.tracer.end()}};var ns=class extends Hi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var be=require("@vkontakte/videoplayer-shared/es2015");var os=class extends Hi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new be.ValueSubject(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,be.filterChanged)()).subscribe(o=>{let l=i.position$.getValue(),d=i.volume$.getValue(),c=!d.volume||d.muted;!o&&!l&&c?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((0,be.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,be.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,be.map)(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,be.filter)(o=>(0,be.isNonNullable)(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add((0,be.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,be.merge)(r.playbackRateState$,new be.ValueSubject(1))}).pipe((0,be.filter)(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let d=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-f||this.video.paused||(0,be.isNullable)(d)||(t=o-d)})).add((0,be.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,be.merge)(r.playbackRateState$,new be.ValueSubject(1))}).pipe((0,be.filterChanged)((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:d})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&d>=1-f||(0,be.isNullable)(o)||(0,be.isNullable)(l))return;let p=-1*(l-o-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=Gv(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 te=require("@vkontakte/videoplayer-shared/es2015");var bc=J(Ra(),1);var y=require("@vkontakte/videoplayer-shared/es2015");var lo=J(dt(),1),Gi=J(xt(),1),co=J(Ra(),1);var dy=J(mn(),1);var vi=require("@vkontakte/videoplayer-shared/es2015");var y$=18,ry=!1;try{ry=X.browser.isSafari&&!!X.browser.safariVersion&&X.browser.safariVersion<=y$}catch(a){console.error(a)}var cc=class{constructor(e){this.bufferFull$=new vi.Subject;this.error$=new vi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:vi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return R(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return R(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};ry&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:vi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,vi.assertNever)(t)}}},ay=cc;var L=require("@vkontakte/videoplayer-shared/es2015");var dc=J(xt(),1);var so=require("@vkontakte/videoplayer-shared/es2015"),sy=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var o;let u=(o=s?hi(s):void 0)!=null?o:(0,so.videoSizeToQuality)({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}),oy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),uy=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),pc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,dc.default)(i.split("."),0),isDefault:r}),hc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,dc.default)(r.split("."),0)}),fc=a=>"url"in a,ut=a=>a.type==="template";var ly=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},Qi=(a,e)=>{for(let t of a)if(e(t))return t;return null},cy=a=>{let e=!1,t=(0,so.throttleFn)(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};var uo=require("@vkontakte/videoplayer-shared/es2015");var no=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 oo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new uo.Subscription;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add((0,uo.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!Z(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=no(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 us=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new L.ValueSubject(0);this.currentLowLatencySegmentLength$=new L.ValueSubject(0);this.currentSegmentLength$=new L.ValueSubject(0);this.onLastSegment$=new L.ValueSubject(!1);this.fullyBuffered$=new L.ValueSubject(!1);this.playingRepresentation$=new L.ValueSubject(void 0);this.playingRepresentationInit$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.gaps=[];this.subscription=new L.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new fe;this.switchAbortController=new fe;this.destroyAbortController=new fe;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=(0,L.abortable)(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){let t=this.representations.get(e);(0,L.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new ay(this.sourceBuffer),this.sourceBufferBufferedDiff=new oo(this.mediaSource,this.sourceBuffer),this.subscription.add((0,L.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add((0,L.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:L.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!Z(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,kr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=Be(this.sourceBuffer.buffered,u),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,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),s=this.parsedInitData.get(t.id);(0,L.assertNonNullable)(i,"No init buffer for starting representation"),(0,L.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=(0,L.abortable)(this.destroyAbortController.signal,function(e,t=!1){return oe(this,null,function*(){if(!Z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,L.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,L.isNullable)(s)||(0,L.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,L.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,L.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new Pi(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=(0,L.abortable)(this.destroyAbortController.signal,function(e,t=!1){return oe(this,null,function*(){if(!Z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,L.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,L.isNullable)(s)||(0,L.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,L.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,L.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Pi(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,L.abortable)(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){var o,l;let t=(o=(0,co.default)(e,d=>d.representations))!=null?o:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(h=>h.id===d);c&&this.representations.set(d,c);let f=this.representations.get(d);if(!f||!ut(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,L.assertNonNullable)(r);let s=this.segments.get(i);(0,L.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,L.assertNonNullable)(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));var d;this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new fe,(0,L.abortable)(this.switchAbortController.signal,function(i,r=!1){return oe(this,null,function*(){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,L.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if((0,L.isNullable)(u)||(0,L.isNullable)(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),(0,L.assertNonNullable)(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!Z(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();(0,L.isNonNullable)(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(){!(0,L.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return R(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new fe,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if((0,L.isNullable)(e)||(0,L.isNullable)(this.downloadingRepresentationId)||(0,L.isNullable)(this.playingRepresentationId)||(0,L.isNullable)(this.sourceBuffer)||!Z(this.mediaSource,this.sourceBuffer)||(0,L.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,L.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);(0,L.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=Be(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&&(s=c)}if(isFinite(this.bufferLimit)&&kr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Be(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let o=null;if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o!=null&&o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,lo.default)(o,r))d="high";else{let c=(0,Gi.default)(o,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(o!=null&&o.length)&&Be(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Gi.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Be(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;(0,L.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,co.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,co.default)(e==null?void 0:e.streams[this.kind],u=>u.representations))!=null?i:[];if(![...this.segments.values()].every(u=>!u.length))for(let u of t){if(!u||!ut(u.segmentReference))return;let o=u.segmentReference.segments.map(p=>Q(C({},p),{status:"none",size:void 0})),l=100,d=(r=this.segments.get(u.id))!=null?r:[],c=(n=(s=(0,Gi.default)(d,-1))==null?void 0:s.time.to)!=null?n:0,f=o==null?void 0:o.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(u.segmentReference);this.segments.set(u.id,p)}else{let p=o.slice(f+1);this.segments.set(u.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,L.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!ut(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=At(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,u;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(o=>o.time.from<=e&&o.time.to>=e);return(u=r==null?void 0:r.time.from)!=null?u:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&_t&&_t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&_t&&_t(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:f,time:{from:p,to:h}},b)=>{let v=p<=i&&h>=i,S=p>i||v||b===0&&i===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&p<=i+T||r<T&&h-p>=T||h<=i+T;return(f==="none"||f==="partially_ejected"&&S&&E&&this.sourceBuffer&&Z(this.mediaSource,this.sourceBuffer)&&!(Ue(this.sourceBuffer.buffered,p)&&Ue(this.sourceBuffer.buffered,h)))&&S&&E});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let f=s;f<n.length&&(u<=d||o<=c);f++){let p=n[f];if(u+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}loadSegments(e,t,i="auto"){return R(this,null,function*(){ut(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return R(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(yield(0,L.abortable)(u,function(){return oe(this,null,function*(){let d=(0,L.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,L.now)(),!d)return;let c=new DataView(d),f=Ot(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(c,b)}o&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,u);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(c);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Ft(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())ut(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return R(this,null,function*(){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&&(yield(0,L.abortable)(n,function(){return oe(this,null,function*(){let o=(0,L.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),(0,L.fromEvent)(window,"online").pipe((0,L.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,L.now)(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Ft(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(ut(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Gi.default)(e,0).byte.from,to:(0,Gi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(u,o)=>R(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,L.now)(),yield 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:L.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!ut(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,L.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:L.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,lo.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!Z(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){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Ot(u.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",o.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(u){return R(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Z(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let l of this.activeSegments){if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let{segment:d}=l,c=d.byte.from-i,f=d.byte.to-i,p=f-c+1,h=c<r,b=f<=r;if(h){if(d.status==="downloading"&&b){d.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+c,p);(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-c),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?v:Ot(o.mime).parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(d.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}}})}onSegmentFullyAppended(e,t){if(!((0,L.isNullable)(this.sourceBuffer)||!Z(this.mediaSource,this.sourceBuffer))){!this.isLive&&X.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ue(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ue(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:L.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",fc(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||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Rr(()=>(0,dy.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return R(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,L.abortable)(this.destroyAbortController.signal,function(){return oe(this,null,function*(){let u=(0,L.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ot(e.mime),r)).then(u=>{if(!u)return;let{init:o,dataView:l,segments:d}=u,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let f=d;this.isLive&&ut(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),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:L.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,n),n})}dropBuffer(){return R(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return R(this,null,function*(){if(!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,L.isNullable)(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=u=>{var l;if(s>=t)return;r.push(C({},u.time));let o=fc(u)?(l=u.size)!=null?l: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,d=o.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&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,d=0;for(let c of this.segments.values())for(let f of c)(0,lo.default)(["none","partially_ejected"],f.status)&&Math.round(f.time.from)<=Math.round(o)&&Math.round(f.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:o,to:l},url:"",status:"none"};n(c)}}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=ly(r),(yield Promise.all(r.map(o=>this.sourceBufferTaskQueue.remove(o.from,o.to)))).reduce((o,l)=>o||l,!1)):!1})}abortBuffer(){return R(this,null,function*(){if(!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,L.isNullable)(e)?0:Be(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!Z(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(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||!Z(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Rr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:L.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,L.isNullable)(this.sourceBuffer)||!Z(this.mediaSource,this.sourceBuffer)||(0,L.isNullable)(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=no(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 d=0;d<e.length;d+=2){let c=e[d],f=e[d+1];o||(o=c-t<=n&&f+t>=u),(n>=c&&n<f-t||u>c+t&&u<=f)&&(l+=1)}o||(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:L.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,Gi.default)(e,-1))==null?void 0:t.time.to:0)||0}};var ae=require("@vkontakte/videoplayer-shared/es2015");var ho=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new ae.ValueSubject(void 0);this.lastConnectionReused$=new ae.ValueSubject(void 0);this.lastRequestFirstBytes$=new ae.ValueSubject(void 0);this.recoverableError$=new ae.Subject;this.error$=new ae.Subject;this.abortAllController=new fe;this.subscription=new ae.SubscriptionRemovable;this.fetchManifest=(0,ae.abortable)(this.abortAllController.signal,function(e){return oe(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=gi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=qn(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(po);return r?(t.log("success",(0,ae.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,ae.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,ae.abortable)(this.abortAllController.signal,function(d){return oe(this,arguments,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}={}){var le,he,F;let c=e,f=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{f.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let $=new URL(c,location.href);$.searchParams.append("bytes",`${i.from}-${i.to}`),c=$.toString();break}default:(0,ae.assertNever)(t)}this.requestQuic&&(c=gi(c));let h=this.abortAllController.signal,b;if(n){let $=new fe;if(b=(0,ae.merge)((0,ae.fromEvent)(this.abortAllController.signal,"abort"),(0,ae.fromEvent)(n,"abort")).subscribe(()=>{try{$.abort()}catch(P){po(P)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(P){po(P)}h=$.signal}let v=(0,ae.now)();p.log("startRequest",(0,ae.flattenObject)({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:v}));let S=yield this.doFetch(c,{priority:s,headers:f,signal:h}),T=(0,ae.now)();if(!S)return p.error("error",{message:"No response in request"}),p.end(),this.unsubscribeAbortSubscription(b),null;if((le=this.throughputEstimator)==null||le.addRawRtt(T-v),!S.ok||!S.body){this.unsubscribeAbortSubscription(b);let $=`Fetch error ${S.status}: ${S.statusText}`;return p.error("error",{message:$}),p.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!u){this.unsubscribeAbortSubscription(b);let $=(0,ae.now)(),P={requestStartedAt:v,requestEndedAt:$,duration:$-v};return p.log("endRequest",(0,ae.flattenObject)(P)),p.end(),S.arrayBuffer()}let E=S.body;if(u){let $;[E,$]=S.body.tee(),(he=this.throughputEstimator)==null||he.trackStream($,o)}let w=E.getReader(),A,O=parseInt((F=S.headers.get("content-length"))!=null?F:"",10);Number.isFinite(O)&&(A=O),!A&&i&&(A=i.to-i.from+1);let H=0,_=A?new Uint8Array(A):new Uint8Array(0),U=!1,M=$=>{this.unsubscribeAbortSubscription(b),U=!0,po($)},G=(0,ae.abortable)(h,function(B){return oe(this,arguments,function*({done:$,value:P}){if(H===0&&this.lastRequestFirstBytes$.next((0,ae.now)()-v),h.aborted){this.unsubscribeAbortSubscription(b);return}if(!$&&P){if(l&&A)_.set(P,H),H+=P.byteLength;else{let N=new Uint8Array(_.length+P.length);N.set(_),N.set(P,_.length),_=N,H+=P.byteLength}r==null||r(new DataView(_.buffer),H),yield w==null?void 0:w.read().then(G,M)}})}.bind(this));yield w==null?void 0:w.read().then(G,M),this.unsubscribeAbortSubscription(b);let q=(0,ae.now)(),Y={failed:U,requestStartedAt:v,requestEndedAt:q,duration:q-v};return U?(p.error("endRequest",(0,ae.flattenObject)(Y)),p.end(),null):(p.log("endRequest",(0,ae.flattenObject)(Y)),p.end(),_.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,ae.abortable)(this.abortAllController.signal,function(e,t,i){return oe(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!c)return null;let f=new DataView(c,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(c,h.from-n,h.to-h.from+1);else{let T=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!T)return null;b=new DataView(T)}let v=t.parseSegments(b,p,h);return{init:p,dataView:new DataView(c),segments:v}})}.bind(this));this.fetchTemplateRepresentation=(0,ae.abortable)(this.abortAllController.signal,function(e,t){return oe(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>Q(C({},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}=Un(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return R(this,null,function*(){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,ae.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}doFetch(e,t){return R(this,null,function*(){let i=yield mt(e,t);if(i.ok)return i;let r=yield i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:ae.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ae.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ae.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ae.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:ae.ErrorCategory.FATAL})}})}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},po=a=>{if(!Ft(a))throw a};var fo=require("@vkontakte/videoplayer-shared/es2015");var ls=class a{constructor(e,t){this.currentRepresentation$=new fo.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,fo.isNullable)(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,u=s.segments[0].time.from,o=s.segments[n-1].time.to;if(e<u||e>o)continue;let l=s.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(Q(C({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ut(t.segmentReference))}};var E$=["progress","play","seeked","stalled","waiting"],x$=["timeupdate","progress","loadeddata","playing","seeked"];var mo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new y.Subscription;this.representationSubscription=new y.Subscription;this.state$=new ne("none");this.currentVideoRepresentation$=new y.ValueSubject(void 0);this.currentVideoRepresentationInit$=new y.ValueSubject(void 0);this.currentAudioRepresentation$=new y.ValueSubject(void 0);this.currentVideoSegmentLength$=new y.ValueSubject(0);this.currentAudioSegmentLength$=new y.ValueSubject(0);this.error$=new y.Subject;this.lastConnectionType$=new y.ValueSubject(void 0);this.lastConnectionReused$=new y.ValueSubject(void 0);this.lastRequestFirstBytes$=new y.ValueSubject(void 0);this.currentLiveTextRepresentation$=new y.ValueSubject(null);this.isLive$=new y.ValueSubject(!1);this.isActiveLive$=new y.ValueSubject(!1);this.isLowLatency$=new y.ValueSubject(!1);this.liveDuration$=new y.ValueSubject(0);this.liveSeekableDuration$=new y.ValueSubject(0);this.liveAvailabilityStartTime$=new y.ValueSubject(0);this.liveStreamStatus$=new y.ValueSubject(void 0);this.bufferLength$=new y.ValueSubject(0);this.liveLatency$=new y.ValueSubject(void 0);this.liveLoadBufferLength$=new y.ValueSubject(0);this.livePositionFromPlayer$=new y.ValueSubject(0);this.currentStallDuration$=new y.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new y.ValueSubject(0);this.fetcherRecoverableError$=new y.Subject;this.fetcherError$=new y.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new y.Subject;this.gapWatchdogActive=!1;this.destroyController=new fe;this.initManifest=(0,y.abortable)(this.destroyController.signal,function(e,t,i){return oe(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Re(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:y.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,y.abortable)(this.destroyController.signal,function(){return oe(this,null,function*(){var n,u;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:y.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=On(e!=null?e:"",this.manifestUrlString)}catch(o){let l=(n=Vn(e))!=null?n:{id:"ManifestParsing",category:y.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,d)=>{var c,f,p,h;return!!((f=(c=this.element)==null?void 0:c.canPlayType)!=null&&f.call(c,l)&&((h=(p=st())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${d}"`))||o==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,f=((u=t.duration)!=null?u:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let o of["video","audio"]){let d=t.streams[o].filter(({mime:p,codecs:h})=>i(o,p,h)),c=new Set(d.map(({codecs:p})=>p)),f=Jn(c);if(f&&(r[o]=d.filter(({codecs:p})=>p.startsWith(f))),o==="video"){let p=this.tuning.preferHDR,h=r.video.some(v=>v.hdr),b=r.video.some(v=>!v.hdr);X.display.isHDR&&p&&h?r.video=r.video.filter(v=>v.hdr):b&&(r.video=r.video.filter(v=>!v.hdr))}}let s=Q(C({},t),{streams:r});return this.tracer.log("updateManifestEnd",(0,y.flattenObject)(s)),s})}.bind(this));this.initRepresentations=(0,y.abortable)(this.destroyController.signal,function(e,t,i){return oe(this,null,function*(){var f;this.tracer.log("initRepresentationsStart",(0,y.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,y.assertNonNullable)(this.manifest),(0,y.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new y.Subscription,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,y.fromEvent)(p,"error").pipe((0,y.filter)(h=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?vn():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&yr())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},u=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new us("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],(0,y.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,b)=>[...h,...b.representations],[]);this.audioBufferManager=new us("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}ls.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ls(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=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,y.merge)(...x$.map(p=>(0,y.fromEvent)(this.element,p))).pipe((0,y.map)(p=>this.element?Be(this.element.buffered,this.element.currentTime*1e3):0),(0,y.filterChanged)(),(0,y.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,y.merge)((0,y.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,y.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,y.now)())),this.subscription.add((0,y.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,y.interval)(1e3).subscribe(h=>{let b=di(this.manifestUrlString,2);this.manifestUrlString=Re(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,y.fromEvent)(this.element,"play").subscribe(h=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add((0,y.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.map)(({isActiveLive:h,isLowLatency:b})=>h&&b),(0,y.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Cr(this.element,1)})),this.representationSubscription.add((0,y.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.filter)(({bufferLength:h,isActiveLive:b,isLowLatency:v})=>b&&v&&!!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 b=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,y.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,y.filter)(({isLive:h})=>h),(0,y.filterChanged)((h,b)=>b.bufferLength<h.bufferLength),(0,y.map)(({rtt:h,bufferLength:b,segmentServerLatency:v})=>{let S=di(this.manifestUrlString,2);return(h/2+b+v+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,y.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:b,isLowLatency:v})=>{if(!v||!b)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,T=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,E=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,w=h-S;if(this.isManualDecreasePlaybackInLive())return;let A=1;Math.abs(w)>T&&(A=1+Math.sign(w)*E),Cr(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var v,S;let b=0;if(h){let T=((S=(v=this.element)==null?void 0:v.currentTime)!=null?S:0)*1e3;b=Math.min(...this.bufferManagers.map(w=>{var A,O;return(O=(A=w.getLiveSegmentsToLoadState(this.manifest))==null?void 0:A.to)!=null?O:T}))-T}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add((0,y.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,y.throttle)(1e3)).subscribe(v=>R(this,[v],function*({liveLoadBufferLength:h,bufferLength:b}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,T=di(this.manifestUrlString,2),E=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,w=Math.min(E,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),A=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,O=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,H=isFinite(h)?h:b,_=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),U=E<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(U);let M="none";if(_?M="active_low_latency":this.isLowLatency$.getValue()&&U?(this.bufferManagers.forEach(G=>G.proceedLowLatencyLive()),M="active_low_latency"):T!==0&&H<w?M="live_forward_buffering":H<w+O&&(M="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let G=p-(w+A),q=this.normolizeLiveOffset(Math.trunc(T+G/S)),Y=Math.abs(q-T),le=0;!h||Y<=this.tuning.dashCmafLive.offsetCalculationError?le=T:q>0&&Y>this.tuning.dashCmafLive.offsetCalculationError&&(le=q),this.manifestUrlString=Re(this.manifestUrlString,le,2)}(M==="live_with_target_offset"||M==="live_forward_buffering")&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:y.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,y.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,y.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=(0,y.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,y.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=(0,y.combine)({allBuffersFull:l,someBufferEnded:d}).pipe((0,y.filterChanged)(),(0,y.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,y.filter)(p=>p));if(this.representationSubscription.add((0,y.merge)(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,y.merge)(...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=>{var b;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var v;if(((v=this.source)==null?void 0:v.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(b=this.source)==null||b.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,bc.default)((0,bc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let b=[];return h.duration&&b.push(h.duration),ut(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&b.push(h.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,y.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,y.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:y.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ho({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=Xt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,C({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return R(this,null,function*(){var r,s,n;(0,y.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,y.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Re(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){(0,y.assertNonNullable)(this.element),this.state$.setState("running");let e=(0,y.fromEvent)(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe((0,y.throttle)(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add((0,y.merge)(...E$.map(t=>(0,y.fromEvent)(this.element,t)),(0,y.fromEvent)(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:y.ErrorCategory.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add((0,y.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,y.fromEvent)(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ue(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var h,b,v,S,T,E,w,A,O,H,_;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let s={timeInWaiting:r},n=(0,y.now)(),u=100,o=(v=(b=this.videoBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?v:0;this.videoLastDataObtainedTimestamp$.next(o);let l=(T=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?T:0,d=(w=(E=this.videoBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?w:0,c=(O=(A=this.audioBufferManager)==null?void 0:A.getForwardBufferDuration())!=null?O:0,f=d<u&&n-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<u&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((f||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let U=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(U).catch(M=>{this.error$.next({id:"stallIntervalCallback",category:y.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:M})}),s.liveLastOffset=U}else{let U=this.element.currentTime*1e3;(H=this.videoBufferManager)==null||H.maintain(U),(_=this.audioBufferManager)==null||_.maintain(U),s.position=U}this.tracer.log("stallIntervalCallback",(0,y.flattenObject)(s))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=(0,y.interval)(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:y.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return R(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return R(this,null,function*(){var r,s,n,u,o;(0,y.assertNonNullable)(this.element),(0,y.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ue(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(u=this.audioBufferManager)==null?void 0:u.abort()])),!((0,y.isNullable)(this.element)||(0,y.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(o=this.audioBufferManager)==null||o.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,y.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,y.isNonNullable)(this.element)&&(0,y.isNonNullable)(this.source)&&(0,y.isNonNullable)(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,y.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return R(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.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",(0,y.flattenObject)({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:o,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var Ze=require("@vkontakte/videoplayer-shared/es2015"),bo=class{constructor(){this.subscription=new Ze.Subscription;this.pipSize$=new Ze.ValueSubject(void 0);this.videoSize$=new Ze.ValueSubject(void 0);this.elementSize$=new Ze.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Ze.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,Ze.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,Ze.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Ze.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Wi=class{constructor(e){this.subscription=new te.Subscription;this.videoState=new ne("stopped");this.observableVideo=null;this.droppedFramesManager=new wr;this.stallsManager=new ro;this.elementSizeManager=new bo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new 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==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),j(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"),j(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&j(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&j(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&j(this.params.desiredState.playbackState,"paused");return;default:return(0,te.assertNever)(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Br(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new ht(e.source.url),this.params=e,this.video=We(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(Ne(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 mo({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;(0,te.isNullable)(this.observableVideo)&&(this.observableVideo=Ke(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:te.ErrorCategory.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((0,te.filter)(c=>!!c.length),(0,te.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,te.map)(c=>c.to.state!=="none"),(0,te.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,te.filter)(te.isNonNullable),(0,te.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,te.map)(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(Ct(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(pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(ft(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),j(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),j(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 f=this.player.getStreams();if((0,te.assertNonNullable)(f,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let b of f.audio){h.push(pc(b));let v=[];for(let S of b.representations){let T=ny(S);v.push(T),this.audioTracksMap.set(T,{stream:b,representation:S})}this.audioStreamsMap.set(b,v)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of f.video){p.push(hc(h));let b=[];for(let v of h.representations){let S=sy(Q(C({},v),{streamId:h.id}));S&&(b.push(S),this.videoTracksMap.set(S,{stream:h,representation:v}))}this.videoStreamsMap.set(h,b)}this.params.output.availableVideoStreams$.next(p);for(let h of f.text)for(let b of h.representations){let v=oy(h,b);this.textTracksMap.set(v,{stream:h,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:u}=this.params.tuning.dash,o=u&&cy(u)||null;this.subscription.add((0,te.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,te.fromEvent)(this.video,"progress")).pipe((0,te.filter)(()=>this.videoTracksMap.size>0)).subscribe(()=>R(this,null,function*(){let c=this.player.state$.getState(),f=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||f||c==="running"&&o&&!o())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:h}=this.selectedRepresentations;if(!p)return;let b=Qi(this.videoTracksMap.keys(),S=>{var T;return((T=this.videoTracksMap.get(S))==null?void 0:T.representation.id)===p.id});(0,te.isNonNullable)(b)&&(this.stallsManager.lastVideoTrackSelected=b);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")yield this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",p.id),h){let S=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",h.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((0,te.filterChanged)()).subscribe(c=>{let f=Qi(this.videoTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!f){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=f,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===h.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(hc(h));let v=this.player.calculateDurationFromSegments();v&&this.params.output.duration$.next(v/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,te.filterChanged)()).subscribe(c=>{let f=Qi(this.audioTracksMap.entries(),([,{representation:v}])=>v.id===c);if(!f){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=f,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===h.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(pc(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var f,p;if(c!=null&&c.is3dVideo&&((f=this.params.tuning.spherical)!=null&&f.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe((0,te.map)(({to:c})=>c==="ready"),(0,te.filterChanged)());this.subscription.add((0,te.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,te.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add((0,te.merge)(l,this.player.state$.stateChangeEnded$,(0,te.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=(0,te.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,te.observableFrom)(["init"])).pipe((0,te.debounce)(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var _,U,M,G,q,Y,le,he,F,$,P,B;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ta:ya,t=this.params.tuning.useNewAutoSelectVideoTrack?$n:Ln,i=this.params.tuning.useNewAutoSelectVideoTrack?Bt:kn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=(_=r.videoTrack.getState())==null?void 0:_.id,o=Qi(this.videoTracksMap.keys(),N=>N.id===u),l=s.currentVideoTrack$.getValue(),d=((G=(M=r.videoStream.getState())!=null?M:o&&((U=this.videoTracksMap.get(o))==null?void 0:U.stream))!=null?G:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=Qi(this.videoStreamsMap.keys(),N=>N.id===d.id),f=c&&this.videoStreamsMap.get(c);if(!f)return;let p=Be(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,v=Math.min(p/Math.min(h,b||1/0),1),S=(q=r.audioStream.getState())!=null?q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,T=(S==null?void 0:S.id)&&Qi(this.audioStreamsMap.keys(),N=>N.id===S.id)||this.audioStreamsMap.keys().next().value,E=0;if(T){if(o&&!n){let N=e(o,f,(Y=this.audioStreamsMap.get(T))!=null?Y:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);E=Math.max(E,(le=N==null?void 0:N.bitrate)!=null?le:-1/0)}if(l){let N=e(l,f,(he=this.audioStreamsMap.get(T))!=null?he:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);E=Math.max(E,(F=N==null?void 0:N.bitrate)!=null?F:-1/0)}}let w=o;(n||!w)&&(w=i(f,{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:v,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=T&&t(w,f,($=this.audioStreamsMap.get(T))!=null?$:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),O=(P=this.videoTracksMap.get(w))==null?void 0:P.representation,H=A&&((B=this.audioTracksMap.get(A))==null?void 0:B.representation);O&&H?(this.selectedRepresentations.video=O,this.selectedRepresentations.audio=H):O&&!H&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=O,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"),j(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:te.ErrorCategory.DOM,thrown:e}))}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),ze(this.video),this.tracer.end()}};var cs=class extends Wi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var ge=require("@vkontakte/videoplayer-shared/es2015");var ds=class extends Wi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new ge.ValueSubject(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,ge.filterChanged)()).subscribe(o=>{let l=i.position$.getValue(),d=i.volume$.getValue(),c=!d.volume||d.muted;!o&&!l&&c?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((0,ge.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,ge.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ge.map)(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,ge.filter)(o=>(0,ge.isNonNullable)(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add((0,ge.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,ge.merge)(r.playbackRateState$,new ge.ValueSubject(1))}).pipe((0,ge.filter)(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let d=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-f||this.video.paused||(0,ge.isNullable)(d)||(t=o-d)})).add((0,ge.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,ge.merge)(r.playbackRateState$,new ge.ValueSubject(1))}).pipe((0,ge.filterChanged)((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:d})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&d>=1-f||(0,ge.isNullable)(o)||(0,ge.isNullable)(l))return;let p=-1*(l-o-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=uy(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 hy="X-Playback-Duration",gc=a=>R(null,null,function*(){var r;let e=yield mt(a),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(hy)?parseInt(e.headers.get(hy),10):void 0});var ue=require("@vkontakte/videoplayer-shared/es2015");var vc=J(Mu(),1);var go=require("@vkontakte/videoplayer-shared/es2015");var A$=a=>{let e=null;if(a.QUALITY&&(e=hi(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,go.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},P$=(a,e)=>{var s,n;let t=a.split(`
179
+ `),i=[],r=[];for(let u=0;u<t.length;u++){let o=t[u],l=o.match(/^#EXT-X-STREAM-INF:(.+)/),d=o.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,vc.default)(l[1].split(",").map(T=>T.split("="))),f=(s=c.QUALITY)!=null?s:`stream-${c.BANDWIDTH}`,p=A$(c),h;c.BANDWIDTH&&(h=parseInt(c.BANDWIDTH,10)/1e3||void 0),!h&&c["AVERAGE-BANDWIDTH"]&&(h=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,v;if(c.RESOLUTION){let[T,E]=c.RESOLUTION.split("x").map(w=>parseInt(w,10));T&&E&&(v={width:T,height:E})}let S=new URL(t[++u],e).toString();p&&i.push({id:f,quality:p,url:S,bandwidth:h,size:v,fps:b})}if(d){let c=(0,vc.default)(d[1].split(",").map(b=>{let v=b.indexOf("=");return[b.substring(0,v),b.substring(v+1)]}).map(([b,v])=>[b,v.replace(/^"|"$/g,"")])),f=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=c.LANGUAGE,h=c.NAME;f&&p&&r.push({type:"internal",id:p,label:h,language:p,url:f,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},R$=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Sc=0,fy=(r,...s)=>R(null,[r,...s],function*(a,e=a,t,i){let u=yield(yield mt(a,i)).text();Sc+=1;try{let{qualityManifests:o,textTracks:l}=P$(u,e);return{qualityManifests:o,textTracks:l}}catch(o){if(Sc<=t.manifestRetryMaxCount)return yield R$((0,go.getExponentialDelay)(Sc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),fy(a,e,t)}return{qualityManifests:[],textTracks:[]}}),So=fy;var lt=require("@vkontakte/videoplayer-shared/es2015");var vo=class{constructor(e,t,i,r,s){this.subscription=new lt.Subscription;this.abortControllers={destroy:new fe,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new lt.ValueSubject(null);this.getCurrentTime$=new lt.ValueSubject(null);this.error$=new lt.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe((0,lt.throttle)(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return R(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=yield this.fetchManifestData();yield this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return R(this,null,function*(){try{let i=yield this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}})}parseTextTracks(e,t){return R(this,null,function*(){for(let i of e){let r=new URL(i.url,t).toString(),n=yield(yield mt(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(),d=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),f=new Date(i.programDateTime).valueOf();i.segmentStartTime=f-c}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((0,lt.isNonNullable)(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([Q(C({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return R(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new fe;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return R(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:lt.ErrorCategory.WTF,thrown:t,message:e})}};var ps=class{constructor(e){this.subscription=new ue.Subscription;this.videoState=new ne("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new ue.ValueSubject([]);this.liveOffset=new Oi;this.manifestStartTime$=new ue.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),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"),j(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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),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==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?j(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),j(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&j(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(j(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,ue.assertNever)(t)}};var i;this.params=e,this.video=We(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ue.VideoQuality.INVARIANT,url:this.params.source.url};let t=(r,s)=>So(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new vo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ht(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ue.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:ue.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new ue.ValueSubject((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var o,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(c=(d=(o=r==null?void 0:r.to)==null?void 0:o.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let u=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:ue.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=Ke(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(Ye(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),s(ft(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),j(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),j(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())==null?void 0:u.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((0,ue.filterChanged)(),(0,ue.map)(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,ue.isNonNullable)(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(p=>p.id===c);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Ne(f.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.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(()=>{var o,l,d;let u=(d=(l=(o=this.video)==null?void 0:o.getStartDate)==null?void 0:l.call(o))==null?void 0:d.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add((0,ue.combine)({startTime:this.manifestStartTime$.pipe((0,ue.filter)(ue.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:o})=>this.params.output.liveTime$.next(u+o*1e3),i)),this.subscription.add(this.manifests$.pipe((0,ue.map)(u=>u.map(({id:o,quality:l,size:d,bandwidth:c,fps:f})=>({id:o,quality:l,size:d,fps:f,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,ue.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ue.observableFrom)(["init"])).pipe((0,ue.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),ze(this.video)}prepare(){var u,o,l;let e=this.selectManifest();if((0,ue.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(o=(u=t==null?void 0:t.to)!=null?u:i)!=null?o:{};for(let[f,p]of[[d,"mq"],[c,"lq"]]){let h=String(parseFloat(f||""));p&&f&&r.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Re(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),gc(n).then(d=>{var c;if(!(0,ue.isNullable)(d))this.maxSeekBackTime$.next(d);else{let f=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();((0,ue.isNullable)(f)||!isFinite(f))&&mt(n).then(p=>p.text()).then(p=>{var b;let h=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:b[1];if(h){let v=new URL(h,n).toString();gc(v).then(S=>{(0,ue.isNullable)(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){Xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),j(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ue.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();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=Re(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};var pe=require("@vkontakte/videoplayer-shared/es2015");var hs=class{constructor(e){this.subscription=new pe.Subscription;this.videoState=new ne("stopped");this.manifests$=new pe.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),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"),j(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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?j(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),j(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&j(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&j(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,pe.assertNever)(t)}};this.textTracksManager=new ht(e.source.url),this.params=e,this.video=We(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:pe.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),So(Re(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:pe.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var o,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(c=(d=(o=r==null?void 0:r.to)==null?void 0:o.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"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(f=>f.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:pe.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:u})},r=Ke(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((0,pe.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Ct(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(pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),j(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),j(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,pe.isNonNullable)(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(v=>v.id===h);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(Ne(b.url)))}let c=this.params.desiredState.playbackRate.getState(),f=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(c!==f){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),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u.state==="requested"&&this.seek(u.position)},i))),this.subscription.add(this.manifests$.pipe((0,pe.map)(u=>u.map(({id:o,quality:l,size:d,bandwidth:c,fps:f})=>({id:o,quality:l,size:d,fps:f,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!X.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add((0,pe.merge)((0,pe.fromEvent)(u,"addtrack"),(0,pe.fromEvent)(u,"removetrack"),(0,pe.fromEvent)(u,"change"),(0,pe.observableFrom)(["init"])).subscribe(()=>{for(let o=0;o<u.length;o++)u[o].mode="hidden"},i))}let n=(0,pe.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,pe.observableFrom)(["init"])).pipe((0,pe.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ze(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,pe.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:u,min:o}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,d]of[[u,"mq"],[o,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}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"),j(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pe.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var my=J(lr(),1),yc=J(Tr(),1),by=J(xt(),1);var Ie=require("@vkontakte/videoplayer-shared/es2015");var fs=class{constructor(e){this.subscription=new Ie.Subscription;this.videoState=new ne("stopped");this.trackUrls={};this.textTracksManager=new ht;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),j(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==null?void 0:i.to)!=="paused"&&u.state==="requested"&&this.seek(u.position),e){case"ready":t==="ready"?j(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),j(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&j(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&j(this.params.desiredState.playbackState,"paused");return;default:return(0,Ie.assertNever)(e)}};this.params=e,this.video=We(e.container,e.tuning),this.params.output.element$.next(this.video),(0,my.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,yc.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:Ie.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:u})},r=Ke(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((0,Ie.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Ct(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(pt(this.video,t.playbackRate,r.playbackRateState$,i)),s(ft(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),j(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),j(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o,l;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready");let u=this.params.desiredState.videoTrack.getTransition();if(u&&(0,Ie.isNonNullable)(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=(0,Ie.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Ie.observableFrom)(["init"])).pipe((0,Ie.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ze(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,Ie.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,Ie.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=gi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Ne(t))}playIfAllowed(){Xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),j(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ie.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let f=Bt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(f)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,yc.default)(this.trackUrls).map(c=>c.track);if(!r||!s||Ir(e,n[0].quality,(d=(0,by.default)(n,-1))==null?void 0:d.quality)){i();return}let u=e.max?(0,Ie.isLowerOrEqual)(r,e.max):!0,o=e.min?(0,Ie.isHigherOrEqual)(r,e.min):!0;u&&o||i(e)}};var Ee=require("@vkontakte/videoplayer-shared/es2015");var Sy=require("@vkontakte/videoplayer-shared/es2015");var gy=["stun:videostun.mycdn.me:80"],k$=1e3,L$=3,Tc=()=>null,yo=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Tc;this.externalStopCallback=Tc;this.externalErrorCallback=Tc;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return R(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return R(this,null,function*(){try{let e={iceServers:[{urls:gy}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return R(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return R(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:Sy.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return R(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return R(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),k$)}normalizeOptions(e={}){let t={stunServerList:gy,maxRetryNumber:L$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ms=class{constructor(e){this.videoState=new ne("stopped");this.maxSeekBackTime$=new Ee.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),j(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"),j(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&j(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&j(this.params.desiredState.playbackState,"paused");return;default:return(0,Ee.assertNever)(e)}};this.subscription=new Ee.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=We(e.container,e.tuning),this.liveStreamClient=new yo(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ze(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ee.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,Ee.merge)(this.videoState.stateChangeStarted$.pipe((0,Ee.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Ee.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(n)}`})}));let r=Ke(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(ft(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(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(0,Ee.assertNever)(n.to)}},i)).add((0,Ee.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Ee.observableFrom)(["init"])).pipe((0,Ee.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ne(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:Ee.VideoQuality.INVARIANT}),this.video.srcObject=e,j(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:Ee.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),j(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ee.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var bs=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var x=require("@vkontakte/videoplayer-shared/es2015");var Jt=require("@vkontakte/videoplayer-shared/es2015"),vy=a=>new Jt.Observable(e=>{let t=new Jt.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Jt.map)(({from:l,to:d})=>`${l}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Jt.map)(({type:l})=>l!==void 0)),n=new Jt.Subject,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()}});var bt=require("@vkontakte/videoplayer-shared/es2015");function yy(){return new(window.AudioContext||window.webkitAudioContext)}var gs=class gs{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new fe;this.subscriptions=new bt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,bt.filter)(s=>!!s.type),(0,bt.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){X.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,bt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,bt.filter)(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,bt.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return R(this,null,function*(){let{volumeMultiplier:t}=this,i=yy();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:gs.errorId,category:bt.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${gs.errorId} exception`,thrown:e})}};gs.errorId="VolumeMultiplierManager";var Vr=gs;var $$={chunkDuration:5e3,maxParallelRequests:5},Ss=class{constructor(e){this.current$=new x.ValueSubject({type:void 0});this.providerError$=new x.Subject;this.noAvailableProvidersError$=new x.Subject;this.volumeMultiplierError$=new x.Subject;this.providerOutput={position$:new x.ValueSubject(0),duration$:new x.ValueSubject(1/0),volume$:new x.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new x.ValueSubject([]),currentVideoStream$:new x.ValueSubject(void 0),availableVideoTracks$:new x.ValueSubject([]),currentVideoTrack$:new x.ValueSubject(void 0),availableAudioStreams$:new x.ValueSubject([]),currentAudioStream$:new x.ValueSubject(void 0),availableAudioTracks$:new x.ValueSubject([]),currentVideoSegmentLength$:new x.ValueSubject(0),currentAudioSegmentLength$:new x.ValueSubject(0),isAudioAvailable$:new x.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new x.ValueSubject(!1),autoVideoTrackLimits$:new x.ValueSubject(void 0),currentBuffer$:new x.ValueSubject(void 0),isBuffering$:new x.ValueSubject(!0),error$:new x.Subject,fetcherError$:new x.Subject,fetcherRecoverableError$:new x.Subject,warning$:new x.Subject,willSeekEvent$:new x.Subject,soundProhibitedEvent$:new x.Subject,seekedEvent$:new x.Subject,loopedEvent$:new x.Subject,endedEvent$:new x.Subject,firstBytesEvent$:new x.Subject,loadedMetadataEvent$:new x.Subject,firstFrameEvent$:new x.Subject,canplay$:new x.Subject,isLive$:new x.ValueSubject(void 0),isLiveEnded$:new x.ValueSubject(null),canPlayLiveTailBuffer$:new x.ValueSubject(!1),isLowLatency$:new x.ValueSubject(!1),canChangePlaybackSpeed$:new x.ValueSubject(!0),liveTime$:new x.ValueSubject(void 0),liveBufferTime$:new x.ValueSubject(void 0),liveLatency$:new x.ValueSubject(void 0),severeStallOccurred$:new x.Subject,availableTextTracks$:new x.ValueSubject([]),currentTextTrack$:new x.ValueSubject(void 0),hostname$:new x.ValueSubject(void 0),httpConnectionType$:new x.ValueSubject(void 0),httpConnectionReused$:new x.ValueSubject(void 0),inPiP$:new x.ValueSubject(!1),inFullscreen$:new x.ValueSubject(!1),element$:new x.ValueSubject(void 0),elementVisible$:new x.ValueSubject(!0),availableSources$:new x.ValueSubject(void 0),is3DVideo$:new x.ValueSubject(!1),playbackState$:new x.ValueSubject(""),getCurrentTime$:new x.ValueSubject(null)};this.subscription=new x.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Tl([...Kv(this.params.tuning),...Yv(this.params.tuning)],this.params.tuning).filter(l=>(0,x.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Ic.default)(r,l)),...t.filter(l=>(0,Ic.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,x.flattenObject)(s)),this.screenFormatsIterator=new bs(s);let n=[...sc(!0),...sc(!1)];this.chromecastFormatsIterator=new bs(n.filter(l=>(0,x.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&u!==1&&Vr.isSupported()&&(this.volumeMultiplierManager=new Vr(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(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,x.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:x.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,x.assertNever)(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(0,x.assertNonNullable)(o),this.params.tuning.useNewDashProvider?new cs(Q(C({},u),{source:o,sourceHls:l})):new ns(Q(C({},u),{source:o,sourceHls:l}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(o),this.params.tuning.useNewDashProvider?new ds(Q(C({},u),{source:o})):new os(Q(C({},u),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(o),new hs(Q(C({},u),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(o),new ps(Q(C({},u),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(o),new fs(Q(C({},u),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(o),new Wg(Q(C({},u),{source:o,config:Q(C({},$$),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(o),new ms({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(0,x.assertNever)(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(0,x.assertNonNullable)(u),new ga({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(0,x.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,x.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,x.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Q(C({},e),{url:i(e.url)})}return(0,Iy.default)((0,Ty.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new x.Subscription,t=!1,i=0;return e.add((0,x.merge)(this.providerOutput.error$.pipe((0,x.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),vy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,x.map)(r=>({id:`ProviderHangup:${r}`,category:x.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,x.filter)(({to:s})=>s==="playing"),(0,x.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=r.category===x.ErrorCategory.NETWORK,o=r.category===x.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!o,c=l&&!o&&(u&&t||!d);n=Q(C({},n),{isNetworkError:u,isFatalError:o,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(s!=null?s:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",(0,x.flattenObject)(n)):this.tracer.error("providerError",(0,x.flattenObject)(n))})),e}};var ie=require("@vkontakte/videoplayer-shared/es2015");var M$=5e3,Ey="one_video_throughput",xy="one_video_rtt",Zt=window.navigator.connection,wy=()=>{let a=Zt==null?void 0:Zt.downlink;if((0,ie.isNonNullable)(a)&&a!==10)return a*1e3},Ay=()=>{let a=Zt==null?void 0:Zt.rtt;if((0,ie.isNonNullable)(a)&&a!==3e3)return a},Py=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Ec=class a{constructor(e){this.subscription=new ie.Subscription;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(Ey)||(e.useBrowserEstimation?wy():void 0)||M$,i=(s=(r=a.load(xy))!=null?r:e.useBrowserEstimation?Ay():void 0)!=null?s:0;if(this.throughput$=new ie.ValueSubject(t),this.rtt$=new ie.ValueSubject(i),this.rttAdjustedThroughput$=new ie.ValueSubject(Py(t,i,e.rttPenaltyRequestSize)),this.throughput=Xt.getSmoothedValue(t,-1,e),this.rtt=Xt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let o=wy();o&&this.throughput.next(o);let l=Ay();(0,ie.isNonNullable)(l)&&this.rtt.next(l)};Zt&&"onchange"in Zt&&this.subscription.add((0,ie.fromEvent)(Zt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{ie.safeStorage.set(Ey,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{ie.safeStorage.set(xy,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,ie.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,ie.map)(({throughput:n,rtt:u})=>Py(n,u,e.rttPenaltyRequestSize)),(0,ie.filter)(n=>{let u=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-u)/u>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,ie.now)(),r=new ie.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,ie.fromEvent)(e,"progress").pipe((0,ie.once)()).subscribe(s=>{t=s.loaded,i=(0,ie.now)()}));break;case 1:case 0:r.add((0,ie.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,ie.now)()}));break}r.add((0,ie.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,u=(0,ie.now)(),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=(0,ie.now)(),n=0,u=(0,ie.now)(),o=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=f=>R(this,[f],function*({done:d,value:c}){if(d)!t&&this.addRawSpeed(r,(0,ie.now)()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=(0,ie.now)();if(p-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=u-s;b&&this.addRawSpeed(n,b,1,t),n=c.byteLength,s=(0,ie.now)()}else n+=c.byteLength;u=(0,ie.now)()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,ie.now)()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,ie.now)()-u,this.concurrentDownloads.size),n=0,u=(0,ie.now)());yield i==null?void 0:i.read().then(l,o)}});this.concurrentDownloads.add(e),i==null||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){var i;let t=ie.safeStorage.get(e);if((0,ie.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},Ry=Ec;var zi=require("@vkontakte/videoplayer-shared/es2015");var ky={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:zi.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:zi.VideoQuality.Q_720P,trafficSavingLimit:zi.VideoQuality.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:zi.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,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},Ly=a=>{var e;return Q(C({},(0,zi.fillWithDefault)(a,ky)),{configName:[...(e=a.configName)!=null?e:[],...ky.configName]})};var m=require("@vkontakte/videoplayer-shared/es2015");var ei=require("@vkontakte/videoplayer-shared/es2015"),xc=({seekState:a,position$:e})=>(0,ei.merge)(a.stateChangeEnded$.pipe((0,ei.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,ei.filter)(ei.isNonNullable)),e.pipe((0,ei.filter)(()=>a.getState().state==="none")));var $y=require("@vkontakte/videoplayer-shared/es2015"),My=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,$y.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var To=require("@vkontakte/videoplayer-shared/es2015"),Dy=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,To.filter)(r=>r.length>0),(0,To.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var vs=class{constructor(e={configName:[]},t=m.TracerFactory.createRootTracer(!1)){this.subscription=new m.Subscription;this.logger=new m.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new m.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new m.ValueSubject(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new ne("stopped"),seekState:new ne({state:"none"}),volume:new ne({volume:1,muted:!1}),videoTrack:new ne(void 0),videoStream:new ne(void 0),audioStream:new ne(void 0),autoVideoTrackSwitching:new ne(!0),autoVideoTrackLimits:new ne({}),isLooped:new ne(!1),isLowLatency:new ne(!1),playbackRate:new ne(1),externalTextTracks:new ne([]),internalTextTracks:new ne([]),currentTextTrack:new ne(void 0),textTrackCuesSettings:new ne({}),cameraOrientation:new ne({x:0,y:0})};this.info={playbackState$:new m.ValueSubject(void 0),position$:new m.ValueSubject(0),duration$:new m.ValueSubject(1/0),muted$:new m.ValueSubject(!1),volume$:new m.ValueSubject(1),availableVideoStreams$:new m.ValueSubject([]),currentVideoStream$:new m.ValueSubject(void 0),availableQualities$:new m.ValueSubject([]),availableQualitiesFps$:new m.ValueSubject({}),currentQuality$:new m.ValueSubject(void 0),isAutoQualityEnabled$:new m.ValueSubject(!0),autoQualityLimitingAvailable$:new m.ValueSubject(!1),autoQualityLimits$:new m.ValueSubject({}),predefinedQualityLimitType$:new m.ValueSubject("unknown"),availableAudioStreams$:new m.ValueSubject([]),currentAudioStream$:new m.ValueSubject(void 0),availableAudioTracks$:new m.ValueSubject([]),isAudioAvailable$:new m.ValueSubject(!0),currentPlaybackRate$:new m.ValueSubject(1),currentBuffer$:new m.ValueSubject({start:0,end:0}),isBuffering$:new m.ValueSubject(!0),isStalled$:new m.ValueSubject(!1),isEnded$:new m.ValueSubject(!1),isLooped$:new m.ValueSubject(!1),isLive$:new m.ValueSubject(void 0),isLiveEnded$:new m.ValueSubject(null),canPlayLiveTailBuffer$:new m.ValueSubject(!1),canChangePlaybackSpeed$:new m.ValueSubject(void 0),atLiveEdge$:new m.ValueSubject(void 0),atLiveDurationEdge$:new m.ValueSubject(void 0),liveTime$:new m.ValueSubject(void 0),liveBufferTime$:new m.ValueSubject(void 0),liveLatency$:new m.ValueSubject(void 0),currentFormat$:new m.ValueSubject(void 0),availableTextTracks$:new m.ValueSubject([]),currentTextTrack$:new m.ValueSubject(void 0),throughputEstimation$:new m.ValueSubject(void 0),rttEstimation$:new m.ValueSubject(void 0),videoBitrate$:new m.ValueSubject(void 0),hostname$:new m.ValueSubject(void 0),httpConnectionType$:new m.ValueSubject(void 0),httpConnectionReused$:new m.ValueSubject(void 0),surface$:new m.ValueSubject("none"),chromecastState$:new m.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new m.ValueSubject(void 0),intrinsicVideoSize$:new m.ValueSubject(void 0),availableSources$:new m.ValueSubject(void 0),is3DVideo$:new m.ValueSubject(!1),currentVideoSegmentLength$:new m.ValueSubject(0),currentAudioSegmentLength$:new m.ValueSubject(0)};this.events={inited$:new m.Subject,ready$:new m.Subject,started$:new m.Subject,playing$:new m.Subject,paused$:new m.Subject,stopped$:new m.Subject,willReady$:new m.Subject,willStart$:new m.Subject,willResume$:new m.Subject,willPause$:new m.Subject,willStop$:new m.Subject,willDestruct$:new m.Subject,watchCoverageRecord$:new m.Subject,watchCoverageLive$:new m.Subject,managedError$:new m.Subject,fatalError$:new m.Subject,fetcherRecoverableError$:new m.Subject,ended$:new m.Subject,looped$:new m.Subject,seeked$:new m.Subject,willSeek$:new m.Subject,autoplaySoundProhibited$:new m.Subject,firstBytes$:new m.Subject,loadedMetadata$:new m.Subject,firstFrame$:new m.Subject,canplay$:new m.Subject,log$:new m.Subject,fetcherError$:new m.Subject,severeStallOccured$:new m.Subject};this.experimental={element$:new m.ValueSubject(void 0),tuningConfigName$:new m.ValueSubject([]),enableDebugTelemetry$:new m.ValueSubject(!1),dumpTelemetry:Lg,getCurrentTime$:new m.ValueSubject(null)};if(this.initLogs(),this.tuning=Ly(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ns({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ry(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new m.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,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(f=>JSON.stringify(f,(p,h)=>{let b=typeof h;return(0,Cy.default)(["number","string","boolean"],b)?h:h===null?null:`<${b}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:m.ErrorCategory.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var l,d,c;let o=e,{container:n}=o,u=dd(o,["container"]);this.tracer.log("initVideo",(0,m.flattenObject)(u)),this.domContainer=My(e),this.chromecastInitializer.contentId=(l=e.meta)==null?void 0:l.videoId,this.providerContainer=new Ss({sources:e.sources,meta:(d=e.meta)!=null?d:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?X.isInited$.pipe((0,m.filter)(n=>!!n),(0,m.once)()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),(0,m.fromEvent)(document,"visibilitychange").pipe((0,m.once)()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),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((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{var u;let i=this.desiredState.volume,r=i.getTransition(),s=(u=r==null?void 0:r.to.muted)!=null?u:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{var u;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,s=i.getTransition(),n=(u=s==null?void 0:s.to.volume)!=null?u: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((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{(0,m.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,m.filter)(i=>i.length>0),(0,m.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",(0,m.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{var i;(0,m.assertNonNullable)(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",(0,m.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>C({type:"external"},t)))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{var t;Dy(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",C({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>e),(0,m.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,m.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,m.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next($l(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.filter)(({from:e})=>e==="stopped"),(0,m.once)()).subscribe(()=>{this.initedAt=(0,m.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"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",(0,m.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState(Q(C({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:m.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,m.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,m.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,m.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,m.map)(n=>n.destination),(0,m.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,m.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,m.map)(({availableVideoTracks:n,currentVideoStream:u})=>n.filter(o=>u?u.id===o.streamId:!0).map(({quality:o})=>o).sort((o,l)=>(0,m.isInvariantQuality)(o)?1:(0,m.isInvariantQuality)(l)?-1:(0,m.isHigher)(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((0,m.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe((0,m.filter)(n=>(0,m.isNonNullable)(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,m.filterChanged)((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,m.filterChanged)((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,m.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,m.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe((0,m.tap)(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add((0,m.combine)({hasLiveOffsetByPaused:(0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(n=>n.to),(0,m.filterChanged)(),(0,m.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:u})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(u));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,m.combine)({atLiveEdge:(0,m.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:xc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,m.map)(({isLive:n,position:u,isLowLatency:o})=>{let l=this.getActiveLiveDelay(o);return n&&Math.abs(u)<l/1e3}),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,m.map)(({atLiveEdge:n,hasPausedTimeoutCase:u})=>n&&!u)).subscribe(this.info.atLiveEdge$)).add((0,m.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,m.map)(({isLive:n,position:u,duration:o})=>n&&(Math.abs(o)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.muted),(0,m.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.volume),(0,m.filterChanged)()).subscribe(this.info.volume$)).add(xc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,m.merge)(e.providerOutput.endedEvent$.pipe((0,m.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,m.mapTo)(!1))).pipe((0,m.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,m.map)(n=>({id:n?`No${n}`:"NoProviders",category:m.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe((0,m.once)(),(0,m.map)(n=>n!=null?n:(0,m.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new m.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new m.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.filter)(({to:n})=>n==="playing"),(0,m.once)()).subscribe(()=>i.next(!1)));let r=0,s=(0,m.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,m.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return n&&!u}),(0,m.filterChanged)());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,m.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,l;let u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)==null?void 0:o.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,m.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),o=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":o?l?n?c="pip":u?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,m.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new m.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,m.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,m.filter)(i=>i.length>0),(0,m.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=Bt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,m.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,m.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,m.assertNonNullable)(this.providerContainer),(0,m.assertNonNullable)(e),kg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Rg(i)),this.providerContainer.current$.subscribe(({type:i})=>va("provider",i)),e.duration$.subscribe(i=>va("duration",i)),e.availableVideoTracks$.pipe((0,m.filter)(i=>!!i.length),(0,m.once)()).subscribe(i=>va("tracks",i)),this.events.fatalError$.subscribe(new He("fatalError")),this.events.managedError$.subscribe(new He("managedError")),e.position$.subscribe(new He("position")),e.currentVideoTrack$.pipe((0,m.map)(i=>i==null?void 0:i.quality)).subscribe(new He("quality")),this.info.currentBuffer$.subscribe(new He("buffer")),e.isBuffering$.subscribe(new He("isBuffering"))].forEach(i=>this.subscription.add(i)),va("codecs",X.video.supportedCodecs)}initTracerSubscription(){let e=(0,m.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,m.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,m.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,m.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,m.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,m.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,m.filter)(i=>i>0),(0,m.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,m.filter)(i=>i>0),(0,m.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,m.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,m.filter)(i=>i.end>0),(0,m.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,m.filterChanged)())}).pipe((0,m.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,m.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,m.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,m.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,m.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,m.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,m.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,m.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,m.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,m.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,m.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,m.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=()=>R(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:m.ErrorCategory.DOM,message:String(r)})})});this.subscription.add((0,m.merge)((0,m.fromEvent)(document,"visibilitychange"),(0,m.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,m.flattenObject)({quality:t,availableTracks:(0,m.flattenObject)(e),track:(0,m.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!wa()}};var Nt=require("@vkontakte/videoplayer-shared/es2015"),D$=`@vkontakte/videoplayer-core@${Ro}`;